Bundle: redb / redb.Templates (redb.Templates.txt), 472 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 Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt ==== Path: redb/redb.Templates/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/README.md ---- # RedBase Project Templates Create a new RedBase application in seconds: ```bash dotnet new install redb.Templates dotnet new redb -n MyApp cd MyApp dotnet run ``` Every project runs as is: SQLite creates its database file next to the app, and Pro is on. Pro is free of charge, no license key required. ## Templates | Short name | What it is | |------------|------------| | `redb` | Console app: create, load, update, query, tree | | `redb-razor` | Razor Pages site: list with search, sorting and paging, create / edit form | | `redb-blazor` | Blazor site (Interactive Server): products list and form, category tree | | `redb-worker` | Integration worker: folder inbox, XSD check, one transaction, receipt; own host or a Tsak module | | `redb-chat` | LLM chat with the history in RedBase; console and HTTP; options for tools and audit; own host or a Tsak module | | `redb-app` | Blazor WebAssembly client and a redb.Route REST API with sign-in (JWT); the API runs in its own host or as a Tsak module | | `redb-bff` | Blazor backend-for-frontend with a cookie session, and a backend of redb.Route controllers; the backend runs in its own host or as a Tsak module | | `redb-identity-app` | An application on redb.Identity: a Tsak module next to Identity in one worker, whose API checks bearer tokens by introspection over direct-vm, and a Blazor web server that signs users in with OpenID Connect. Options: `--web`, `--framework` | | `redb-route` | Tsak module with routes in XML markup: a timer route in XML and the same route in C#, the context configuration sample, packaging into `.tpkg` on build | | `redb-route-rest` | Tsak module with an HTTP JSON API in XML markup: `` with GET and POST, a JSON schema check, 400 on a bad body, OpenAPI; the same API in C# under `/api/cs` | | `redb-route-rabbitmq` | Tsak module for RabbitMQ in XML markup: one shared connection, a producer, a consumer with retries, a queue for the messages that still fail, request-reply in C#, a compose file for a local broker | | `redb-route-kafka` | Tsak module for Kafka in XML markup: one cluster connection, a keyed producer, a consumer group with retries, a topic for the records that still fail, payments with running totals in C#, a compose file for a local single-node Kafka | | `redb-route-eip` | Tsak module with the common integration patterns in XML markup, no broker needed: seda queue, idempotent consumer, throttle, wire tap, aggregator, content-based router, splitter, dead letter channel; the same chain in C# | | `redb-route-sql` | Tsak module with the SQL outbox pattern in XML markup: a route writes rows, a poll consumer marks each done or failed, a status report in C#; `--db sqlite` (default), `postgres` or `mssql` | | `redb-route-sql-batch` | Tsak module that writes to SQL in batches in XML markup: single messages aggregated into batches of 20, one transaction per batch, a refused row skipped and reported, a batch of typed records from C#; `--db sqlite` (default), `postgres` or `mssql` | | `redb-route-scatter-gather` | Tsak module with scatter-gather in XML markup: one request to three recipients in parallel, a timeout, the best answer picked; a second request in C# with its own strategy function; no broker needed | | `redb-route-validator-xslt` | Tsak module for XML documents in XML markup: an XSD check, an XSLT transformation, a rejected document routed with the reason; the same route in C# with LINQ to XML; no broker needed | | `redb-route-beans` | Tsak module whose XML routes call a C# class of the project: a bean built from configuration, a method with expression arguments, a method that takes the exchange; a second route in C# with the same bean; no broker needed | | `redb-route-xmljson` | Tsak module that turns XML into JSON and back without a class, in XML markup: an XSD decides arrays, numbers and booleans and, on the way back, namespaces and element order; an HTTP API that answers 400 for a body that is not an order; the same round trip in C#; no broker needed | | `redb-route-redb` | Tsak module that stores redb objects from XML routes: a props class of the project as the scheme, save by a unique key, query, a named redb instance on Pro with ChangeTracking and switchable caches, a typed LINQ report in C#; `--db sqlite` (default), `postgres` or `mssql` | | `redb-route-ldap` | Tsak module for LDAP in XML markup: a directory watch with an initial load, a search on a timer, a password check by bind, a user list in C#; a compose file with a seeded OpenLDAP | | `redb-route-s3` | Tsak module for S3 in XML markup: objects written to a bucket, a poll consumer that reads the new ones and moves them to an archive bucket, CSV price lists in C#; a compose file with an S3-compatible store | | `redb-route-email` | Tsak module that sends and reads e-mail in XML markup: an SMTP sender with retries, an IMAP reader that marks processed messages read, an HTML report sent from C#; a compose file with GreenMail | | `redb-route-file` | Tsak module for files in XML markup: an inbox polled for new files, done and error folders, a receipt per file, CSV files through an inbox of their own in C#; `--transport file` (default), `ftp` or `sftp`, with a compose file for a local FTP or SFTP server | | `redb-route-cron` | Tsak module with scheduled jobs in XML markup: a Quartz cron job with a time zone, no overlapping runs and a misfire rule, and a Quartz interval, a cleanup job in C#; no broker needed | | `redb-route-amqp` | Tsak module for AMQP 1.0 in XML markup (ActiveMQ Artemis, Qpid, Azure Service Bus and others): one connection, a producer, a consumer with retries, a queue for the messages that still fail, request-reply in C#; a compose file with Artemis | | `redb-route-mqtt` | Tsak module for MQTT 3.1.1 and 5 in XML markup: test sensors publishing with QoS 1, a retained status, a subscriber with topic wildcards that forwards readings over a limit, humidity averages in C#; a compose file with Mosquitto | | `redb-route-as2` | Tsak module for AS2 in XML markup: sends a signed and encrypted document and verifies the signed MDN, receives with duplicate detection, XML invoices sent from C#; a compose file for a local exchange with OpenAS2 | | `redb-route-as4` | Tsak module for AS4 (eDelivery) in XML markup: sends a signed and encrypted message and verifies the partner's signed receipt, receives with duplicate detection, credit notes sent from C#; a compose file for a local exchange with Holodeck B2B | Every template configures RedBase the same way: with Pro, the PVT prefilter and change tracking are on, the props cache is off and the comment next to it shows how to turn it on. Every `redb-route-*` module shows its scenario in both forms a real project mixes: the XML route files, and a `RouteBuilder` in `routes/*.cs` that `` in `context.xml` adds to the same context, with the same beans and configuration keys. The C# routes have ids that start with `cs-` and triggers, queues and folders of their own, so the two forms never consume the same message twice. ## `redb`: console app ### Parameters | Parameter | Values | Default | Description | |-----------|--------|---------|-------------| | `--db` | `sqlite`, `postgres`, `mssql` | `sqlite` | Database provider | | `--pro` | `true`, `false` | `true` | Pro packages: compiled LINQ, change tracking, aggregation | ### Examples ```bash # SQLite + Pro (default) dotnet new redb -n MyApp # SQLite + Free dotnet new redb -n MyApp --pro false # PostgreSQL + Pro dotnet new redb -n MyApp --db postgres # SQL Server + Free dotnet new redb -n MyApp --db mssql --pro false ``` For PostgreSQL and SQL Server, put your password into the connection string in `Program.cs` first. The database named there must already exist: the app creates the RedBase tables in it, not the database itself. ### What you get A console app that walks through the basics: - **Initialize** — `InitializeAsync(ensureCreated: true)` creates the RedBase tables on the first run and syncs the schemes of your classes - **Create, load, update, delete** — `RedbObject` with typed properties, an array among them - **Query** — LINQ over your own properties: `Query().Where(...).OrderByDescending(...)` - **Aggregation (Pro)** — `AverageAsync` computed in the database - **Tree** — a three-level category hierarchy with `CreateChildAsync` and `LoadTreeAsync`; deleting the root deletes its children To switch the database later, follow the comments in `RedbApp.csproj` and `Program.cs`. ## Links - Documentation (EN): [redbase.app](https://redbase.app) - Documentation (RU): [redb.ru](https://redb.ru) - API Reference: [redbase-app.github.io/redb](https://redbase-app.github.io/redb/) - Quick Start: [redbase.app/quick-start](https://redbase.app/quick-start) - GitHub: [github.com/redbase-app/redb](https://github.com/redbase-app/redb) - NuGet: [nuget.org/packages/redb.Templates](https://www.nuget.org/packages/redb.Templates) Path: redb/redb.Templates/redb.Templates.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/redb.Templates.csproj ---- Template redb.Templates 4.8.0 RedBase Project Templates RedBase RedBase Project templates for RedBase (REDB), the entity database for .NET: a console app (dotnet new redb), a Razor Pages site (redb-razor), a Blazor site (redb-blazor), an integration worker (redb-worker), an LLM chat (redb-chat), a Blazor WebAssembly app with a redb.Route API (redb-app), a Blazor BFF with redb.Route controllers (redb-bff), an application on redb.Identity (redb-identity-app: a module beside Identity with token introspection in process, and an OpenID Connect web server) and Tsak modules with routes in XML markup next to the same routes in C# (redb-route, and redb-route-rest, -rabbitmq, -kafka, -sql, -sql-batch, -eip, -scatter-gather, -validator-xslt, -xmljson, -beans, -redb, -ldap, -s3, -email, -file, -cron, -amqp, -mqtt, -as2, -as4 for one scenario each). The database ones run as is on SQLite with Pro; the route-based ones also deploy as Tsak modules. dotnet-new;templates;redbase;redb;database;entity;tree;linq;blazor;razor;worker;llm;bff;tsak;xml;routes;identity;oidc https://redbase.app README.md https://github.com/redbase-app/redb git Copyright (c) 2024-2026 RedBase true false content true net10.0 true true $(TargetsForTfmSpecificContentInPackage);AddRouteXmlSharedFiles <_RouteXmlTemplateDir Include="@(RouteXmlTemplate->'%(RecursiveDir)'->Replace('.template.config\', '')->Replace('.template.config/', ''))" /> <_RouteXmlSharedCopy Include="@(RouteXmlSharedFile)" TemplateDir="%(_RouteXmlTemplateDir.Identity)" /> <_RouteXmlAgents Include="@(_RouteXmlTemplateDir->'$(IntermediateOutputPath)route-xml\%(Identity)AGENTS.md')" TemplateDir="%(Identity)" Scenario="templates\route-xml\%(Identity).template.config\agents-scenario.md" /> Path: redb/redb.Templates/scripts/smoke-templates.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/scripts/smoke-templates.ps1 ---- <# .SYNOPSIS Generates a project from every template of the redb.Templates pack, with each option that changes the code, and builds it. .DESCRIPTION Installs the given template pack, runs `dotnet new` for each case of $Cases into a temporary folder, then `dotnet build` and, per case, one behavioural check: a console app is started and its output is read, a web site is started and a page is checked, the worker's module is packed and the package is inspected, the chat is started without an API key and must refuse to run without leaving a database behind. Before a release is on nuget.org, pass -LocalFeed with the folder that holds the freshly built redb.* packages: a nuget.config pointing at it is written next to the generated projects, and the restored packages go to /packages instead of the global NuGet cache. .EXAMPLE ./smoke-templates.ps1 -PackagePath ../../nupkg/redb.Templates.4.2.1.nupkg -LocalFeed ../../nupkg ./smoke-templates.ps1 -PackagePath ../../nupkg/redb.Templates.4.2.1.nupkg -Only redb-chat #> param( [Parameter(Mandatory = $true)] [string] $PackagePath, [string] $LocalFeed, # Short names to run; empty runs every case. [string[]] $Only = @(), [string] $WorkDir = (Join-Path ([System.IO.Path]::GetTempPath()) "redb-templates-smoke") ) $ErrorActionPreference = 'Stop' # pwsh -File passes "-Only a,b" as ONE element; split it like the other release scripts do. Without this a list # matched no template, no case ran, and the run still ended with "All cases passed". $Only = @($Only | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) # Build nodes keep output files locked between runs, which breaks the cleanup of the work directory. $env:MSBUILDDISABLENODEREUSE = '1' # Every template, and every option that puts different code into the project. # RunDll / ExpectOut - start the built app (relative to the project folder) and check its output # ExpectFail - the app must stop with an error instead of starting # Web / WebProject - start the site, wait for the url and check the answer with Assert # Pack / PackHas - run deploy/pack-tpkg.ps1 and check what the package holds, PackHas: files it must carry # ModuleMaxTfm - the highest framework the packed module may target (net10.0, the runtime of the Tsak # worker), read from the module assembly inside the package of Pack or RoutePack $Cases = @( @{ Id = 'redb'; Template = 'redb'; Args = @(); RunDll = 'bin/Release/net10.0/SmokeApp.dll'; ExpectOut = 'Cleaned up. Done!' } @{ Id = 'redb-free'; Template = 'redb'; Args = @('--pro', 'false'); RunDll = 'bin/Release/net10.0/SmokeApp.dll'; ExpectOut = 'Cleaned up. Done!' } @{ Id = 'redb-postgres'; Template = 'redb'; Args = @('--db', 'postgres') } @{ Id = 'redb-mssql'; Template = 'redb'; Args = @('--db', 'mssql') } @{ Id = 'redb-razor'; Template = 'redb-razor'; Args = @(); Web = 'http://localhost:5080/'; WebProject = '.' Assert = { param($page) # The decimal price is parsed and printed with the invariant culture: a site on a machine # with a comma locale must answer the same as everywhere else (see the README, "Culture"). if ($page.Content -notmatch '1299\.00') { throw 'the price list does not use the invariant culture' } } } @{ Id = 'redb-blazor'; Template = 'redb-blazor'; Args = @(); Web = 'http://localhost:5081/'; WebProject = '.' Assert = { param($page) if ($page.Content -notmatch '5 product\(s\)') { throw 'the product list did not render' } if ($page.Content -notmatch 'prerenderId') { throw 'the page was not prerendered' } } } @{ Id = 'redb-worker'; Template = 'redb-worker'; Args = @(); Pack = $true } @{ Id = 'redb-chat'; Template = 'redb-chat'; Args = @(); ExpectFail = $true; RunDll = 'SmokeApp.Host/bin/Release/net10.0/SmokeApp.Host.dll' ExpectOut = 'The LLM API key is not set'; NoFiles = '*.db' } @{ Id = 'redb-chat-shell'; Template = 'redb-chat'; Args = @('--tools', 'shell'); ExpectFail = $true; RunDll = 'SmokeApp.Host/bin/Release/net10.0/SmokeApp.Host.dll' ExpectOut = 'The LLM API key is not set'; NoFiles = '*.db' } @{ Id = 'redb-chat-mcp-audit'; Template = 'redb-chat'; Args = @('--tools', 'mcp', '--audit', 'true'); ExpectFail = $true; RunDll = 'SmokeApp.Host/bin/Release/net10.0/SmokeApp.Host.dll' ExpectOut = 'The LLM API key is not set'; NoFiles = '*.db' } @{ Id = 'redb-app'; Template = 'redb-app'; Args = @(); Web = 'http://localhost:5082/'; WebProject = 'SmokeApp.Web' Assert = { param($page) # .NET 10 serves the client with an import map and fingerprinted names (see the template). if ($page.Content -notmatch 'type="importmap"') { throw 'the client index.html has no import map' } if ($page.Content -notmatch 'blazor\.webassembly\.[0-9a-z]+\.js') { throw 'the client loader is not fingerprinted' } } } @{ Id = 'redb-bff'; Template = 'redb-bff'; Args = @(); Web = 'http://localhost:5083/login'; WebProject = 'SmokeApp.Web' Assert = { param($page) if ($page.Content -notmatch ' "@ | Set-Content -Path (Join-Path $WorkDir 'nuget.config') -Encoding utf8 # The packages restored from the local feed must not land in the global cache: there they would stand in # for the published packages of the same version on every later restore of this machine. They go to a # folder of the work directory, which the next run removes with it. Restored paths run to ~190 # characters below this folder, so a long -WorkDir hits MAX_PATH and the build loses its references. $env:NUGET_PACKAGES = Join-Path $WorkDir 'packages' } # `dotnet new install --force` over an installed pack of the same id adds a second entry instead of replacing # it, and every `dotnet new` of its templates then fails with "Sequence contains more than one matching # element" (exit 70). Every entry of the id goes first; it is redb.Templates, whichever source it came from. for ($i = 0; $i -lt 5; $i++) { dotnet new uninstall redb.Templates *> $null; if ($LASTEXITCODE -ne 0) { break } } Invoke-Checked "dotnet new install" { dotnet new install $PackagePath } function Wait-ForUrl([string] $url, [int] $TimeoutSeconds = 90) { $deadline = (Get-Date).AddSeconds($TimeoutSeconds) while ((Get-Date) -lt $deadline) { try { $answer = Invoke-WebRequest $url -UseBasicParsing -TimeoutSec 5 -SkipHttpErrorCheck if ($answer.StatusCode -lt 500) { return $answer } } catch { } Start-Sleep -Milliseconds 500 } throw "no answer from $url within $TimeoutSeconds s" } # `dotnet run` leaves the app it started behind, so the whole tree goes. Process.Kill(true) does that on Windows and # Linux alike (the CIM query it replaces existed on Windows only, and the smoke could not run in the SDK container). function Stop-ProcessTree([int] $ProcessId) { try { [Diagnostics.Process]::GetProcessById($ProcessId).Kill($true) } catch { } } # The pack script must put the module and its own dependencies in the package and nothing the worker # already ships, which is what deploy/shipped-module-deps.txt lists. # A Route-XML module packed by its build: pkg/-0.0.1.tpkg, and the context name the template was asked for # in pkg/-0.0.1/.config.json. function Invoke-RoutePackCheck([string] $ProjectDir, [string] $Name, [hashtable] $Expect) { $package = Join-Path $ProjectDir "pkg/$Name-0.0.1.tpkg" if (-not (Test-Path $package)) { throw "the build produced no pkg/$Name-0.0.1.tpkg" } # Every redb-route-* carries an AGENTS.md assembled at pack time (route-xml/_agents + the scenario part of the # template). Its placeholders must be replaced by the template engine like everywhere else in the project. $agents = Join-Path $ProjectDir 'AGENTS.md' if (-not (Test-Path $agents)) { throw 'the project has no AGENTS.md' } $agentsText = Get-Content $agents -Raw $left = @('modulectx', 'routemodule', 'RouteModule' | Where-Object { $agentsText -cmatch "\b$_\b" }) if ($left.Count -gt 0) { throw "AGENTS.md still carries the template placeholder(s): $($left -join ', ')" } if ($Expect.ContextName) { $config = Join-Path $ProjectDir "pkg/$Name-0.0.1/$Name.config.json" if (-not (Test-Path $config)) { throw "no pkg/$Name-0.0.1/$Name.config.json" } $context = (Get-Content $config -Raw | ConvertFrom-Json).ContextName if ($context -ne $Expect.ContextName) { throw "ContextName is '$context', expected '$($Expect.ContextName)'" } } if ($Expect.RequiredConfigKey -or $Expect.RequiredConfigKeys -or $Expect.NoRequiredConfigKeys) { $manifest = Join-Path $ProjectDir "pkg/$Name-0.0.1/manifest.json" if (-not (Test-Path $manifest)) { throw "no pkg/$Name-0.0.1/manifest.json" } $keys = @((Get-Content $manifest -Raw | ConvertFrom-Json).RequiredConfigKeys | Where-Object { $_ }) # RequiredConfigKeys: the exact set, in any order; a key short or one too many both fail. if ($Expect.RequiredConfigKeys) { $diff = @(Compare-Object @($Expect.RequiredConfigKeys) $keys) if ($diff.Count -gt 0) { throw "RequiredConfigKeys is [$($keys -join ', ')], expected [$($Expect.RequiredConfigKeys -join ', ')]" } } if ($Expect.RequiredConfigKey -and $keys -notcontains $Expect.RequiredConfigKey) { throw "RequiredConfigKeys has no $($Expect.RequiredConfigKey) (has: $($keys -join ', '))" } # A module that needs no key must not ask for one: the worker would refuse to start it. if ($Expect.NoRequiredConfigKeys -and $keys.Count -gt 0) { throw "RequiredConfigKeys should be empty, has: $($keys -join ', ')" } } if ($Expect.Entries) { # Resources the routes read at run time travel inside the package, not next to it. Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [IO.Compression.ZipFile]::OpenRead($package) try { $inside = @($zip.Entries | ForEach-Object { $_.FullName -replace '\\', '/' }) } finally { $zip.Dispose() } $missing = @($Expect.Entries | Where-Object { $inside -notcontains $_ }) if ($missing.Count -gt 0) { throw "the package has no $($missing -join ', ')" } } if ($Expect.PackageRef) { $csproj = Join-Path $ProjectDir 'SmokeApp.csproj' if ((Get-Content $csproj -Raw) -notmatch ('[^"]+)"') | ForEach-Object { $_.Groups['v'].Value } | Sort-Object -Unique) if ($providers.Count -eq 0) { throw 'context.sample.json names no Provider' } if (@($providers | Where-Object { $_ -ne $Expect.SampleProvider }).Count -gt 0) { throw "context.sample.json Provider is $($providers -join ', '), expected $($Expect.SampleProvider)" } } if ($Expect.Provider) { $contextXml = Join-Path $ProjectDir "pkg/$Name-0.0.1/context.xml" if (-not (Test-Path $contextXml)) { throw "no pkg/$Name-0.0.1/context.xml" } $text = Get-Content $contextXml -Raw if ($text -match '#if\b') { throw 'context.xml still carries #if: the template conditions were not resolved' } # of the redb.Route XML, or an attribute ProviderName="...". $declared = @([regex]::Matches($text, 'key\s*=\s*"ProviderName"\s+value\s*=\s*"(?[^"]+)"|\bProviderName\s*=\s*"(?[^"]+)"') | ForEach-Object { $_.Groups['v'].Value } | Sort-Object -Unique) if ($declared.Count -eq 0) { throw 'context.xml declares no ProviderName' } if (@($declared | Where-Object { $_ -ne $Expect.Provider }).Count -gt 0) { throw "ProviderName is $($declared -join ', '), expected $($Expect.Provider)" } } Write-Host (" package: pkg/{0}-0.0.1.tpkg, {1:N0} KB" -f $Name, ((Get-Item $package).Length / 1KB)) -ForegroundColor DarkGray } function Invoke-PackageCheck([string] $ProjectDir, [string] $PackageName, [string] $ModuleDll, [string[]] $MustHave = @()) { Push-Location $ProjectDir try { & (Join-Path $ProjectDir 'deploy/pack-tpkg.ps1') | Out-Null $package = Join-Path $ProjectDir ('deploy/output/' + $PackageName) if (-not (Test-Path $package)) { throw "the pack script produced no $PackageName" } Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [IO.Compression.ZipFile]::OpenRead($package) try { $names = @($zip.Entries | ForEach-Object { $_.Name }) $shipped = @(Get-Content (Join-Path $ProjectDir 'deploy/shipped-module-deps.txt') | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $repeated = @($names | Where-Object { $shipped -contains $_ }) if ($repeated.Count -gt 0) { throw "the package repeats what the worker ships: $($repeated -join ', ')" } if ($names -notcontains $ModuleDll) { throw "$ModuleDll is not in the package" } if ($names -notcontains 'manifest.json') { throw 'manifest.json is not in the package' } $absent = @($MustHave | Where-Object { $names -notcontains $_ }) if ($absent.Count -gt 0) { throw "the package has no $($absent -join ', ')" } if (-not (Test-Path ($package + '.contents.txt'))) { throw 'the package contents list was not written' } Write-Host " package: $($names.Count) entries" -ForegroundColor DarkGray } finally { $zip.Dispose() } } finally { Pop-Location } } # A module loads into the Tsak worker, so it must not target a framework above the worker's runtime: the package # builds and packs either way, and only the worker would refuse it. The framework is the TargetFrameworkAttribute # of the module assembly as it sits in the package (".NETCoreApp,Version=v10.0"). function Assert-ModuleFramework([string] $Package, [string] $ModuleDll, [string] $MaxTfm) { if ($MaxTfm -notmatch '^net(\d+)\.(\d+)$') { throw "ModuleMaxTfm '$MaxTfm' is not a netX.Y framework" } $max = [version]"$($Matches[1]).$($Matches[2])" Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [IO.Compression.ZipFile]::OpenRead($Package) try { $entry = @($zip.Entries | Where-Object { $_.Name -eq $ModuleDll }) | Select-Object -First 1 if (-not $entry) { throw "$ModuleDll is not in the package" } $bytes = [IO.MemoryStream]::new() $stream = $entry.Open() try { $stream.CopyTo($bytes) } finally { $stream.Dispose() } } finally { $zip.Dispose() } $bytes.Position = 0 $pe = [Reflection.PortableExecutable.PEReader]::new($bytes) try { $md = [Reflection.Metadata.PEReaderExtensions]::GetMetadataReader($pe) $framework = $null foreach ($handle in $md.GetAssemblyDefinition().GetCustomAttributes()) { $attribute = $md.GetCustomAttribute($handle) if ($attribute.Constructor.Kind -ne [Reflection.Metadata.HandleKind]::MemberReference) { continue } $parent = $md.GetMemberReference([Reflection.Metadata.MemberReferenceHandle]$attribute.Constructor).Parent if ($parent.Kind -ne [Reflection.Metadata.HandleKind]::TypeReference) { continue } if ($md.GetString($md.GetTypeReference([Reflection.Metadata.TypeReferenceHandle]$parent).Name) -ne 'TargetFrameworkAttribute') { continue } # Blob: prolog 01 00, then the string with a one-byte length (a framework name is shorter than 128). $blob = $md.GetBlobBytes($attribute.Value) $framework = [Text.Encoding]::UTF8.GetString($blob, 3, $blob[2]) break } } finally { $pe.Dispose() } if (-not $framework) { throw "$ModuleDll carries no TargetFrameworkAttribute" } if ($framework -notmatch '^\.NETCoreApp,Version=v(\d+\.\d+)$') { throw "$ModuleDll targets '$framework', not .NETCoreApp" } if ([version]$Matches[1] -gt $max) { throw "$ModuleDll targets $framework, above ${MaxTfm}: the worker cannot load it" } Write-Host " module framework: $framework (at most $MaxTfm)" -ForegroundColor DarkGray } $failed = @() $ran = 0 foreach ($case in $Cases) { if ($Only.Count -gt 0 -and $Only -notcontains $case.Template) { continue } $ran++ $id = $case.Id $out = Join-Path $WorkDir $id Write-Host "=== $id ===" -ForegroundColor Cyan try { $newArgs = @($case.Template, '-n', 'SmokeApp', '-o', $out) + $case.Args Invoke-Checked "dotnet new $id" { dotnet new @newArgs } $buildArgs = @($out, '-c', 'Release') if ($case.RoutePack) { $buildArgs += '-p:PackRouteOnBuild=true', '-p:Version=0.0.1' } Invoke-Checked "dotnet build $id" { dotnet build @buildArgs } if ($case.RoutePack) { Invoke-RoutePackCheck $out 'smokeapp' $case.RoutePack } if ($case.Web) { $projectDir = if ($case.WebProject -eq '.') { $out } else { Join-Path $out $case.WebProject } $env:ASPNETCORE_ENVIRONMENT = 'Development' # -NoNewWindow: without it Windows gives the site a console window of its own, which pops up on the # desktop of whoever runs the smoke. The output goes to the two logs either way. $site = Start-Process dotnet -ArgumentList @('run', '-c', 'Release', '--no-build', '--project', $projectDir) -PassThru ` -NoNewWindow -RedirectStandardOutput (Join-Path $out 'smoke.out.log') -RedirectStandardError (Join-Path $out 'smoke.err.log') try { $answer = Wait-ForUrl $case.Web & $case.Assert $answer } finally { Stop-ProcessTree $site.Id } } if ($case.RunDll -or $case.ExpectFail) { Push-Location $out try { $output = (& dotnet $case.RunDll 2>&1 | Out-String) Write-Host $output -ForegroundColor DarkGray if ($case.ExpectFail -and $LASTEXITCODE -eq 0) { throw 'the app was expected to stop with an error, it started instead' } if ($case.RunDll -and -not $case.ExpectFail -and $LASTEXITCODE -ne 0) { throw "the app exited with $LASTEXITCODE" } if ($case.ExpectOut -and $output -notmatch $case.ExpectOut) { throw "the output has no '$($case.ExpectOut)'" } if ($case.NoFiles) { $left = @(Get-ChildItem -Path $out -Filter $case.NoFiles -ErrorAction SilentlyContinue) if ($left.Count -gt 0) { throw "the app created $($left[0].Name) before it stopped" } } } finally { Pop-Location } } if ($case.Pack) { Invoke-PackageCheck $out 'SmokeApp.tpkg' 'SmokeApp.Module.dll' @($case.PackHas | Where-Object { $_ }) } if ($case.ModuleMaxTfm) { if ($case.Pack) { Assert-ModuleFramework (Join-Path $out 'deploy/output/SmokeApp.tpkg') 'SmokeApp.Module.dll' $case.ModuleMaxTfm } elseif ($case.RoutePack) { Assert-ModuleFramework (Join-Path $out 'pkg/smokeapp-0.0.1.tpkg') 'SmokeApp.dll' $case.ModuleMaxTfm } else { throw 'ModuleMaxTfm needs Pack or RoutePack: there is no package to read the module from' } } Write-Host "OK $id" -ForegroundColor Green } catch { Write-Host "FAIL $id : $($_.Exception.Message)" -ForegroundColor Red $failed += $id } } if ($ran -eq 0) { throw "No case ran: -Only $($Only -join ', ') matches no template of the cases list." } if ($failed.Count -gt 0) { throw "Failed cases: $($failed -join ', ')" } Write-Host "All $ran case(s) passed." -ForegroundColor Green Path: redb/redb.Templates/templates/redb-app/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/.dockerignore ---- **/bin/ **/obj/ *.db *.db-shm *.db-wal deploy/output/ deploy/.env Path: redb/redb.Templates/templates/redb-app/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Web", "Blazor", "WebAssembly", "API", "Database", "RedBase" ], "identity": "RedBase.App.Template", "name": "RedBase Blazor WebAssembly App with a redb.Route API", "description": "A Blazor WebAssembly client and a redb.Route REST API with JWT sign-in on redb; the API runs in its own host or as a Tsak module.", "shortName": "redb-app", "tags": { "language": "C#", "type": "solution" }, "sourceName": "RedbApp", "preferNameDirectory": true, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/redb-app/Directory.Build.props Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/Directory.Build.props ---- net10.0 enable enable 4.8.0 false Path: redb/redb.Templates/templates/redb-app/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/README.md ---- # RedbApp A Blazor WebAssembly application with an API on redb.Route and RedBase: sign-in, a product list with search, sorting and paging, a create / edit form, and a category tree. SQLite with Pro, so it runs as is. Two processes, as in production: the API, and the client that runs in the browser. The API is a module that runs in its own host or on a Tsak worker. ## Run In two terminals, from the project folder: ```bash dotnet run --project RedbApp.Host # the API on http://localhost:5092 dotnet run --project RedbApp.Web # the client on http://localhost:5082 ``` Open http://localhost:5082 and sign in as `admin` / `admin`. On the first run the API creates `redbapp.db`, builds the RedBase tables and adds sample products and categories. Or both in containers: `cp deploy/.env.example deploy/.env`, set `APP_SIGNING_KEY` and `APP_ADMIN_PASSWORD`, then `docker compose -f deploy/docker-compose.yml up --build` and open http://localhost:8080. ## Projects | Project | What it is | |---------|------------| | `RedbApp.Models` | What the API and the browser exchange. No RedBase: the client references it | | `RedbApp.Api` | The module: `InitRoute.main`, the REST routes, the redb Props classes, the services | | `RedbApp.Host` | The API's own host: redb registration and settings, then `InitRoute.main` | | `RedbApp.Web` | The Blazor WebAssembly client | ## Where things are | File | What it does | |------|--------------| | `RedbApp.Api/Routes/AuthRouteBuilder.cs` | `POST /api/auth/login` -> a signed token | | `RedbApp.Api/Auth/JwtTokens.cs` | Issues the token, and checks it on every other call as the `IHttpTokenValidator` | | `RedbApp.Api/Routes/ApiRouteBuilder.cs` | The REST declarations: each verb forwards to a `direct:` route | | `RedbApp.Api/Services/ProductService.cs` | Search, sorting and paging in the database; create, update, delete | | `RedbApp.Api/Services/CategoryService.cs` | The tree: roots, subtrees, add a node, delete a subtree | | `RedbApp.Api/RedbApp.Api.config.json` | Host, port, CORS origin, token issuer and lifetime | | `RedbApp.Host/appsettings.json` | `ConnectionStrings:Redb`, the signing key and the users (the `Override` layer) | | `RedbApp.Web/Services/ApiClient.cs` | The API calls; the token goes with each one, a 401 ends the session | | `RedbApp.Web/wwwroot/appsettings.Development.json` | Where the client finds the API in development | ## Sign-in `POST /api/auth/login` checks the login and password and returns a JWT signed with `Auth:SigningKey`. Every other route of the API is declared with `InboundAuth = Bearer`: a request without a valid token gets 401 before the route runs, an accepted one carries the user on the exchange (`ExchangePrincipal.Get(exchange)`). The users live in configuration (`Auth:Users`), a stand-in that keeps the template small. A real application keeps them in a store of its own, for example redb.Identity. The signing key in `RedbApp.Host/appsettings.json` is for your machine only: set your own through the environment everywhere else (`Tsak__Contexts__redbapp__Override__Auth__SigningKey`). ## Settings The module reads its settings from its route context. Both hosts fill it the same way: the module's config file first, then `Tsak:Contexts:redbapp:Override`, which wins. So an environment variable works the same in the own host and on a Tsak worker. In development the client runs on another port, so the API answers CORS for `Api:CorsOrigins`. In a deployment nginx serves the client and forwards `/api/` to the API (`RedbApp.Web/nginx.conf`): one origin, no CORS. ## RedBase settings `RedbApp.Host/Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. On Tsak the same settings are environment variables of the worker (`Tsak__Redb__...`, see `deploy/docker-compose.tsak.yml`). The compose file sets no `Tsak__Cluster__NodeId`: a worker is named after its container's host name, so every replica of `docker compose up --scale` is a Tsak node of its own. Set an explicit id only for a single instance or a StatefulSet; two live workers with one id are refused. ## Another database 1. In `RedbApp.Host.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy All compose files read `deploy/.env` (copy it from `deploy/.env.example`). Run them from the project folder; each has the commands at the top. | File | What runs | |------|-----------| | `deploy/docker-compose.yml` | The API in its own host with SQLite, and the client behind nginx | | `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml` | The same with a database server; switch the provider first (see above) | | `deploy/docker-compose.tsak.yml` | The API as a module on the Tsak stack image, and the client behind nginx. Pack the module first: `pwsh deploy/pack-tpkg.ps1` | The images: `RedbApp.Host/Dockerfile` (the API) and `RedbApp.Web/Dockerfile` (the client in nginx), both built from the project folder. `pack-tpkg.ps1` puts the manifest, the module config, the module DLL and every dependency the worker does not ship itself into the package; `deploy/shipped-module-deps.txt` lists what the worker provides, and `deploy/output/RedbApp.tpkg.contents.txt` shows what went in. To run the module on a Tsak host built locally from the `tsak-worker` template, drop the assemblies that host lacks (`redb.Route.File.dll`, `redb.Route.GenericFile.dll`, ...) into its `Libs/shared`: the host resolves a module's shared assemblies from `Libs/shared` next to the application, and that template copies `Libs/**` to its output. Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Auth/JwtTokens.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Auth/JwtTokens.cs ---- using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using redb.Route.Http; namespace RedbApp.Api.Auth; /// /// Issues the sign-in token and checks it on every API call. One key signs and verifies (HMAC-SHA256), so /// the API is the only party that can do either. /// /// As an it is registered in the route registry and named by /// TokenValidator on the REST declarations: a request without a valid token gets 401 and never /// reaches the route; an accepted one reaches it with the principal on the exchange /// (ExchangePrincipal.Get). /// /// public sealed class JwtTokens(ModuleSettings settings) : IHttpTokenValidator { public const string RegistryName = "tokens"; private readonly JsonWebTokenHandler _handler = new(); private readonly SymmetricSecurityKey _key = new(Encoding.UTF8.GetBytes(settings.SigningKey)); public (string Token, DateTimeOffset ExpiresAt) Issue(AppUser user) { var expires = DateTime.UtcNow.AddMinutes(settings.TokenLifetimeMinutes); var token = _handler.CreateToken(new SecurityTokenDescriptor { Issuer = settings.Issuer, Audience = settings.Issuer, Expires = expires, Subject = new ClaimsIdentity([ new Claim(JwtRegisteredClaimNames.Sub, user.Login), new Claim("role", user.Role), ]), SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256), }); return (token, expires); } public async Task ValidateAsync(string token, CancellationToken ct) { var result = await _handler.ValidateTokenAsync(token, new TokenValidationParameters { ValidIssuer = settings.Issuer, ValidAudience = settings.Issuer, IssuerSigningKey = _key, ValidateLifetime = true, NameClaimType = JwtRegisteredClaimNames.Sub, RoleClaimType = "role", }); return result.IsValid ? new ClaimsPrincipal(result.ClaimsIdentity) : null; } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/InitRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using RedbApp.Api.Auth; using RedbApp.Api.Props; using RedbApp.Api.Routes; namespace RedbApp.Api; /// /// The module's entry point. A Tsak worker finds it by convention (a public static class /// InitRoute with a main(IRouteContext) method) and awaits it when the module loads; /// RedbApp.Host calls the same method, so the API exists once. /// Order: settings, components, the token validator, the database, then the routes. /// public static class InitRoute { public static async Task main(IRouteContext context) { var settings = ModuleSettings.FromContext(context); 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. The host registers it: the Tsak worker does, and // so does RedbApp.Host (AddRedbRouteHttpHosting). if (!context.HasComponent("http")) context.AddComponent(new HttpComponent { ServerManager = services.GetRequiredService() }); // The REST declarations name the validator by its registry name. var tokens = new JwtTokens(settings); context.AddToRegistry(JwtTokens.RegistryName, tokens); // The module's schemes and the sample data, through a scope of its own: the connection goes back to // the pool as soon as this is done. Every ProcessWithRedb step gets its own IRedbService the same way. await using (var scope = services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await SeedAsync(redb); } var routes = (RouteContext)context; routes.AddRoutes(new AuthRouteBuilder(settings, tokens)); routes.AddRoutes(new ApiRouteBuilder(settings)); context.GetService()?.CreateLogger("RedbApp").LogInformation( "RedbApp API ready on {Host}:{Port}, {Users} user(s)", settings.ApiHost, settings.ApiPort, settings.Users.Count); return context; } // Sample data on the first run, so the pages are not empty. private static async Task SeedAsync(IRedbService redb) { if (!await redb.Query().AnyAsync()) { var samples = new (string Name, string Category, decimal Price, bool InStock)[] { ("Laptop 14", "Laptops", 1299m, true), ("Laptop 16", "Laptops", 1899m, false), ("Monitor 27", "Monitors", 349m, true), ("Keyboard", "Accessories", 79m, true), ("Mouse", "Accessories", 39m, true), }; foreach (var s in samples) { await redb.SaveAsync(new RedbObject { Name = s.Name, Props = new Product { Category = s.Category, Price = s.Price, InStock = s.InStock }, }); } } if (!await redb.TreeQuery().AnyAsync()) { var root = new TreeRedbObject { Name = "Electronics", Props = new Category { SortOrder = 1 } }; await redb.SaveAsync(root); var computers = new TreeRedbObject { Name = "Computers", Props = new Category { SortOrder = 1 } }; await redb.CreateChildAsync(computers, root); await redb.CreateChildAsync(new TreeRedbObject { Name = "Laptops", Props = new Category { SortOrder = 1 } }, computers); await redb.CreateChildAsync(new TreeRedbObject { Name = "Monitors", Props = new Category { SortOrder = 2 } }, root); } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/ModuleSettings.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/ModuleSettings.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RedbApp.Api; /// /// The module's settings, read from the properties of its route context. Both hosts fill them the same /// way: RedbApp.Api.config.json first, then the Tsak:Contexts:{context}:Override section of the host /// configuration, which wins. The signing key and the users belong only in the Override layer /// (RedbApp.Host appsettings.json, or environment variables such as /// Tsak__Contexts__redbapp__Override__Auth__SigningKey), never in the module's config file. /// public sealed record ModuleSettings( string ApiHost, int ApiPort, string CorsOrigins, string Issuer, int TokenLifetimeMinutes, string SigningKey, IReadOnlyDictionary Users) { public static ModuleSettings FromContext(IRouteContext context) { var api = Section(context, "Api"); var auth = Section(context, "Auth"); var signingKey = Required(context, auth, "Auth", "SigningKey"); // HMAC-SHA256 needs a key of at least 256 bits. if (System.Text.Encoding.UTF8.GetByteCount(signingKey) < 32) throw new InvalidOperationException($"Auth:SigningKey of context '{context.ContextId}' must be at least 32 characters."); var users = auth.TryGetValue("Users", out var raw) && raw is IDictionary section ? section.ToDictionary( u => u.Key, u => AppUser.From(context, u.Key, u.Value as IDictionary), StringComparer.OrdinalIgnoreCase) : throw Missing(context, "Auth:Users"); return new( ApiHost: Required(context, api, "Api", "Host"), ApiPort: int.Parse(Required(context, api, "Api", "Port"), CultureInfo.InvariantCulture), // The origin of the Blazor client when it is served from another port or host. Behind one // reverse proxy (deploy/nginx.conf) the browser sees one origin and CORS is not used. CorsOrigins: Required(context, api, "Api", "CorsOrigins"), Issuer: Required(context, auth, "Auth", "Issuer"), TokenLifetimeMinutes: int.Parse(Required(context, auth, "Auth", "TokenLifetimeMinutes"), CultureInfo.InvariantCulture), SigningKey: signingKey, Users: users); } internal static IDictionary Section(IRouteContext context, string name) => context.GetProperty>(name) ?? throw Missing(context, name); internal static string Required(IRouteContext context, IDictionary? section, string sectionName, string key) => section is not null && section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text ? text : throw Missing(context, $"{sectionName}:{key}"); internal static InvalidOperationException Missing(IRouteContext context, string key) => new( $"{key} is not configured for context '{context.ContextId}': set it in RedbApp.Api.config.json " + $"or in Tsak:Contexts:{context.ContextId}:Override."); } /// /// A user who can sign in. The users come from configuration: a stand-in that keeps the template small. /// A real application keeps its users in a store of its own, for example redb.Identity. /// public sealed record AppUser(string Login, string Password, string Role) { internal static AppUser From(IRouteContext context, string login, IDictionary? section) => new( login, ModuleSettings.Required(context, section, $"Auth:Users:{login}", "Password"), ModuleSettings.Required(context, section, $"Auth:Users:{login}", "Role")); } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Props/Product.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Props/Product.cs ---- using redb.Core.Attributes; namespace RedbApp.Api.Props; /// /// The Props of a product. The object's name is not here: it is the object's own field /// (RedbObject.Name). Each property is stored in a typed column, so filters and sorting on them run /// in the database. /// [RedbScheme("Product")] public class Product { public string Category { get; set; } = string.Empty; public decimal Price { get; set; } public bool InStock { get; set; } public string? Description { get; set; } } /// /// A node of the category tree. The hierarchy itself is part of the object, not of the Props: a node is a /// TreeRedbObject<Category>, and deleting a node deletes its subtree. /// [RedbScheme("Category")] public class Category { public int SortOrder { get; set; } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/RedbApp.Api.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/RedbApp.Api.config.json ---- { "ContextName": "redbapp", "AutoStart": true, "Api": { "Host": "0.0.0.0", "Port": 5092, "CorsOrigins": "http://localhost:5082" }, "Auth": { "Issuer": "redbapp", "TokenLifetimeMinutes": 480 } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/RedbApp.Api.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/RedbApp.Api.csproj ---- Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Routes/ApiRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Routes/ApiRouteBuilder.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http.Rest; using redb.Route.RedbCore.Extensions; using RedbApp.Api.Services; using RedbApp.Models; namespace RedbApp.Api.Routes; /// /// The product and category API. Every verb is a route of its own: the REST declaration binds the request /// and forwards to a direct: endpoint, where one ProcessWithRedb step does the work. Code in the /// same process can send to the same direct: endpoints with a ProducerTemplate. /// Every call needs the token from POST /api/auth/login in Authorization: Bearer .... /// An OpenAPI document of each declaration is served at /api/products/openapi.json and /// /api/categories/openapi.json. /// public sealed class ApiRouteBuilder(ModuleSettings settings) : RouteBuilder { protected override void Configure() { this.Rest("/api/products", o => ApiOptions.Apply(o, settings, requireToken: true)) .Get().Produces("application/json").OutType().To("direct:products-list") .Get("/{id}").Produces("application/json").OutType().To("direct:products-get") .Post().Consumes("application/json").Type().OutType().To("direct:products-create") .Put("/{id}").Consumes("application/json").Type().OutType().To("direct:products-update") .Delete("/{id}").To("direct:products-delete"); From("direct:products-list").RouteId("products-list").ProcessWithRedb(ProductService.ListAsync); From("direct:products-get").RouteId("products-get").ProcessWithRedb(ProductService.GetAsync); From("direct:products-create").RouteId("products-create").ProcessWithRedb(ProductService.CreateAsync); From("direct:products-update").RouteId("products-update").ProcessWithRedb(ProductService.UpdateAsync); From("direct:products-delete").RouteId("products-delete").ProcessWithRedb(ProductService.DeleteAsync); this.Rest("/api/categories", o => ApiOptions.Apply(o, settings, requireToken: true)) .Get().Produces("application/json").OutType>().To("direct:categories-tree") .Post().Consumes("application/json").Type().OutType().To("direct:categories-create") .Delete("/{id}").To("direct:categories-delete"); From("direct:categories-tree").RouteId("categories-tree").ProcessWithRedb(CategoryService.TreeAsync); From("direct:categories-create").RouteId("categories-create").ProcessWithRedb(CategoryService.CreateAsync); // Deleting a subtree removes several objects; the transaction makes it all or nothing. From("direct:categories-delete").RouteId("categories-delete") .Transacted() .ProcessWithRedb(CategoryService.DeleteAsync) .EndTransaction(); } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Routes/AuthRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Routes/AuthRouteBuilder.cs ---- using System.Security.Cryptography; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Route.Http.Rest; using RedbApp.Api.Auth; using RedbApp.Models; namespace RedbApp.Api.Routes; /// /// POST /api/auth/login: login and password in, a token out. The only API call without a token. /// public sealed class AuthRouteBuilder(ModuleSettings settings, JwtTokens tokens) : RouteBuilder { protected override void Configure() { this.Rest("/api/auth", o => ApiOptions.Apply(o, settings, requireToken: false)) .Post("/login").Consumes("application/json").Type().OutType() .To("direct:login"); From("direct:login") .RouteId("login") .Process(Login); } private void Login(IExchange e) { var request = (LoginRequest)e.In.Body!; if (!settings.Users.TryGetValue(request.Login, out var user) || !SamePassword(user.Password, request.Password)) { e.In.Headers[HttpHeaders.ResponseCode] = 401; e.In.Body = new ApiError { Message = "Wrong login or password." }; return; } var (token, expiresAt) = tokens.Issue(user); e.In.Body = new LoginResponse { Token = token, Login = user.Login, Role = user.Role, ExpiresAt = expiresAt }; } // Constant-time comparison, so the answer time does not tell how much of the password was right. private static bool SamePassword(string expected, string actual) => CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(actual)); } /// The options every REST declaration of the module shares. internal static class ApiOptions { public static void Apply(RestOptions o, ModuleSettings settings, bool requireToken) { o.Host = settings.ApiHost; o.Port = settings.ApiPort; o.BindingMode = RestBindingMode.Json; // The Blazor client runs on another port in development, so the browser asks for CORS. o.ExtraConsumerOptions = $"cors=true&corsOrigins={Uri.EscapeDataString(settings.CorsOrigins)}"; if (requireToken) { o.InboundAuth = HttpAuthScheme.Bearer; o.TokenValidator = JwtTokens.RegistryName; } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Services/CategoryService.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Services/CategoryService.cs ---- using System.Globalization; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Http; using RedbApp.Api.Props; using RedbApp.Models; namespace RedbApp.Api.Services; /// The category tree: every root with its subtree, add a node, delete a subtree. public static class CategoryService { /// GET /api/categories: the top-level nodes from a tree query, each loaded with its subtree. public static async Task TreeAsync(IRedbService redb, IExchange e, CancellationToken ct) { var roots = await redb.TreeQuery().WhereRoots().ToListAsync(ct); var result = new List(); foreach (var root in roots) result.Add(ToNode(await redb.LoadTreeAsync(root.Id))); e.In.Body = result; } /// POST /api/categories: a top-level node, or a child of ParentId. public static async Task CreateAsync(IRedbService redb, IExchange e, CancellationToken ct) { var request = (NewCategory)e.In.Body!; if (string.IsNullOrWhiteSpace(request.Name)) { e.In.Headers[HttpHeaders.ResponseCode] = 400; e.In.Body = new ApiError { Message = "The name is required." }; return; } var node = new TreeRedbObject { Name = request.Name.Trim(), Props = new Category() }; if (request.ParentId is { } parentId) { var parent = await redb.LoadAsync(parentId, cancellationToken: ct); if (parent is null) { e.In.Headers[HttpHeaders.ResponseCode] = 404; e.In.Body = new ApiError { Message = $"Category {parentId} was not found." }; return; } await redb.CreateChildAsync(node, parent); } else { await redb.SaveAsync(node, ct); } e.In.Headers[HttpHeaders.ResponseCode] = 201; e.In.Body = new CategoryNode { Id = node.Id, Name = node.Name ?? "" }; } /// DELETE /api/categories/{id}: deleting a node deletes its whole subtree. public static async Task DeleteAsync(IRedbService redb, IExchange e, CancellationToken ct) { var id = long.TryParse(e.In.GetHeader("id"), CultureInfo.InvariantCulture, out var v) ? v : 0; if (await redb.DeleteAsync(id, ct)) { e.In.Body = null; return; } e.In.Headers[HttpHeaders.ResponseCode] = 404; e.In.Body = new ApiError { Message = $"Category {id} was not found." }; } private static CategoryNode ToNode(ITreeRedbObject node) => new() { Id = node.Id, Name = node.Name ?? "", Children = node.Children.Select(ToNode).ToList(), }; } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/Services/ProductService.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/Services/ProductService.cs ---- using System.ComponentModel.DataAnnotations; using System.Globalization; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Route.Abstractions; using redb.Route.Http; using RedbApp.Api.Props; using RedbApp.Models; namespace RedbApp.Api.Services; /// /// The product operations. Each method is one ProcessWithRedb step: it gets the request from the /// exchange (path parameters as headers, query parameters as query.* headers, the JSON body already /// bound to its type) and leaves the answer as the body. /// public static class ProductService { public const int PageSize = 10; /// GET /api/products?search=&inStock=&sort=&page=. Search, sorting and paging run in the database. public static async Task ListAsync(IRedbService redb, IExchange e, CancellationToken ct) { var search = e.In.GetHeader("query.search")?.Trim(); var inStockOnly = e.In.GetHeader("query.inStock") == "true"; var sort = e.In.GetHeader("query.sort") ?? "name"; var page = int.TryParse(e.In.GetHeader("query.page"), CultureInfo.InvariantCulture, out var p) ? p : 1; // The filter is built from scratch for the count and for the page, so the two queries share no state. IRedbQueryable Filtered() { var query = redb.Query(); // Name is the object's own field, so it is filtered with WhereRedb; Props fields use Where. if (!string.IsNullOrEmpty(search)) query = query.WhereRedb(x => x.Name.Contains(search)); if (inStockOnly) query = query.Where(x => x.InStock); return query; } var total = await Filtered().CountAsync(ct); var pageCount = Math.Max(1, (total + PageSize - 1) / PageSize); page = Math.Clamp(page, 1, pageCount); IRedbQueryable sorted = sort switch { "price" => Filtered().OrderBy(x => x.Price), "-price" => Filtered().OrderByDescending(x => x.Price), "category" => Filtered().OrderBy(x => x.Category), _ => Filtered().OrderByRedb(x => x.Name), }; var items = await sorted.Skip((page - 1) * PageSize).Take(PageSize).ToListAsync(ct); e.In.Body = new ProductPage { Items = items.Select(ToDto).ToList(), Total = total, Page = page, PageSize = PageSize }; } /// GET /api/products/{id}. public static async Task GetAsync(IRedbService redb, IExchange e, CancellationToken ct) { var product = await redb.LoadAsync(IdOf(e), cancellationToken: ct); e.In.Body = product is null ? NotFound(e) : ToDto(product); } /// POST /api/products: creates the product and answers 201 with it. public static async Task CreateAsync(IRedbService redb, IExchange e, CancellationToken ct) { var dto = (ProductDto)e.In.Body!; if (Invalid(e, dto)) return; var product = new RedbObject { Props = new Product() }; Apply(product, dto); await redb.SaveAsync(product, ct); e.In.Headers[HttpHeaders.ResponseCode] = 201; e.In.Body = ToDto(product); } /// PUT /api/products/{id}. With change tracking on, the save writes only the fields that changed. public static async Task UpdateAsync(IRedbService redb, IExchange e, CancellationToken ct) { var dto = (ProductDto)e.In.Body!; if (Invalid(e, dto)) return; var product = await redb.LoadAsync(IdOf(e), cancellationToken: ct); if (product is null) { e.In.Body = NotFound(e); return; } Apply(product, dto); await redb.SaveAsync(product, ct); e.In.Body = ToDto(product); } /// DELETE /api/products/{id}: 204, or 404 when there was nothing to delete. public static async Task DeleteAsync(IRedbService redb, IExchange e, CancellationToken ct) { e.In.Body = await redb.DeleteAsync(IdOf(e), ct) ? null : NotFound(e); } private static long IdOf(IExchange e) => long.TryParse(e.In.GetHeader("id"), CultureInfo.InvariantCulture, out var id) ? id : 0; private static ApiError NotFound(IExchange e) { e.In.Headers[HttpHeaders.ResponseCode] = 404; return new ApiError { Message = $"Product {e.In.GetHeader("id")} was not found." }; } // The browser validates the form, but the API cannot trust that: the same attributes are checked here. private static bool Invalid(IExchange e, ProductDto dto) { var errors = new List(); if (Validator.TryValidateObject(dto, new ValidationContext(dto), errors, validateAllProperties: true)) return false; e.In.Headers[HttpHeaders.ResponseCode] = 400; e.In.Body = new ApiError { Message = string.Join(" ", errors.Select(r => r.ErrorMessage)) }; return true; } private static void Apply(RedbObject product, ProductDto dto) { product.Name = dto.Name; product.Props!.Category = dto.Category; product.Props.Price = dto.Price; product.Props.InStock = dto.InStock; product.Props.Description = dto.Description; } private static ProductDto ToDto(RedbObject o) => new() { Id = o.Id, Name = o.Name ?? "", Category = o.Props!.Category, Price = o.Props.Price, InStock = o.Props.InStock, Description = o.Props.Description, }; } Path: redb/redb.Templates/templates/redb-app/RedbApp.Api/manifest.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Api/manifest.json ---- { "Name": "RedbApp", "Version": "1.0.0", "EntryPoints": ["RedbApp.Api.dll"], "Dependencies": [] } Path: redb/redb.Templates/templates/redb-app/RedbApp.Host/ContextConfiguration.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Host/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace RedbApp.Host; /// /// The context configuration the way a Tsak worker builds it, in miniature. Each layer deep-merges over /// the previous one, later layers win: /// /// the module's RedbApp.Api.config.json, /// Tsak:Contexts:{context}:Override of the host configuration. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. So the /// same keys and the same environment variables work here and on a Tsak worker. /// public static class ContextConfiguration { /// The context the 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 = Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"))); 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) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var child in section.GetChildren()) result[child.Key] = child.GetChildren().Any() ? Read(child) : 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; } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Host/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Host/Dockerfile ---- # The API in its own host. Build from the solution folder: # docker build -f RedbApp.Host/Dockerfile -t redbapp-api . FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbApp.Models/RedbApp.Models.csproj RedbApp.Models/ COPY RedbApp.Api/RedbApp.Api.csproj RedbApp.Api/ COPY RedbApp.Host/RedbApp.Host.csproj RedbApp.Host/ RUN dotnet restore RedbApp.Host/RedbApp.Host.csproj COPY . . RUN dotnet publish RedbApp.Host/RedbApp.Host.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/runtime:10.0 WORKDIR /app COPY --from=build /app . # The database goes to a volume. The app runs as the non-root user of the .NET image, which must be # able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/redbapp.db" VOLUME /data EXPOSE 5092 ENTRYPOINT ["dotnet", "RedbApp.Host.dll"] Path: redb/redb.Templates/templates/redb-app/RedbApp.Host/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Host/Program.cs ---- // The API's own host. It does what a Tsak worker does for the module, and nothing more: // 1) reads appsettings.json, then environment variables, // 2) registers redb and the HTTP server of the process, initializes redb, // 3) builds the context configuration (module config file, then the Override section), // 4) awaits RedbApp.Api.InitRoute.main(ctx), the method the Tsak worker calls, // 5) starts the context and runs until Ctrl+C or SIGTERM. using System.Runtime.InteropServices; 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.Route.Core; using redb.Route.Http; using redb.SQLite.Pro.Extensions; using RedbApp.Api; using RedbApp.Host; var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var connectionString = configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbApp.Host.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); // The HTTP servers of the process, one per port, as the Tsak worker registers them. services.AddRedbRouteHttpHosting(); await using var provider = services.BuildServiceProvider(); // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService().InitializeAsync(ensureCreated: true); } var moduleConfig = Path.Combine(AppContext.BaseDirectory, "RedbApp.Api.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); var context = new RouteContext(provider, contextName, provider.GetRequiredService()); ContextConfiguration.ApplyTo(context, ContextConfiguration.Build(configuration, contextName, moduleConfig)); await InitRoute.main(context); // <- the exact method the Tsak worker calls await context.Start(); var settings = ModuleSettings.FromContext(context); Console.WriteLine(); Console.WriteLine($"RedbApp API on http://localhost:{settings.ApiPort}/api (OpenAPI: /api/products/openapi.json)."); Console.WriteLine("Start the client in a second terminal: dotnet run --project RedbApp.Web"); Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); var stop = new TaskCompletionSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; // docker stop sends SIGTERM, not Ctrl+C. using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, c => { c.Cancel = true; stop.TrySetResult(); }); await stop.Task; await context.DisposeAsync(); Path: redb/redb.Templates/templates/redb-app/RedbApp.Host/RedbApp.Host.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Host/RedbApp.Host.csproj ---- Exe Path: redb/redb.Templates/templates/redb-app/RedbApp.Host/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Host/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=redbapp.db" }, "Tsak": { "Contexts": { "redbapp": { // The Override layer of the API's settings: it wins over RedbApp.Api.config.json. The same keys // work on a Tsak worker as environment variables, for example // Tsak__Contexts__redbapp__Override__Auth__SigningKey. "Override": { "Auth": { // Signs the sign-in tokens, at least 32 characters. This one is for your machine only: // set your own through the environment everywhere else. "SigningKey": "local-development-key-change-me-0123456789", // Who can sign in. A stand-in that keeps the template small: a real application keeps its // users in a store of its own, for example redb.Identity. "Users": { "admin": { "Password": "admin", "Role": "admin" } } } } } } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Models/Dtos.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Models/Dtos.cs ---- using System.ComponentModel.DataAnnotations; namespace RedbApp.Models; public sealed class LoginRequest { [Required] public string Login { get; set; } = ""; [Required] public string Password { get; set; } = ""; } public sealed class LoginResponse { public string Token { get; set; } = ""; public string Login { get; set; } = ""; public string Role { get; set; } = ""; public DateTimeOffset ExpiresAt { get; set; } } /// A product as the API sends and receives it. Validation runs on the form and again on the server. public sealed class ProductDto { public long Id { get; set; } [Required, StringLength(200)] public string Name { get; set; } = ""; [Required, StringLength(100)] public string Category { get; set; } = ""; [Range(0, 1_000_000)] public decimal Price { get; set; } public bool InStock { get; set; } [StringLength(2000)] public string? Description { get; set; } } /// One page of the product list, and the total the filter matches. public sealed class ProductPage { public List Items { get; set; } = []; public int Total { get; set; } public int Page { get; set; } public int PageSize { get; set; } } /// A node of the category tree with its children. public sealed class CategoryNode { public long Id { get; set; } public string Name { get; set; } = ""; public List Children { get; set; } = []; } public sealed class NewCategory { [Required, StringLength(100)] public string Name { get; set; } = ""; /// The parent node; null for a top-level category. public long? ParentId { get; set; } } /// The body of an error answer. public sealed class ApiError { public string Message { get; set; } = ""; } Path: redb/redb.Templates/templates/redb-app/RedbApp.Models/RedbApp.Models.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Models/RedbApp.Models.csproj ---- Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/App.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/App.razor ----

Nothing here.

Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Dockerfile ---- # The client: published once, served by nginx. Build from the solution folder: # docker build -f RedbApp.Web/Dockerfile -t redbapp-web . FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbApp.Models/RedbApp.Models.csproj RedbApp.Models/ COPY RedbApp.Web/RedbApp.Web.csproj RedbApp.Web/ RUN dotnet restore RedbApp.Web/RedbApp.Web.csproj COPY . . RUN dotnet publish RedbApp.Web/RedbApp.Web.csproj -c Release -o /publish --no-restore FROM nginx:alpine COPY --from=build /publish/wwwroot /usr/share/nginx/html COPY RedbApp.Web/nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Layout/MainLayout.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Layout/MainLayout.razor ---- @inherits LayoutComponentBase @implements IDisposable @inject Session Session @inject NavigationManager Navigation
RedbApp @if (Session.IsSignedIn) { Products Categories @Session.Login }
@Body
@code { protected override void OnInitialized() => Session.Changed += StateHasChanged; // Every page except the sign-in page needs a session. protected override void OnParametersSet() { if (!Session.IsSignedIn && !Navigation.Uri.EndsWith("/login", StringComparison.OrdinalIgnoreCase)) Navigation.NavigateTo("login"); } private void SignOut() { Session.SignOut(); Navigation.NavigateTo("login"); } public void Dispose() => Session.Changed -= StateHasChanged; } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Categories.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Categories.razor ---- @page "/categories" @inject ApiClient Api @inject Session Session Categories

Categories

@if (error is not null) {

@error

} @code { private List roots = []; private string? newRootName; private string? error; protected override Task OnInitializedAsync() => Session.IsSignedIn ? LoadAsync() : Task.CompletedTask; private Task LoadAsync() => RunAsync(async () => roots = await Api.CategoriesAsync()); private async Task AddAsync(long? parentId, string name) { await RunAsync(() => Api.AddCategoryAsync(new NewCategory { Name = name.Trim(), ParentId = parentId })); if (parentId is null) newRootName = null; await LoadAsync(); } // Deleting a node deletes its whole subtree. private async Task DeleteAsync(long id) { await RunAsync(() => Api.DeleteCategoryAsync(id)); await LoadAsync(); } private async Task RunAsync(Func call) { error = null; try { await call(); } catch (ApiException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/CategoryNodeList.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/CategoryNodeList.razor ---- @* Renders a level of the tree and calls itself for the children. *@
    @foreach (var node in Nodes) {
  • @node.Name @if (adding == node.Id) { } @if (node.Children.Count > 0) { }
  • }
@code { [Parameter, EditorRequired] public List Nodes { get; set; } = []; [Parameter] public EventCallback<(long ParentId, string Name)> OnAddChild { get; set; } [Parameter] public EventCallback OnDelete { get; set; } private long? adding; private string? childName; private async Task AddAsync(long parentId) { var name = childName!.Trim(); Cancel(); await OnAddChild.InvokeAsync((parentId, name)); } private void Cancel() { adding = null; childName = null; } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Login.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Login.razor ---- @page "/login" @inject ApiClient Api @inject NavigationManager Navigation Sign in

Sign in

@if (error is not null) {

@error

}

The users are in RedbApp.Host/appsettings.json (Auth:Users).

@code { private readonly LoginRequest request = new(); private string? error; private bool busy; private async Task SignInAsync() { busy = true; error = await Api.LoginAsync(request); busy = false; if (error is null) Navigation.NavigateTo(""); } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/ProductEdit.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/ProductEdit.razor ---- @page "/products/new" @page "/products/{Id:long}" @inject ApiClient Api @inject Session Session @inject NavigationManager Navigation @(Id is null ? "New product" : "Edit product")

@(Id is null ? "New product" : "Edit product")

@if (error is not null) {

@error

} @if (product is not null) {
Cancel
} @code { [Parameter] public long? Id { get; set; } private ProductDto? product; private string? error; protected override async Task OnParametersSetAsync() { if (!Session.IsSignedIn) return; if (Id is null) { product = new ProductDto(); return; } try { product = await Api.ProductAsync(Id.Value); } catch (ApiException ex) { error = ex.Message; } } private async Task SaveAsync() { try { await Api.SaveProductAsync(product!); Navigation.NavigateTo(""); } catch (ApiException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Products.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Pages/Products.razor ---- @page "/" @inject ApiClient Api @inject Session Session Products

Products

New product
@if (error is not null) {

@error

}

@data.Total product(s)

@foreach (var item in data.Items) { }
NameCategoryPriceIn stock
@item.Name @item.Category @item.Price.ToString("F2") @(item.InStock ? "yes" : "no")
@code { private string? search; private bool inStockOnly; private string sort = "name"; private ProductPage data = new() { Page = 1, PageSize = 10 }; private string? error; private int PageCount => Math.Max(1, (data.Total + data.PageSize - 1) / Math.Max(1, data.PageSize)); protected override Task OnInitializedAsync() => Session.IsSignedIn ? LoadAsync(1) : Task.CompletedTask; private Task ReloadFromFirstPage() => LoadAsync(1); private Task GoToAsync(int page) => LoadAsync(page); private async Task DeleteAsync(long id) { await RunAsync(() => Api.DeleteProductAsync(id)); await LoadAsync(data.Page); } // Search, sorting and paging run in the API, and there in the database. private Task LoadAsync(int page) => RunAsync(async () => data = await Api.ProductsAsync(search, inStockOnly, sort, page)); private async Task RunAsync(Func call) { error = null; try { await call(); } catch (ApiException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Program.cs ---- using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using RedbApp.Web; using RedbApp.Web.Services; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); // Where the API is. wwwroot/appsettings.Development.json points at the API host on its own port; in a // deployment the setting is empty and the client calls its own origin, where nginx forwards /api/. var apiBase = builder.Configuration["ApiBaseUrl"] is { Length: > 0 } configured ? configured : builder.HostEnvironment.BaseAddress; builder.Services.AddSingleton(); builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(apiBase) }); builder.Services.AddScoped(); await builder.Build().RunAsync(); Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Properties/launchSettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Properties/launchSettings.json ---- { "profiles": { "RedbApp.Web": { "commandName": "Project", "launchBrowser": true, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5082", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/RedbApp.Web.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/RedbApp.Web.csproj ---- true Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Services/ApiClient.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Services/ApiClient.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using Microsoft.AspNetCore.Components; using RedbApp.Models; namespace RedbApp.Web.Services; /// /// The API calls of the client. Every call carries the token of the ; a 401 answer /// means the token is gone or expired, so the session ends and the user is sent to the sign-in page. /// public sealed class ApiClient(HttpClient http, Session session, NavigationManager navigation) { public async Task LoginAsync(LoginRequest request) { using var response = await http.PostAsJsonAsync("api/auth/login", request); if (!response.IsSuccessStatusCode) return await ErrorOf(response); session.SignIn((await response.Content.ReadFromJsonAsync())!); return null; } public Task ProductsAsync(string? search, bool inStockOnly, string sort, int page) => GetAsync($"api/products?search={Uri.EscapeDataString(search ?? "")}" + $"&inStock={(inStockOnly ? "true" : "false")}&sort={Uri.EscapeDataString(sort)}&page={page}"); public Task ProductAsync(long id) => GetAsync($"api/products/{id}"); public Task SaveProductAsync(ProductDto product) => product.Id == 0 ? SendAsync(HttpMethod.Post, "api/products", product) : SendAsync(HttpMethod.Put, $"api/products/{product.Id}", product); public Task DeleteProductAsync(long id) => SendAsync(HttpMethod.Delete, $"api/products/{id}", null); public Task> CategoriesAsync() => GetAsync>("api/categories"); public Task AddCategoryAsync(NewCategory category) => SendAsync(HttpMethod.Post, "api/categories", category); public Task DeleteCategoryAsync(long id) => SendAsync(HttpMethod.Delete, $"api/categories/{id}", null); private async Task GetAsync(string uri) { using var response = await SendRawAsync(HttpMethod.Get, uri, null); return (await response.Content.ReadFromJsonAsync())!; } private async Task SendAsync(HttpMethod method, string uri, object? body) { using var response = await SendRawAsync(method, uri, body); } private async Task SendRawAsync(HttpMethod method, string uri, object? body) { using var request = new HttpRequestMessage(method, uri); if (session.Token is { } token) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); if (body is not null) request.Content = JsonContent.Create(body, body.GetType()); var response = await http.SendAsync(request); if (response.StatusCode == HttpStatusCode.Unauthorized) { response.Dispose(); session.SignOut(); navigation.NavigateTo("login"); throw new ApiException("Your session has ended. Please sign in again."); } if (!response.IsSuccessStatusCode) { var message = await ErrorOf(response); response.Dispose(); throw new ApiException(message); } return response; } private static async Task ErrorOf(HttpResponseMessage response) { var error = response.Content.Headers.ContentType?.MediaType == "application/json" ? await response.Content.ReadFromJsonAsync() : null; return error?.Message ?? $"The server answered {(int)response.StatusCode} {response.ReasonPhrase}."; } } /// An API call that did not succeed; the message is meant for the user. public sealed class ApiException(string message) : Exception(message); Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/Services/Session.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/Services/Session.cs ---- using RedbApp.Models; namespace RedbApp.Web.Services; /// /// Who is signed in, and the token that proves it. Kept in memory only: reloading the page signs out. /// A real application may keep the token in sessionStorage through JS interop. /// public sealed class Session { public string? Token { get; private set; } public string? Login { get; private set; } public string? Role { get; private set; } public bool IsSignedIn => Token is not null; public event Action? Changed; public void SignIn(LoginResponse response) { Token = response.Token; Login = response.Login; Role = response.Role; Changed?.Invoke(); } public void SignOut() { Token = Login = Role = null; Changed?.Invoke(); } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/_Imports.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/_Imports.razor ---- @using System.Net.Http @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using RedbApp.Models @using RedbApp.Web @using RedbApp.Web.Layout @using RedbApp.Web.Services Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/nginx.conf Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/nginx.conf ---- # The client as static files, and the API behind the same origin: the browser sees one address, so no # CORS is needed. "api" is the API's service name in deploy/docker-compose*.yml. server { listen 80; root /usr/share/nginx/html; location /api/ { proxy_pass http://api:5092; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # Client-side routes (/products/12, /categories) all load index.html. location / { try_files $uri $uri/ /index.html; } } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/app.css Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/app.css ---- body { font-family: system-ui, sans-serif; margin: 0; color: #1f2328; background: #fff; } header { display: flex; gap: 1.5rem; align-items: center; padding: 0.75rem 1.5rem; border-bottom: 1px solid #d0d7de; } header .brand { font-weight: 600; color: #b3261e; text-decoration: none; } main { max-width: 960px; margin: 0 auto; padding: 1rem 1.5rem; } a { color: #0969da; } .filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 0.5rem; } .muted { color: #656d76; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #d0d7de; } .num { text-align: right; } .pager { display: flex; gap: 0.5rem; margin-top: 1rem; } .pager span { font-weight: 600; } .form { display: grid; gap: 0.35rem; max-width: 480px; } .form input:not([type=checkbox]), .form textarea { padding: 0.35rem; font: inherit; } .form .actions { display: flex; gap: 1rem; align-items: center; margin-top: 0.75rem; } .field-validation-error, .validation-summary-errors { color: #b3261e; } button.link { background: none; border: 0; padding: 0; color: #b3261e; cursor: pointer; font: inherit; } header a.active { font-weight: 600; } .pager button { font: inherit; } .tree { list-style: none; padding-left: 1.25rem; } .tree li { margin: 0.25rem 0; } .tree button.link { margin-left: 0.5rem; } .inline { display: inline-flex; gap: 0.4rem; margin-left: 0.5rem; } header .who { margin-left: auto; color: #656d76; } .error { color: #b3261e; } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/appsettings.Development.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/appsettings.Development.json ---- { "ApiBaseUrl": "http://localhost:5092/" } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/appsettings.json ---- { "ApiBaseUrl": "" } Path: redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/index.html Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.Web/wwwroot/index.html ---- RedbApp
Loading...
Path: redb/redb.Templates/templates/redb-app/RedbApp.slnx Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/RedbApp.slnx ---- Path: redb/redb.Templates/templates/redb-app/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/docker-compose.mssql.yml ---- # The API with SQL Server instead of SQLite, and the client behind nginx. # Before the first run, switch the provider in code (see the comment in RedbApp.Host/Program.cs): # RedbApp.Host.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then (deploy/.env as for docker-compose.yml): docker compose -f deploy/docker-compose.mssql.yml up --build # Then open http://localhost:8080. services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql api: build: context: .. dockerfile: RedbApp.Host/Dockerfile environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" Tsak__Contexts__redbapp__Override__Auth__SigningKey: ${APP_SIGNING_KEY:?APP_SIGNING_KEY required} Tsak__Contexts__redbapp__Override__Auth__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: - db web: build: context: .. dockerfile: RedbApp.Web/Dockerfile ports: - "8080:80" depends_on: - api volumes: mssqldata: Path: redb/redb.Templates/templates/redb-app/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/docker-compose.postgres.yml ---- # The API with PostgreSQL instead of SQLite, and the client behind nginx. # Before the first run, switch the provider in code (see the comment in RedbApp.Host/Program.cs): # RedbApp.Host.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder (deploy/.env as for docker-compose.yml): # docker compose -f deploy/docker-compose.postgres.yml up --build # Then open http://localhost:8080. services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 api: build: context: .. dockerfile: RedbApp.Host/Dockerfile environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" Tsak__Contexts__redbapp__Override__Auth__SigningKey: ${APP_SIGNING_KEY:?APP_SIGNING_KEY required} Tsak__Contexts__redbapp__Override__Auth__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: db: condition: service_healthy web: build: context: .. dockerfile: RedbApp.Web/Dockerfile ports: - "8080:80" depends_on: - api volumes: pgdata: Path: redb/redb.Templates/templates/redb-app/deploy/docker-compose.tsak.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/docker-compose.tsak.yml ---- # The API as a module on a Tsak worker, and the client behind nginx. The Tsak stack image (worker and # dashboard in one container) loads RedbApp.tpkg from deploy/output. The worker's default redb is # SQLite, so nothing else is needed. # # From the project folder: # cp deploy/.env.example deploy/.env # then fill in the Tsak values and the APP_ values # pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbApp.tpkg # docker compose -f deploy/docker-compose.tsak.yml up -d --build # # Then open http://localhost:8080. Dashboard: http://localhost:8085 (admin and TSAK_WEB_ADMIN_PASSWORD). services: # The service is called "api" so that RedbApp.Web/nginx.conf reaches it unchanged. api: image: ghcr.io/redbase-app/redb-tsak-stack:${TSAK_VERSION:-4.8.0-net10} restart: unless-stopped ports: - "127.0.0.1:9090:9090" # worker API - "127.0.0.1:8085:8085" # dashboard environment: # The worker's default (unnamed) redb, the one the module works in. The same settings as the own # host: Pro, change tracking, the PVT prefilter. The props cache stays off; to turn it on add # Tsak__Redb__EnablePropsCache=true. - Tsak__Redb__UsePro=true - Tsak__Redb__PropsSaveStrategy=ChangeTracking - Tsak__Redb__EnablePvtPrefilter=true - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://api:9090 # No Tsak__Cluster__NodeId: a node is named after its container's host name, so each replica of # `docker compose up --scale` is a node of its own. A fixed id suits one instance or a StatefulSet only. # 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, the same keys the own host reads. - Tsak__Contexts__redbapp__Override__Auth__SigningKey=${APP_SIGNING_KEY:?APP_SIGNING_KEY required} - Tsak__Contexts__redbapp__Override__Auth__Users__admin__Password=${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} - Tsak__Contexts__redbapp__Override__Auth__Users__admin__Role=admin volumes: - ./output:/app/modules web: build: context: .. dockerfile: RedbApp.Web/Dockerfile ports: - "8080:80" depends_on: - api Path: redb/redb.Templates/templates/redb-app/deploy/docker-compose.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/docker-compose.yml ---- # The API in its own host with SQLite, and the client behind nginx on one origin. # From the project folder: # cp deploy/.env.example deploy/.env # then set APP_SIGNING_KEY and APP_ADMIN_PASSWORD # docker compose -f deploy/docker-compose.yml up --build # Then open http://localhost:8080 and sign in as admin. services: api: build: context: .. dockerfile: RedbApp.Host/Dockerfile environment: Tsak__Contexts__redbapp__Override__Auth__SigningKey: ${APP_SIGNING_KEY:?APP_SIGNING_KEY required} Tsak__Contexts__redbapp__Override__Auth__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} volumes: - apidata:/data web: build: context: .. dockerfile: RedbApp.Web/Dockerfile ports: - "8080:80" depends_on: - api volumes: apidata: Path: redb/redb.Templates/templates/redb-app/deploy/pack-tpkg.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds RedbApp.Api and packs it into RedbApp.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, RedbApp.Api.dll and every dependency the worker does not ship itself (RedbApp.Models and redb.Route.File, for example). deploy/shipped-module-deps.txt lists what the worker ships (its header says how to regenerate the list); the package contents are written next to it as RedbApp.tpkg.contents.txt. .EXAMPLE ./deploy/pack-tpkg.ps1 ./deploy/pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $module = Join-Path $root "RedbApp.Api" $entryDll = "RedbApp.Api.dll" $publish = Join-Path ([IO.Path]::GetTempPath()) "redbapp-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "redbapp-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "RedbApp.tpkg" $shippedList = Join-Path $PSScriptRoot "shipped-module-deps.txt" # 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 $module "RedbApp.Api.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of RedbApp.Api failed." } # The worker resolves only the assemblies it ships (shipped-module-deps.txt). Every other dependency, # RedbApp.Models included, has to travel inside the package, otherwise the module fails to load. $shipped = @(Get-Content $shippedList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $extra = @(Get-ChildItem $publish -Filter *.dll | Where-Object { $_.Name -ne $entryDll -and $shipped -notcontains $_.Name }) 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 $module "manifest.json") $staging Copy-Item (Join-Path $module "RedbApp.Api.config.json") $staging Copy-Item (Join-Path $publish $entryDll) $staging foreach ($dependency in $extra) { Copy-Item $dependency.FullName $staging } # Native assets of a dependency (runtimes//native/...), if the module brought any. $runtimes = Join-Path $publish "runtimes" if (Test-Path $runtimes) { Copy-Item $runtimes $staging -Recurse } if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) # What the package holds, next to it: handy when a Tsak node refuses to load the module. $contents = Get-ChildItem $staging -Recurse -File | ForEach-Object { $_.FullName.Substring($staging.Length + 1).Replace('\', '/') } Set-Content -Path ($package + ".contents.txt") -Value $contents -Encoding utf8 Write-Host "Packed $package" Write-Host " module: $entryDll" Write-Host (" packed dependencies: {0}" -f $extra.Count) foreach ($dependency in $extra) { Write-Host (" " + $dependency.Name) } Write-Host (" not packed: {0} assemblies shipped by the worker" -f $shipped.Count) Path: redb/redb.Templates/templates/redb-app/deploy/shipped-module-deps.txt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-app/deploy/shipped-module-deps.txt ---- # Assemblies the redb.Tsak worker already provides: /app/*.dll and /app/Libs/shared/*.dll of # redb-tsak-worker:4.8.0, and the assemblies of the ASP.NET Core shared framework of its base image that this # list carries (Microsoft.Extensions.*, System.Diagnostics.EventLog, System.Security.Cryptography.Pkcs). The # worker binds those from /usr/share/dotnet/shared: since 4.8 the SDK publishes no copy of them into /app, and a # copy inside a module would give ILogger, IConfiguration or IOptions a second type identity. A module # dependency present here is NOT packed into the .tpkg; every other dependency travels inside the package. # # The worker resolves these from its own folder and from Libs/shared next to the application # (Libs/shared under the app directory, not the current one). A Tsak host built locally from the # tsak-worker template ships a smaller set: put the assemblies a module needs (redb.Route.File, # redb.Route.GenericFile, ...) into that host project Libs/shared - the template copies Libs/** to # the output - or pack them by removing them from this list. # # Regenerate when the worker image changes: the command gives the /app part; merge it in and keep the # shared-framework entries the list already has. # docker run --rm --entrypoint sh redb-tsak-worker: -c "ls /app/*.dll /app/Libs/shared/*.dll" | sed "s|.*/||" | sort -u # AWSSDK.Core.dll AWSSDK.S3.dll AWSSDK.SQS.dll AWSSDK.SimpleNotificationService.dll Amqp.Net.dll Azure.Core.Amqp.dll Azure.Core.dll Azure.Messaging.ServiceBus.dll BCrypt-Net-Next.dll BouncyCastle.Cryptography.dll Chr.Avro.Binary.dll Chr.Avro.Json.dll Chr.Avro.dll Confluent.Kafka.dll CsvHelper.dll Elastic.Clients.Elasticsearch.dll Elastic.Esql.dll Elastic.Transport.dll FirebaseAdmin.dll FluentFTP.dll FluentValidation.dll Google.Api.CommonProtos.dll Google.Api.Gax.Grpc.dll Google.Api.Gax.Rest.dll Google.Api.Gax.dll Google.Apis.Auth.dll Google.Apis.Core.dll Google.Apis.Storage.v1.dll Google.Apis.dll Google.Cloud.Firestore.V1.dll Google.Cloud.Firestore.dll Google.Cloud.Location.dll Google.Cloud.Storage.V1.dll Google.LongRunning.dll Google.Protobuf.dll Grpc.Auth.dll Grpc.Core.Api.dll Grpc.Net.Client.dll Grpc.Net.Common.dll Humanizer.dll Json.More.dll JsonPath.Net.dll JsonPointer.Net.dll JsonSchema.Net.dll Jsonata.Net.Native.SystemTextJson.dll Jsonata.Net.Native.dll MQTTnet.dll MailKit.dll MessagePack.Annotations.dll MessagePack.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Protocols.MessagePack.dll Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll Microsoft.Azure.Amqp.dll Microsoft.Bcl.AsyncInterfaces.dll Microsoft.Bcl.Cryptography.dll Microsoft.Data.SqlClient.Extensions.Abstractions.dll Microsoft.Data.SqlClient.Internal.Logging.dll Microsoft.Data.SqlClient.dll Microsoft.Data.Sqlite.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.CommandLine.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.Configuration.UserSecrets.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.Diagnostics.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.dll Microsoft.Extensions.Diagnostics.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.Console.dll Microsoft.Extensions.Logging.Debug.dll Microsoft.Extensions.Logging.EventLog.dll Microsoft.Extensions.Logging.EventSource.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.Identity.Client.Extensions.Msal.dll Microsoft.Identity.Client.dll Microsoft.IdentityModel.Abstractions.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Protocols.OpenIdConnect.dll Microsoft.IdentityModel.Protocols.dll Microsoft.IdentityModel.Tokens.dll Microsoft.NET.StringTools.dll Microsoft.SqlServer.Server.dll MimeKit.dll Newtonsoft.Json.dll Novell.Directory.Ldap.NETStandard.dll Npgsql.dll OpenTelemetry.Api.ProviderBuilderExtensions.dll OpenTelemetry.Api.dll OpenTelemetry.Exporter.OpenTelemetryProtocol.dll OpenTelemetry.Exporter.Prometheus.HttpListener.dll OpenTelemetry.Extensions.Hosting.dll OpenTelemetry.Instrumentation.Process.dll OpenTelemetry.Instrumentation.Runtime.dll OpenTelemetry.dll Pipelines.Sockets.Unofficial.dll Quartz.Extensions.DependencyInjection.dll Quartz.Extensions.Hosting.dll Quartz.Serialization.Json.dll Quartz.dll RabbitMQ.Client.OAuth2.dll RabbitMQ.Client.dll Renci.SshNet.dll SQLitePCLRaw.batteries_v2.dll SQLitePCLRaw.core.dll SQLitePCLRaw.provider.e_sqlite3.dll Scriban.dll Serilog.AspNetCore.dll Serilog.Enrichers.Environment.dll Serilog.Enrichers.Process.dll Serilog.Enrichers.Thread.dll Serilog.Extensions.Hosting.dll Serilog.Extensions.Logging.dll Serilog.Formatting.Compact.dll Serilog.Settings.Configuration.dll Serilog.Sinks.Console.dll Serilog.Sinks.Debug.dll Serilog.Sinks.File.dll Serilog.dll StackExchange.Redis.dll System.ClientModel.dll System.CodeDom.dll System.Configuration.ConfigurationManager.dll System.Diagnostics.EventLog.dll System.IO.Hashing.dll System.IdentityModel.Tokens.Jwt.dll System.Management.dll System.Memory.Data.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll Telegram.Bot.dll XPath2.dll YamlDotNet.dll amqmdnetstd.dll amqmxmsstd.dll redb.Core.Pro.dll redb.Core.dll redb.Licensing.dll redb.MSSql.Pro.dll redb.MSSql.dll redb.Postgres.Pro.dll redb.Postgres.dll redb.Route.Amqp.dll redb.Route.As2.dll redb.Route.As4.dll redb.Route.AzureServiceBus.dll redb.Route.Cache.dll redb.Route.Controllers.dll redb.Route.Core.dll redb.Route.DataFormats.Avro.dll redb.Route.DataFormats.Csv.dll redb.Route.DataFormats.Mime.dll redb.Route.DataFormats.Protobuf.dll redb.Route.DataFormats.XmlJson.dll redb.Route.DataFormats.Yaml.dll redb.Route.Elasticsearch.dll redb.Route.Exec.dll redb.Route.File.dll redb.Route.Firebase.dll redb.Route.Ftp.dll redb.Route.GenericFile.dll redb.Route.Grpc.dll redb.Route.Http.Hosting.dll redb.Route.Http.dll redb.Route.IbmMq.dll redb.Route.JsonTransform.dll redb.Route.Kafka.dll redb.Route.Ldap.dll redb.Route.Llm.Abstractions.dll redb.Route.Llm.Mcp.dll redb.Route.Llm.Tools.dll redb.Route.Llm.dll redb.Route.Mail.dll redb.Route.MqttNet.dll redb.Route.Quartz.dll redb.Route.RabbitMQ.dll redb.Route.Redis.dll redb.Route.S3.dll redb.Route.Sftp.dll redb.Route.SignalR.StackExchangeRedis.dll redb.Route.SignalR.dll redb.Route.Soap.dll redb.Route.Sql.dll redb.Route.Sqs.dll redb.Route.Tcp.dll redb.Route.Telegram.dll redb.Route.Templates.dll redb.Route.Validation.Adapters.dll redb.Route.WebSocket.dll redb.Route.XPath2.dll redb.Route.Xml.dll redb.Route.dll redb.SQLite.Pro.dll redb.SQLite.dll redb.Tsak.Contracts.dll redb.Tsak.Core.Pro.dll redb.Tsak.Core.dll redb.Tsak.Worker.dll Path: redb/redb.Templates/templates/redb-bff/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/.dockerignore ---- **/bin/ **/obj/ *.db *.db-shm *.db-wal deploy/output/ deploy/.env Path: redb/redb.Templates/templates/redb-bff/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Web", "Blazor", "BFF", "API", "Database", "RedBase" ], "identity": "RedBase.Bff.Template", "name": "RedBase Blazor BFF with redb.Route controllers", "description": "A Blazor backend-for-frontend with a cookie session and a backend of redb.Route controllers on redb; the backend runs in its own host or as a Tsak module.", "shortName": "redb-bff", "tags": { "language": "C#", "type": "solution" }, "sourceName": "RedbBff", "preferNameDirectory": true, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/redb-bff/Directory.Build.props Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/Directory.Build.props ---- net10.0 enable enable 4.8.0 false Path: redb/redb.Templates/templates/redb-bff/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/README.md ---- # RedbBff A Blazor backend-for-frontend on RedBase and redb.Route controllers: a product list with search, sorting and paging, a create / edit form, and a category tree. SQLite with Pro, so it runs as is. Two processes: - **the web server** (Blazor, Interactive Server): users sign in here, the browser holds only a session cookie; - **the backend**: redb.Route controllers over RedBase. Its only caller is the web server, with a service key. It is a module that runs in its own host or on a Tsak worker. ## Run In two terminals, from the project folder: ```bash dotnet run --project RedbBff.Host # the backend on http://127.0.0.1:5093 dotnet run --project RedbBff.Web # the web server on http://localhost:5083 ``` Open http://localhost:5083 and sign in as `admin` / `admin`. On the first run the backend creates `redbbff.db`, builds the RedBase tables and adds sample products and categories. Or both in containers: `cp deploy/.env.example deploy/.env`, set `BFF_SERVICE_KEY` and `APP_ADMIN_PASSWORD`, then `docker compose -f deploy/docker-compose.yml up --build` and open http://localhost:8080. ## Projects | Project | What it is | |---------|------------| | `RedbBff.Models` | What the web server and the backend exchange. No RedBase | | `RedbBff.Backend` | The module: `InitRoute.main`, the controllers, the redb Props classes | | `RedbBff.Host` | The backend's own host: redb registration and settings, then `InitRoute.main` | | `RedbBff.Web` | The web server: Blazor pages, the cookie session, the backend client | ## Where things are | File | What it does | |------|--------------| | `RedbBff.Backend/InitRoute.cs` | One HTTP endpoint with the service-key check, dispatching to every controller | | `RedbBff.Backend/Controllers/ProductsController.cs` | `[Route]`, `[HttpGet("{id}")]`, `[FromQuery]`, `[FromBody]`; search, sorting and paging in the database | | `RedbBff.Backend/Controllers/CategoriesController.cs` | The tree: roots, subtrees, add a node, delete a subtree | | `RedbBff.Backend/Controllers/ApiController.cs` | The redb service of the request, status codes, validation | | `RedbBff.Backend/ServiceKeyValidator.cs` | Lets in only the web server | | `RedbBff.Host/appsettings.json` | `ConnectionStrings:Redb` and the service key (the `Override` layer) | | `RedbBff.Web/Program.cs` | The cookie session, sign-in and sign-out, the backend client | | `RedbBff.Web/Components/Pages/Login.razor` | A plain form: only a plain request can set the session cookie | | `RedbBff.Web/appsettings.json` | The backend's address and key, and the users | ## Sign-in The users sign in to the web server. The sign-in form POSTs to `/auth/login`, which checks the user and sets the session cookie; every page carries `[Authorize]` (`Components/_Imports.razor`). The users live in configuration (`Web:Users`), a stand-in that keeps the template small; a real application keeps them in a store of its own, for example redb.Identity. The web server calls the backend with the service key as a bearer token. The key never reaches the browser. The development keys in both `appsettings.json` files are for your machine only: set your own through the environment everywhere else (`Backend__ServiceKey`, `Tsak__Contexts__redbbff__Override__Api__ServiceKey`). ## Settings The backend reads its settings from its route context. Both hosts fill it the same way: the module's config file first, then `Tsak:Contexts:redbbff:Override`, which wins. So an environment variable works the same in the own host and on a Tsak worker. The backend listens on 127.0.0.1; in a container it listens on all interfaces but its port stays inside the compose network. ## RedBase settings `RedbBff.Host/Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. On Tsak the same settings are environment variables of the worker (`Tsak__Redb__...`, see `deploy/docker-compose.tsak.yml`). The compose file sets no `Tsak__Cluster__NodeId`: a worker is named after its container's host name, so every replica of `docker compose up --scale` is a Tsak node of its own. Set an explicit id only for a single instance or a StatefulSet; two live workers with one id are refused. ## Another database 1. In `RedbBff.Host.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy All compose files read `deploy/.env` (copy it from `deploy/.env.example`). Run them from the project folder; each has the commands at the top. | File | What runs | |------|-----------| | `deploy/docker-compose.yml` | The backend in its own host with SQLite, and the web server | | `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml` | The same with a database server; switch the provider first (see above) | | `deploy/docker-compose.tsak.yml` | The backend as a module on the Tsak stack image, and the web server. Pack the module first: `pwsh deploy/pack-tpkg.ps1` | The images: `RedbBff.Host/Dockerfile` (the backend) and `RedbBff.Web/Dockerfile` (the web server), both built from the project folder. `pack-tpkg.ps1` puts the manifest, the module config, the module backend DLL and every dependency the worker does not ship itself into the package; `deploy/shipped-module-deps.txt` lists what the worker provides, and `deploy/output/RedbBff.tpkg.contents.txt` shows what went in. To run the module on a Tsak host built locally from the `tsak-worker` template, drop the assemblies that host lacks (`redb.Route.File.dll`, `redb.Route.Controller`-related assemblies, ...) into its `Libs/shared`: the host resolves a module's shared assemblies from `Libs/shared` next to the application, and that template copies `Libs/**` to its output. Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ApiController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ApiController.cs ---- using System.ComponentModel.DataAnnotations; using redb.Core; using redb.Route.Controllers; using redb.Route.Http; using redb.Route.RedbCore.Extensions; using RedbBff.Models; namespace RedbBff.Backend.Controllers; /// /// What the controllers of this backend share. A controller is created for each request, without DI: /// what it needs comes from Context (the route context) and Exchange (the request). /// public abstract class ApiController : RedbController { /// /// The redb service of this request: scoped to the exchange and disposed with it, so parallel requests /// never share a connection. The empty name is the host's default redb. /// protected IRedbService Redb => Context.GetRedbService("", Exchange); /// Sets the status code of the answer; the returned object is still the body. protected T Status(int code, T body) { Exchange.Out ??= Exchange.In.Clone(); Exchange.Out.Headers[HttpHeaders.ResponseCode] = code; return body; } protected ApiError NotFound(string message) => Status(404, new ApiError { Message = message }); /// The web server validates the form, but the backend cannot trust that: the same attributes are checked here. protected ApiError? Invalid(object dto) { var errors = new List(); return Validator.TryValidateObject(dto, new ValidationContext(dto), errors, validateAllProperties: true) ? null : Status(400, new ApiError { Message = string.Join(" ", errors.Select(r => r.ErrorMessage)) }); } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/CategoriesController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/CategoriesController.cs ---- using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Controllers.Attributes; using RedbBff.Backend.Props; using RedbBff.Models; namespace RedbBff.Backend.Controllers; /// The category tree: every root with its subtree, add a node, delete a subtree. [Route("/api/categories")] public sealed class CategoriesController : ApiController { /// The top-level nodes from a tree query, each loaded with its subtree. [HttpGet] public async Task> Tree() { var redb = Redb; var roots = await redb.TreeQuery().WhereRoots().ToListAsync(); var result = new List(); foreach (var root in roots) result.Add(ToNode(await redb.LoadTreeAsync(root.Id))); return result; } /// A top-level node, or a child of ParentId. [HttpPost] public async Task Create([FromBody] NewCategory request) { if (Invalid(request) is { } error) return error; var redb = Redb; var node = new TreeRedbObject { Name = request.Name.Trim(), Props = new Category() }; if (request.ParentId is { } parentId) { var parent = await redb.LoadAsync(parentId); if (parent is null) return NotFound($"Category {parentId} was not found."); await redb.CreateChildAsync(node, parent); } else { await redb.SaveAsync(node); } return Status(201, new CategoryNode { Id = node.Id, Name = node.Name ?? "" }); } /// Deleting a node deletes its whole subtree. [HttpDelete("{id}")] public async Task Delete([FromRoute("id")] long id) => await Redb.DeleteAsync(id) ? null : NotFound($"Category {id} was not found."); private static CategoryNode ToNode(ITreeRedbObject node) => new() { Id = node.Id, Name = node.Name ?? "", Children = node.Children.Select(ToNode).ToList(), }; } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ProductsController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ProductsController.cs ---- using System.Globalization; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Route.Controllers.Attributes; using RedbBff.Backend.Props; using RedbBff.Models; namespace RedbBff.Backend.Controllers; /// /// The products. Attributes route the request: [HttpGet("{id}")] binds the path segment to the /// id parameter, [FromQuery] a query parameter, [FromBody] the JSON body. The return /// value is the JSON answer; null answers 204. /// [Route("/api/products")] public sealed class ProductsController : ApiController { public const int PageSize = 10; /// GET /api/products?search=&inStock=&sort=&page=. Search, sorting and paging run in the database. [HttpGet] public async Task List( [FromQuery("search")] string? search, [FromQuery("inStock")] string? inStock, [FromQuery("sort")] string? sort, [FromQuery("page")] string? page) { var redb = Redb; var term = search?.Trim(); var inStockOnly = inStock == "true"; // The filter is built from scratch for the count and for the page, so the two queries share no state. IRedbQueryable Filtered() { var query = redb.Query(); // Name is the object's own field, so it is filtered with WhereRedb; Props fields use Where. if (!string.IsNullOrEmpty(term)) query = query.WhereRedb(x => x.Name.Contains(term)); if (inStockOnly) query = query.Where(x => x.InStock); return query; } var total = await Filtered().CountAsync(); var pageCount = Math.Max(1, (total + PageSize - 1) / PageSize); var number = Math.Clamp(int.TryParse(page, CultureInfo.InvariantCulture, out var p) ? p : 1, 1, pageCount); IRedbQueryable sorted = sort switch { "price" => Filtered().OrderBy(x => x.Price), "-price" => Filtered().OrderByDescending(x => x.Price), "category" => Filtered().OrderBy(x => x.Category), _ => Filtered().OrderByRedb(x => x.Name), }; var items = await sorted.Skip((number - 1) * PageSize).Take(PageSize).ToListAsync(); return new ProductPage { Items = items.Select(ToDto).ToList(), Total = total, Page = number, PageSize = PageSize }; } [HttpGet("{id}")] public async Task Get([FromRoute("id")] long id) { var product = await Redb.LoadAsync(id); return product is null ? NotFound($"Product {id} was not found.") : ToDto(product); } /// Creates the product and answers 201 with it. [HttpPost] public async Task Create([FromBody] ProductDto dto) { if (Invalid(dto) is { } error) return error; var product = new RedbObject { Props = new Product() }; Apply(product, dto); await Redb.SaveAsync(product); return Status(201, ToDto(product)); } /// With change tracking on, the save writes only the fields that changed. [HttpPut("{id}")] public async Task Update([FromRoute("id")] long id, [FromBody] ProductDto dto) { if (Invalid(dto) is { } error) return error; var redb = Redb; var product = await redb.LoadAsync(id); if (product is null) return NotFound($"Product {id} was not found."); Apply(product, dto); await redb.SaveAsync(product); return ToDto(product); } [HttpDelete("{id}")] public async Task Delete([FromRoute("id")] long id) => await Redb.DeleteAsync(id) ? null : NotFound($"Product {id} was not found."); private static void Apply(RedbObject product, ProductDto dto) { product.Name = dto.Name; product.Props!.Category = dto.Category; product.Props.Price = dto.Price; product.Props.InStock = dto.InStock; product.Props.Description = dto.Description; } private static ProductDto ToDto(RedbObject o) => new() { Id = o.Id, Name = o.Name ?? "", Category = o.Props!.Category, Price = o.Props.Price, InStock = o.Props.InStock, Description = o.Props.Description, }; } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/InitRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Extensions; using redb.Route.Core; using redb.Route.Http; using RedbBff.Backend.Controllers; using RedbBff.Backend.Props; namespace RedbBff.Backend; /// /// The module's entry point. A Tsak worker finds it by convention (a public static class /// InitRoute with a main(IRouteContext) method) and awaits it when the module loads; /// RedbBff.Host calls the same method, so the backend exists once. /// Order: settings, components, the service key, the database, then the route. /// public static class InitRoute { public static async Task main(IRouteContext context) { var settings = ModuleSettings.FromContext(context); 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. The host registers it: the Tsak worker does, and // so does RedbBff.Host (AddRedbRouteHttpHosting). if (!context.HasComponent("http")) context.AddComponent(new HttpComponent { ServerManager = services.GetRequiredService() }); context.AddToRegistry(ServiceKeyValidator.RegistryName, new ServiceKeyValidator(settings.ServiceKey)); // The module's schemes and the sample data, through a scope of its own: the connection goes back to // the pool as soon as this is done. await using (var scope = services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await SeedAsync(redb); } // Every controller of this assembly behind one HTTP endpoint. The dispatcher matches the method and // the path against the [Route] and [HttpGet] attributes; no match answers 404. var registry = new ControllerRegistry(); registry.RegisterAssembly(typeof(ProductsController).Assembly); ((RouteContext)context).AddRoutes(r => r .From($"http:{settings.ApiHost}:{settings.ApiPort}/{{**path}}?inOut=true" + $"&inboundAuth=bearer&tokenValidator=#{ServiceKeyValidator.RegistryName}&inboundRealm=backend") .RouteId("backend-api") .RedbHttpController(registry)); context.GetService()?.CreateLogger("RedbBff").LogInformation( "RedbBff backend ready on {Host}:{Port}", settings.ApiHost, settings.ApiPort); return context; } // Sample data on the first run, so the pages are not empty. private static async Task SeedAsync(IRedbService redb) { if (!await redb.Query().AnyAsync()) { var samples = new (string Name, string Category, decimal Price, bool InStock)[] { ("Laptop 14", "Laptops", 1299m, true), ("Laptop 16", "Laptops", 1899m, false), ("Monitor 27", "Monitors", 349m, true), ("Keyboard", "Accessories", 79m, true), ("Mouse", "Accessories", 39m, true), }; foreach (var s in samples) { await redb.SaveAsync(new RedbObject { Name = s.Name, Props = new Product { Category = s.Category, Price = s.Price, InStock = s.InStock }, }); } } if (!await redb.TreeQuery().AnyAsync()) { var root = new TreeRedbObject { Name = "Electronics", Props = new Category { SortOrder = 1 } }; await redb.SaveAsync(root); var computers = new TreeRedbObject { Name = "Computers", Props = new Category { SortOrder = 1 } }; await redb.CreateChildAsync(computers, root); await redb.CreateChildAsync(new TreeRedbObject { Name = "Laptops", Props = new Category { SortOrder = 1 } }, computers); await redb.CreateChildAsync(new TreeRedbObject { Name = "Monitors", Props = new Category { SortOrder = 2 } }, root); } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/ModuleSettings.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/ModuleSettings.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RedbBff.Backend; /// /// The module's settings, read from the properties of its route context. Both hosts fill them the same /// way: RedbBff.Backend.config.json first, then the Tsak:Contexts:{context}:Override section of the /// host configuration, which wins. The service key belongs only in the Override layer (RedbBff.Host /// appsettings.json, or Tsak__Contexts__redbbff__Override__Api__ServiceKey), never in the module's /// config file. /// public sealed record ModuleSettings(string ApiHost, int ApiPort, string ServiceKey) { public static ModuleSettings FromContext(IRouteContext context) { var api = context.GetProperty>("Api") ?? throw Missing(context, "Api"); var serviceKey = Required(context, api, "ServiceKey"); if (serviceKey.Length < 32) throw new InvalidOperationException($"Api:ServiceKey of context '{context.ContextId}' must be at least 32 characters."); return new( // 127.0.0.1 by default: only the web server of the same machine calls the backend. A container // sets 0.0.0.0 and keeps the port inside the compose network (deploy/*.yml). ApiHost: Required(context, api, "Host"), ApiPort: int.Parse(Required(context, api, "Port"), CultureInfo.InvariantCulture), ServiceKey: serviceKey); } private static string Required(IRouteContext context, IDictionary section, string key) => section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text ? text : throw Missing(context, $"Api:{key}"); private static InvalidOperationException Missing(IRouteContext context, string key) => new( $"{key} is not configured for context '{context.ContextId}': set it in RedbBff.Backend.config.json " + $"or in Tsak:Contexts:{context.ContextId}:Override."); } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Props/Product.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Props/Product.cs ---- using redb.Core.Attributes; namespace RedbBff.Backend.Props; /// /// The Props of a product. The object's name is not here: it is the object's own field /// (RedbObject.Name). Each property is stored in a typed column, so filters and sorting on them run /// in the database. /// [RedbScheme("Product")] public class Product { public string Category { get; set; } = string.Empty; public decimal Price { get; set; } public bool InStock { get; set; } public string? Description { get; set; } } /// /// A node of the category tree. The hierarchy itself is part of the object, not of the Props: a node is a /// TreeRedbObject<Category>, and deleting a node deletes its subtree. /// [RedbScheme("Category")] public class Category { public int SortOrder { get; set; } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/RedbBff.Backend.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/RedbBff.Backend.config.json ---- { "ContextName": "redbbff", "AutoStart": true, "Api": { "Host": "127.0.0.1", "Port": 5093 } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/RedbBff.Backend.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/RedbBff.Backend.csproj ---- Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/ServiceKeyValidator.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/ServiceKeyValidator.cs ---- using System.Security.Claims; using System.Security.Cryptography; using System.Text; using redb.Route.Http; namespace RedbBff.Backend; /// /// The backend has one caller: the web server. It sends the shared service key as a bearer token; any /// other request gets 401 before a controller runs. The users sign in to the web server, not here. /// public sealed class ServiceKeyValidator(string serviceKey) : IHttpTokenValidator { public const string RegistryName = "service-key"; private readonly byte[] _expected = Encoding.UTF8.GetBytes(serviceKey); public Task ValidateAsync(string token, CancellationToken ct) { // Constant-time comparison, so the answer time does not tell how much of the key was right. var accepted = CryptographicOperations.FixedTimeEquals(_expected, Encoding.UTF8.GetBytes(token)); return Task.FromResult(accepted ? new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, "web")], authenticationType: "ServiceKey")) : null); } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/manifest.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/manifest.json ---- { "Name": "RedbBff", "Version": "1.0.0", "EntryPoints": ["RedbBff.Backend.dll"], "Dependencies": [] } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/ContextConfiguration.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace RedbBff.Host; /// /// The context configuration the way a Tsak worker builds it, in miniature. Each layer deep-merges over /// the previous one, later layers win: /// /// the module's RedbBff.Backend.config.json, /// Tsak:Contexts:{context}:Override of the host configuration. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. So the /// same keys and the same environment variables work here and on a Tsak worker. /// public static class ContextConfiguration { /// The context the 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 = Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"))); 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) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var child in section.GetChildren()) result[child.Key] = child.GetChildren().Any() ? Read(child) : 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; } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/Dockerfile ---- # The backend in its own host. Build from the solution folder: # docker build -f RedbBff.Host/Dockerfile -t redbbff-backend . FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbBff.Models/RedbBff.Models.csproj RedbBff.Models/ COPY RedbBff.Backend/RedbBff.Backend.csproj RedbBff.Backend/ COPY RedbBff.Host/RedbBff.Host.csproj RedbBff.Host/ RUN dotnet restore RedbBff.Host/RedbBff.Host.csproj COPY . . RUN dotnet publish RedbBff.Host/RedbBff.Host.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/runtime:10.0 WORKDIR /app COPY --from=build /app . # The database goes to a volume. The app runs as the non-root user of the .NET image, which must be # able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/redbbff.db" # Inside a container the backend must listen on all interfaces to be reachable from the web container; # the compose files do not publish its port. ENV Tsak__Contexts__redbbff__Override__Api__Host=0.0.0.0 VOLUME /data EXPOSE 5093 ENTRYPOINT ["dotnet", "RedbBff.Host.dll"] Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/Program.cs ---- // The backend's own host. It does what a Tsak worker does for the module, and nothing more: // 1) reads appsettings.json, then environment variables, // 2) registers redb and the HTTP server of the process, initializes redb, // 3) builds the context configuration (module config file, then the Override section), // 4) awaits RedbBff.Backend.InitRoute.main(ctx), the method the Tsak worker calls, // 5) starts the context and runs until Ctrl+C or SIGTERM. using System.Runtime.InteropServices; 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.Route.Core; using redb.Route.Http; using redb.SQLite.Pro.Extensions; using RedbBff.Backend; using RedbBff.Host; var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var connectionString = configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbBff.Host.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); // The HTTP servers of the process, one per port, as the Tsak worker registers them. services.AddRedbRouteHttpHosting(); await using var provider = services.BuildServiceProvider(); // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService().InitializeAsync(ensureCreated: true); } var moduleConfig = Path.Combine(AppContext.BaseDirectory, "RedbBff.Backend.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); var context = new RouteContext(provider, contextName, provider.GetRequiredService()); ContextConfiguration.ApplyTo(context, ContextConfiguration.Build(configuration, contextName, moduleConfig)); await InitRoute.main(context); // <- the exact method the Tsak worker calls await context.Start(); var settings = ModuleSettings.FromContext(context); Console.WriteLine(); Console.WriteLine($"RedbBff backend on http://{settings.ApiHost}:{settings.ApiPort}/api (only the web server calls it, with the service key)."); Console.WriteLine("Start the web server in a second terminal: dotnet run --project RedbBff.Web"); Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); var stop = new TaskCompletionSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; // docker stop sends SIGTERM, not Ctrl+C. using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, c => { c.Cancel = true; stop.TrySetResult(); }); await stop.Task; await context.DisposeAsync(); Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/RedbBff.Host.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/RedbBff.Host.csproj ---- Exe Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=redbbff.db" }, "Tsak": { "Contexts": { "redbbff": { // The Override layer of the backend's settings: it wins over RedbBff.Backend.config.json. The same // keys work on a Tsak worker as environment variables, for example // Tsak__Contexts__redbbff__Override__Api__ServiceKey. "Override": { "Api": { // The key the web server sends, at least 32 characters. It must match Backend:ServiceKey in // RedbBff.Web/appsettings.json. This one is for your machine only: set your own through the // environment everywhere else. "ServiceKey": "local-development-service-key-change-me" } } } } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Models/Dtos.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Models/Dtos.cs ---- using System.ComponentModel.DataAnnotations; namespace RedbBff.Models; /// A product as the API sends and receives it. Validation runs on the form and again in the backend. public sealed class ProductDto { public long Id { get; set; } [Required, StringLength(200)] public string Name { get; set; } = ""; [Required, StringLength(100)] public string Category { get; set; } = ""; [Range(0, 1_000_000)] public decimal Price { get; set; } public bool InStock { get; set; } [StringLength(2000)] public string? Description { get; set; } } /// One page of the product list, and the total the filter matches. public sealed class ProductPage { public List Items { get; set; } = []; public int Total { get; set; } public int Page { get; set; } public int PageSize { get; set; } } /// A node of the category tree with its children. public sealed class CategoryNode { public long Id { get; set; } public string Name { get; set; } = ""; public List Children { get; set; } = []; } public sealed class NewCategory { [Required, StringLength(100)] public string Name { get; set; } = ""; /// The parent node; null for a top-level category. public long? ParentId { get; set; } } /// The body of an error answer. public sealed class ApiError { public string Message { get; set; } = ""; } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Models/RedbBff.Models.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Models/RedbBff.Models.csproj ---- Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/App.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/App.razor ---- @code { [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; // Every page is interactive except the sign-in page ([ExcludeFromInteractiveRouting]): it is a plain // form that POSTs to /auth/login, because only a plain request can set the session cookie. private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Layout/MainLayout.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Layout/MainLayout.razor ---- @inherits LayoutComponentBase
RedbBff Products Categories @context.User.Identity?.Name @* A plain POST: sign-out clears the cookie, which only a plain request can do. *@
@Body
Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Categories.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Categories.razor ---- @page "/categories" @inject BackendClient Api Categories

Categories

@if (error is not null) {

@error

} @code { private List roots = []; private string? newRootName; private string? error; protected override Task OnInitializedAsync() => LoadAsync(); private Task LoadAsync() => RunAsync(async () => roots = await Api.CategoriesAsync()); private async Task AddAsync(long? parentId, string name) { await RunAsync(() => Api.AddCategoryAsync(new NewCategory { Name = name.Trim(), ParentId = parentId })); if (parentId is null) newRootName = null; await LoadAsync(); } // Deleting a node deletes its whole subtree. private async Task DeleteAsync(long id) { await RunAsync(() => Api.DeleteCategoryAsync(id)); await LoadAsync(); } private async Task RunAsync(Func call) { error = null; try { await call(); } catch (BackendException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/CategoryNodeList.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/CategoryNodeList.razor ---- @* Renders a level of the tree and calls itself for the children. *@
    @foreach (var node in Nodes) {
  • @node.Name @if (adding == node.Id) { } @if (node.Children.Count > 0) { }
  • }
@code { [Parameter, EditorRequired] public List Nodes { get; set; } = []; [Parameter] public EventCallback<(long ParentId, string Name)> OnAddChild { get; set; } [Parameter] public EventCallback OnDelete { get; set; } private long? adding; private string? childName; private async Task AddAsync(long parentId) { var name = childName!.Trim(); Cancel(); await OnAddChild.InvokeAsync((parentId, name)); } private void Cancel() { adding = null; childName = null; } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Error.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Error.razor ---- @page "/Error" @attribute [AllowAnonymous] Error

Something went wrong

The request could not be completed. Check the application log for details.

Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Login.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Login.razor ---- @page "/login" @attribute [AllowAnonymous] @attribute [ExcludeFromInteractiveRouting] Sign in

Sign in

@if (Error is not null) {

@(Error == "stale" ? "The form expired. Please try again." : "Wrong login or password.")

} @* data-enhance=false: a full-page POST, so the answer can set the session cookie. *@

The users are in RedbBff.Web/appsettings.json (Web:Users).

@code { [SupplyParameterFromQuery] private string? Error { get; set; } [SupplyParameterFromQuery] private string? ReturnUrl { get; set; } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/ProductEdit.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/ProductEdit.razor ---- @page "/products/new" @page "/products/{Id:long}" @inject BackendClient Api @inject NavigationManager Navigation @(Id is null ? "New product" : "Edit product")

@(Id is null ? "New product" : "Edit product")

@if (error is not null) {

@error

} @if (product is not null) {
Cancel
} @code { [Parameter] public long? Id { get; set; } private ProductDto? product; private string? error; protected override async Task OnParametersSetAsync() { if (Id is null) { product = new ProductDto(); return; } try { product = await Api.ProductAsync(Id.Value); } catch (BackendException ex) { error = ex.Message; } } private async Task SaveAsync() { try { await Api.SaveProductAsync(product!); Navigation.NavigateTo(""); } catch (BackendException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Products.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Pages/Products.razor ---- @page "/" @inject BackendClient Api Products

Products

New product
@if (error is not null) {

@error

}

@data.Total product(s)

@foreach (var item in data.Items) { }
NameCategoryPriceIn stock
@item.Name @item.Category @item.Price.ToString("F2") @(item.InStock ? "yes" : "no")
@code { private string? search; private bool inStockOnly; private string sort = "name"; private ProductPage data = new() { Page = 1, PageSize = 10 }; private string? error; private int PageCount => Math.Max(1, (data.Total + data.PageSize - 1) / Math.Max(1, data.PageSize)); protected override Task OnInitializedAsync() => LoadAsync(1); private Task ReloadFromFirstPage() => LoadAsync(1); private Task GoToAsync(int page) => LoadAsync(page); private async Task DeleteAsync(long id) { await RunAsync(() => Api.DeleteProductAsync(id)); await LoadAsync(data.Page); } // Search, sorting and paging run in the backend, and there in the database. private Task LoadAsync(int page) => RunAsync(async () => data = await Api.ProductsAsync(search, inStockOnly, sort, page)); private async Task RunAsync(Func call) { error = null; try { await call(); } catch (BackendException ex) { error = ex.Message; } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/RedirectToLogin.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/RedirectToLogin.razor ---- @inject NavigationManager Navigation @code { // A full page load: the sign-in page is not interactive. protected override void OnInitialized() => Navigation.NavigateTo($"login?returnUrl={Uri.EscapeDataString("/" + Navigation.ToBaseRelativePath(Navigation.Uri))}", forceLoad: true); } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Routes.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/Routes.razor ---- @* Checks the page's [Authorize]; a user without a session is sent to the sign-in page. *@ Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/_Imports.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Components/_Imports.razor ---- @using System.ComponentModel.DataAnnotations @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using static Microsoft.AspNetCore.Components.Web.RenderMode @using RedbBff.Models @using RedbBff.Web @using RedbBff.Web.Components @using RedbBff.Web.Services @* Every page needs a session; the sign-in and error pages opt out with [AllowAnonymous]. *@ @attribute [Authorize] Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Dockerfile ---- # The web server. Build from the solution folder: # docker build -f RedbBff.Web/Dockerfile -t redbbff-web . FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbBff.Models/RedbBff.Models.csproj RedbBff.Models/ COPY RedbBff.Web/RedbBff.Web.csproj RedbBff.Web/ RUN dotnet restore RedbBff.Web/RedbBff.Web.csproj COPY . . RUN dotnet publish RedbBff.Web/RedbBff.Web.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app . USER $APP_UID ENV ASPNETCORE_URLS=http://+:8080 EXPOSE 8080 ENTRYPOINT ["dotnet", "RedbBff.Web.dll"] Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Program.cs ---- using System.Net.Http.Headers; using System.Security.Claims; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using RedbBff.Web.Components; using RedbBff.Web.Services; var builder = WebApplication.CreateBuilder(args); // --- Session: an ASP.NET Core auth cookie --- // The browser holds only the cookie; the service key to the backend stays on this server. Pages are // protected by the [Authorize] attribute in Components/_Imports.razor. builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Strict; // Secure when the request is HTTPS. Behind a TLS-terminating proxy, add UseForwardedHeaders so the // request scheme is the real one. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.LoginPath = "/login"; options.ExpireTimeSpan = TimeSpan.FromHours(8); options.SlidingExpiration = true; }); builder.Services.AddAuthorization(); builder.Services.AddCascadingAuthenticationState(); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); builder.Services.AddSingleton(); // --- The backend --- var backendUrl = builder.Configuration["Backend:BaseUrl"] ?? throw new InvalidOperationException("Backend:BaseUrl is missing in appsettings.json."); var serviceKey = builder.Configuration["Backend:ServiceKey"] ?? throw new InvalidOperationException("Backend:ServiceKey is missing in appsettings.json."); builder.Services.AddHttpClient(http => { http.BaseAddress = new Uri(backendUrl); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", serviceKey); }); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); } app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); app.MapStaticAssets(); // --- Sign-in and sign-out --- // SignInAsync writes the Set-Cookie header, which only a plain HTTP request can do: an interactive // circuit has started its response long ago. So the sign-in form of Login.razor POSTs here. These two // endpoints belong to the web server's session; the data goes through the backend. app.MapPost("/auth/login", async (HttpContext http, IAntiforgery antiforgery, WebUsers users) => { // Absolute redirects: a relative "login" would resolve under /auth/. if (!await antiforgery.IsRequestValidAsync(http)) return Results.Redirect("/login?error=stale"); var form = await http.Request.ReadFormAsync(); var login = form["login"].ToString().Trim(); var role = users.Check(login, form["password"].ToString()); if (role is null) return Results.Redirect("/login?error=1"); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Name, login)); identity.AddClaim(new Claim(ClaimTypes.Role, role)); await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); // Only ever a local path, never an address from the form. var returnUrl = form["returnUrl"].ToString(); return Uri.IsWellFormedUriString(returnUrl, UriKind.Relative) && returnUrl.StartsWith('/') && !returnUrl.StartsWith("//") ? Results.LocalRedirect(returnUrl) : Results.Redirect("/"); }).DisableAntiforgery(); // checked above, so a stale form gets its own message app.MapPost("/auth/logout", async (HttpContext http) => { await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Redirect("/login"); }); app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run(); Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Properties/launchSettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Properties/launchSettings.json ---- { "profiles": { "RedbBff.Web": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "http://localhost:5083", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/RedbBff.Web.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/RedbBff.Web.csproj ---- Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Services/BackendClient.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Services/BackendClient.cs ---- using System.Net.Http.Json; using RedbBff.Models; namespace RedbBff.Web.Services; /// /// The backend calls of the web server. The HttpClient comes configured from Program.cs: the backend's /// address and the service key as the bearer token. /// public sealed class BackendClient(HttpClient http) { public Task ProductsAsync(string? search, bool inStockOnly, string sort, int page) => GetAsync($"api/products?search={Uri.EscapeDataString(search ?? "")}" + $"&inStock={(inStockOnly ? "true" : "false")}&sort={Uri.EscapeDataString(sort)}&page={page}"); public Task ProductAsync(long id) => GetAsync($"api/products/{id}"); public Task SaveProductAsync(ProductDto product) => product.Id == 0 ? SendAsync(HttpMethod.Post, "api/products", product) : SendAsync(HttpMethod.Put, $"api/products/{product.Id}", product); public Task DeleteProductAsync(long id) => SendAsync(HttpMethod.Delete, $"api/products/{id}", null); public Task> CategoriesAsync() => GetAsync>("api/categories"); public Task AddCategoryAsync(NewCategory category) => SendAsync(HttpMethod.Post, "api/categories", category); public Task DeleteCategoryAsync(long id) => SendAsync(HttpMethod.Delete, $"api/categories/{id}", null); private async Task GetAsync(string uri) { using var response = await http.GetAsync(uri); await EnsureSuccessAsync(response); return (await response.Content.ReadFromJsonAsync())!; } private async Task SendAsync(HttpMethod method, string uri, object? body) { using var request = new HttpRequestMessage(method, uri); if (body is not null) request.Content = JsonContent.Create(body, body.GetType()); using var response = await http.SendAsync(request); await EnsureSuccessAsync(response); } private static async Task EnsureSuccessAsync(HttpResponseMessage response) { if (response.IsSuccessStatusCode) return; var error = response.Content.Headers.ContentType?.MediaType == "application/json" ? await response.Content.ReadFromJsonAsync() : null; throw new BackendException(error?.Message ?? $"The backend answered {(int)response.StatusCode} {response.ReasonPhrase}."); } } /// A backend call that did not succeed; the message is meant for the user. public sealed class BackendException(string message) : Exception(message); Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/Services/WebUsers.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/Services/WebUsers.cs ---- using System.Security.Cryptography; using System.Text; namespace RedbBff.Web.Services; /// /// The users who can sign in, from Web:Users in configuration. A stand-in that keeps the template /// small: a real application keeps its users in a store of its own, for example redb.Identity. /// public sealed class WebUsers(IConfiguration configuration) { /// The user's role when the login and password match, otherwise null. public string? Check(string login, string password) { var user = configuration.GetSection($"Web:Users:{login}"); var expected = user["Password"]; if (string.IsNullOrEmpty(login) || expected is null) return null; // Constant-time comparison, so the answer time does not tell how much of the password was right. return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(password)) ? user["Role"] ?? throw new InvalidOperationException($"Web:Users:{login}:Role is not set.") : null; } } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/appsettings.json ---- { "Backend": { "BaseUrl": "http://127.0.0.1:5093/", // Sent to the backend as a bearer token; the same value as Api:ServiceKey in // RedbBff.Host/appsettings.json. For your machine only: set your own through the environment // (Backend__ServiceKey) everywhere else. "ServiceKey": "local-development-service-key-change-me" }, "Web": { // Who can sign in. A stand-in that keeps the template small: a real application keeps its users in a // store of its own, for example redb.Identity. "Users": { "admin": { "Password": "admin", "Role": "admin" } } }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } Path: redb/redb.Templates/templates/redb-bff/RedbBff.Web/wwwroot/app.css Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Web/wwwroot/app.css ---- body { font-family: system-ui, sans-serif; margin: 0; color: #1f2328; background: #fff; } header { display: flex; gap: 1.5rem; align-items: center; padding: 0.75rem 1.5rem; border-bottom: 1px solid #d0d7de; } header .brand { font-weight: 600; color: #b3261e; text-decoration: none; } main { max-width: 960px; margin: 0 auto; padding: 1rem 1.5rem; } a { color: #0969da; } .filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 0.5rem; } .muted { color: #656d76; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #d0d7de; } .num { text-align: right; } .pager { display: flex; gap: 0.5rem; margin-top: 1rem; } .pager span { font-weight: 600; } .form { display: grid; gap: 0.35rem; max-width: 480px; } .form input:not([type=checkbox]), .form textarea { padding: 0.35rem; font: inherit; } .form .actions { display: flex; gap: 1rem; align-items: center; margin-top: 0.75rem; } .field-validation-error, .validation-summary-errors { color: #b3261e; } button.link { background: none; border: 0; padding: 0; color: #b3261e; cursor: pointer; font: inherit; } header a.active { font-weight: 600; } .pager button { font: inherit; } .tree { list-style: none; padding-left: 1.25rem; } .tree li { margin: 0.25rem 0; } .tree button.link { margin-left: 0.5rem; } .inline { display: inline-flex; gap: 0.4rem; margin-left: 0.5rem; } header .who { margin-left: auto; color: #656d76; } .error { color: #b3261e; } header form { display: inline; } Path: redb/redb.Templates/templates/redb-bff/RedbBff.slnx Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.slnx ---- Path: redb/redb.Templates/templates/redb-bff/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/docker-compose.mssql.yml ---- # The backend with SQL Server instead of SQLite, and the web server. # Before the first run, switch the provider in code (see the comment in RedbBff.Host/Program.cs): # RedbBff.Host.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then (deploy/.env as for docker-compose.yml): docker compose -f deploy/docker-compose.mssql.yml up --build # Then open http://localhost:8080. services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql backend: build: context: .. dockerfile: RedbBff.Host/Dockerfile environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" Tsak__Contexts__redbbff__Override__Api__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} depends_on: - db web: build: context: .. dockerfile: RedbBff.Web/Dockerfile ports: - "8080:8080" environment: Backend__BaseUrl: "http://backend:5093/" Backend__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} Web__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: - backend volumes: mssqldata: Path: redb/redb.Templates/templates/redb-bff/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/docker-compose.postgres.yml ---- # The backend with PostgreSQL instead of SQLite, and the web server. # Before the first run, switch the provider in code (see the comment in RedbBff.Host/Program.cs): # RedbBff.Host.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder (deploy/.env as for docker-compose.yml): # docker compose -f deploy/docker-compose.postgres.yml up --build # Then open http://localhost:8080. services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 backend: build: context: .. dockerfile: RedbBff.Host/Dockerfile environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" Tsak__Contexts__redbbff__Override__Api__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} depends_on: db: condition: service_healthy web: build: context: .. dockerfile: RedbBff.Web/Dockerfile ports: - "8080:8080" environment: Backend__BaseUrl: "http://backend:5093/" Backend__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} Web__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: - backend volumes: pgdata: Path: redb/redb.Templates/templates/redb-bff/deploy/docker-compose.tsak.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/docker-compose.tsak.yml ---- # The backend as a module on a Tsak worker, and the web server. The Tsak stack image (worker and # dashboard in one container) loads RedbBff.tpkg from deploy/output. The worker's default redb is SQLite, # so nothing else is needed. # # From the project folder: # cp deploy/.env.example deploy/.env # then fill in the Tsak values, BFF_SERVICE_KEY, APP_ADMIN_PASSWORD # pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbBff.tpkg # docker compose -f deploy/docker-compose.tsak.yml up -d --build # # Then open http://localhost:8080. Dashboard: http://localhost:8085 (admin and TSAK_WEB_ADMIN_PASSWORD). services: backend: image: ghcr.io/redbase-app/redb-tsak-stack:${TSAK_VERSION:-4.8.0-net10} restart: unless-stopped ports: - "127.0.0.1:9090:9090" # worker API - "127.0.0.1:8085:8085" # dashboard environment: # The worker's default (unnamed) redb, the one the module works in. The same settings as the own # host: Pro, change tracking, the PVT prefilter. The props cache stays off; to turn it on add # Tsak__Redb__EnablePropsCache=true. - Tsak__Redb__UsePro=true - Tsak__Redb__PropsSaveStrategy=ChangeTracking - Tsak__Redb__EnablePvtPrefilter=true - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://backend:9090 # No Tsak__Cluster__NodeId: a node is named after its container's host name, so each replica of # `docker compose up --scale` is a node of its own. A fixed id suits one instance or a StatefulSet only. # 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, the same keys the own host reads. - Tsak__Contexts__redbbff__Override__Api__Host=0.0.0.0 - Tsak__Contexts__redbbff__Override__Api__ServiceKey=${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} volumes: - ./output:/app/modules web: build: context: .. dockerfile: RedbBff.Web/Dockerfile ports: - "8080:8080" environment: Backend__BaseUrl: "http://backend:5093/" Backend__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} Web__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: - backend Path: redb/redb.Templates/templates/redb-bff/deploy/docker-compose.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/docker-compose.yml ---- # The backend in its own host with SQLite, and the web server. Only the web server is published; the # backend is reachable inside the compose network alone. # From the project folder: # cp deploy/.env.example deploy/.env # then set BFF_SERVICE_KEY and APP_ADMIN_PASSWORD # docker compose -f deploy/docker-compose.yml up --build # Then open http://localhost:8080 and sign in as admin. services: backend: build: context: .. dockerfile: RedbBff.Host/Dockerfile environment: Tsak__Contexts__redbbff__Override__Api__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} volumes: - backenddata:/data web: build: context: .. dockerfile: RedbBff.Web/Dockerfile ports: - "8080:8080" environment: Backend__BaseUrl: "http://backend:5093/" Backend__ServiceKey: ${BFF_SERVICE_KEY:?BFF_SERVICE_KEY required} Web__Users__admin__Password: ${APP_ADMIN_PASSWORD:?APP_ADMIN_PASSWORD required} depends_on: - backend volumes: backenddata: Path: redb/redb.Templates/templates/redb-bff/deploy/pack-tpkg.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds RedbBff.Backend and packs it into RedbBff.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, RedbBff.Backend.dll and every dependency the worker does not ship itself (RedbBff.Models, for example). deploy/shipped-module-deps.txt lists what the worker ships (its header says how to regenerate the list); the package contents are written next to it as RedbBff.tpkg.contents.txt. .EXAMPLE ./deploy/pack-tpkg.ps1 ./deploy/pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $module = Join-Path $root "RedbBff.Backend" $entryDll = "RedbBff.Backend.dll" $publish = Join-Path ([IO.Path]::GetTempPath()) "redbbff-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "redbbff-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "RedbBff.tpkg" $shippedList = Join-Path $PSScriptRoot "shipped-module-deps.txt" # 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 $module "RedbBff.Backend.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of RedbBff.Backend failed." } # The worker resolves only the assemblies it ships (shipped-module-deps.txt). Every other dependency, # RedbBff.Models included, has to travel inside the package, otherwise the module fails to load. $shipped = @(Get-Content $shippedList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $extra = @(Get-ChildItem $publish -Filter *.dll | Where-Object { $_.Name -ne $entryDll -and $shipped -notcontains $_.Name }) 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 $module "manifest.json") $staging Copy-Item (Join-Path $module "RedbBff.Backend.config.json") $staging Copy-Item (Join-Path $publish $entryDll) $staging foreach ($dependency in $extra) { Copy-Item $dependency.FullName $staging } # Native assets of a dependency (runtimes//native/...), if the module brought any. $runtimes = Join-Path $publish "runtimes" if (Test-Path $runtimes) { Copy-Item $runtimes $staging -Recurse } if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) # What the package holds, next to it: handy when a Tsak node refuses to load the module. $contents = Get-ChildItem $staging -Recurse -File | ForEach-Object { $_.FullName.Substring($staging.Length + 1).Replace('\', '/') } Set-Content -Path ($package + ".contents.txt") -Value $contents -Encoding utf8 Write-Host "Packed $package" Write-Host " module: $entryDll" Write-Host (" packed dependencies: {0}" -f $extra.Count) foreach ($dependency in $extra) { Write-Host (" " + $dependency.Name) } Write-Host (" not packed: {0} assemblies shipped by the worker" -f $shipped.Count) Path: redb/redb.Templates/templates/redb-bff/deploy/shipped-module-deps.txt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/deploy/shipped-module-deps.txt ---- # Assemblies the redb.Tsak worker already provides: /app/*.dll and /app/Libs/shared/*.dll of # redb-tsak-worker:4.8.0, and the assemblies of the ASP.NET Core shared framework of its base image that this # list carries (Microsoft.Extensions.*, System.Diagnostics.EventLog, System.Security.Cryptography.Pkcs). The # worker binds those from /usr/share/dotnet/shared: since 4.8 the SDK publishes no copy of them into /app, and a # copy inside a module would give ILogger, IConfiguration or IOptions a second type identity. A module # dependency present here is NOT packed into the .tpkg; every other dependency travels inside the package. # # The worker resolves these from its own folder and from Libs/shared next to the application # (Libs/shared under the app directory, not the current one). A Tsak host built locally from the # tsak-worker template ships a smaller set: put the assemblies a module needs (redb.Route.File, # redb.Route.GenericFile, ...) into that host project Libs/shared - the template copies Libs/** to # the output - or pack them by removing them from this list. # # Regenerate when the worker image changes: the command gives the /app part; merge it in and keep the # shared-framework entries the list already has. # docker run --rm --entrypoint sh redb-tsak-worker: -c "ls /app/*.dll /app/Libs/shared/*.dll" | sed "s|.*/||" | sort -u # AWSSDK.Core.dll AWSSDK.S3.dll AWSSDK.SQS.dll AWSSDK.SimpleNotificationService.dll Amqp.Net.dll Azure.Core.Amqp.dll Azure.Core.dll Azure.Messaging.ServiceBus.dll BCrypt-Net-Next.dll BouncyCastle.Cryptography.dll Chr.Avro.Binary.dll Chr.Avro.Json.dll Chr.Avro.dll Confluent.Kafka.dll CsvHelper.dll Elastic.Clients.Elasticsearch.dll Elastic.Esql.dll Elastic.Transport.dll FirebaseAdmin.dll FluentFTP.dll FluentValidation.dll Google.Api.CommonProtos.dll Google.Api.Gax.Grpc.dll Google.Api.Gax.Rest.dll Google.Api.Gax.dll Google.Apis.Auth.dll Google.Apis.Core.dll Google.Apis.Storage.v1.dll Google.Apis.dll Google.Cloud.Firestore.V1.dll Google.Cloud.Firestore.dll Google.Cloud.Location.dll Google.Cloud.Storage.V1.dll Google.LongRunning.dll Google.Protobuf.dll Grpc.Auth.dll Grpc.Core.Api.dll Grpc.Net.Client.dll Grpc.Net.Common.dll Humanizer.dll Json.More.dll JsonPath.Net.dll JsonPointer.Net.dll JsonSchema.Net.dll Jsonata.Net.Native.SystemTextJson.dll Jsonata.Net.Native.dll MQTTnet.dll MailKit.dll MessagePack.Annotations.dll MessagePack.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Protocols.MessagePack.dll Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll Microsoft.Azure.Amqp.dll Microsoft.Bcl.AsyncInterfaces.dll Microsoft.Bcl.Cryptography.dll Microsoft.Data.SqlClient.Extensions.Abstractions.dll Microsoft.Data.SqlClient.Internal.Logging.dll Microsoft.Data.SqlClient.dll Microsoft.Data.Sqlite.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.CommandLine.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.Configuration.UserSecrets.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.Diagnostics.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.dll Microsoft.Extensions.Diagnostics.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.Console.dll Microsoft.Extensions.Logging.Debug.dll Microsoft.Extensions.Logging.EventLog.dll Microsoft.Extensions.Logging.EventSource.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.Identity.Client.Extensions.Msal.dll Microsoft.Identity.Client.dll Microsoft.IdentityModel.Abstractions.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Protocols.OpenIdConnect.dll Microsoft.IdentityModel.Protocols.dll Microsoft.IdentityModel.Tokens.dll Microsoft.NET.StringTools.dll Microsoft.SqlServer.Server.dll MimeKit.dll Newtonsoft.Json.dll Novell.Directory.Ldap.NETStandard.dll Npgsql.dll OpenTelemetry.Api.ProviderBuilderExtensions.dll OpenTelemetry.Api.dll OpenTelemetry.Exporter.OpenTelemetryProtocol.dll OpenTelemetry.Exporter.Prometheus.HttpListener.dll OpenTelemetry.Extensions.Hosting.dll OpenTelemetry.Instrumentation.Process.dll OpenTelemetry.Instrumentation.Runtime.dll OpenTelemetry.dll Pipelines.Sockets.Unofficial.dll Quartz.Extensions.DependencyInjection.dll Quartz.Extensions.Hosting.dll Quartz.Serialization.Json.dll Quartz.dll RabbitMQ.Client.OAuth2.dll RabbitMQ.Client.dll Renci.SshNet.dll SQLitePCLRaw.batteries_v2.dll SQLitePCLRaw.core.dll SQLitePCLRaw.provider.e_sqlite3.dll Scriban.dll Serilog.AspNetCore.dll Serilog.Enrichers.Environment.dll Serilog.Enrichers.Process.dll Serilog.Enrichers.Thread.dll Serilog.Extensions.Hosting.dll Serilog.Extensions.Logging.dll Serilog.Formatting.Compact.dll Serilog.Settings.Configuration.dll Serilog.Sinks.Console.dll Serilog.Sinks.Debug.dll Serilog.Sinks.File.dll Serilog.dll StackExchange.Redis.dll System.ClientModel.dll System.CodeDom.dll System.Configuration.ConfigurationManager.dll System.Diagnostics.EventLog.dll System.IO.Hashing.dll System.IdentityModel.Tokens.Jwt.dll System.Management.dll System.Memory.Data.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll Telegram.Bot.dll XPath2.dll YamlDotNet.dll amqmdnetstd.dll amqmxmsstd.dll redb.Core.Pro.dll redb.Core.dll redb.Licensing.dll redb.MSSql.Pro.dll redb.MSSql.dll redb.Postgres.Pro.dll redb.Postgres.dll redb.Route.Amqp.dll redb.Route.As2.dll redb.Route.As4.dll redb.Route.AzureServiceBus.dll redb.Route.Cache.dll redb.Route.Controllers.dll redb.Route.Core.dll redb.Route.DataFormats.Avro.dll redb.Route.DataFormats.Csv.dll redb.Route.DataFormats.Mime.dll redb.Route.DataFormats.Protobuf.dll redb.Route.DataFormats.XmlJson.dll redb.Route.DataFormats.Yaml.dll redb.Route.Elasticsearch.dll redb.Route.Exec.dll redb.Route.File.dll redb.Route.Firebase.dll redb.Route.Ftp.dll redb.Route.GenericFile.dll redb.Route.Grpc.dll redb.Route.Http.Hosting.dll redb.Route.Http.dll redb.Route.IbmMq.dll redb.Route.JsonTransform.dll redb.Route.Kafka.dll redb.Route.Ldap.dll redb.Route.Llm.Abstractions.dll redb.Route.Llm.Mcp.dll redb.Route.Llm.Tools.dll redb.Route.Llm.dll redb.Route.Mail.dll redb.Route.MqttNet.dll redb.Route.Quartz.dll redb.Route.RabbitMQ.dll redb.Route.Redis.dll redb.Route.S3.dll redb.Route.Sftp.dll redb.Route.SignalR.StackExchangeRedis.dll redb.Route.SignalR.dll redb.Route.Soap.dll redb.Route.Sql.dll redb.Route.Sqs.dll redb.Route.Tcp.dll redb.Route.Telegram.dll redb.Route.Templates.dll redb.Route.Validation.Adapters.dll redb.Route.WebSocket.dll redb.Route.XPath2.dll redb.Route.Xml.dll redb.Route.dll redb.SQLite.Pro.dll redb.SQLite.dll redb.Tsak.Contracts.dll redb.Tsak.Core.Pro.dll redb.Tsak.Core.dll redb.Tsak.Worker.dll Path: redb/redb.Templates/templates/redb-blazor/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/.dockerignore ---- bin/ obj/ *.db *.db-shm *.db-wal Path: redb/redb.Templates/templates/redb-blazor/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Web", "Blazor", "Database", "RedBase" ], "identity": "RedBase.Blazor.Template", "name": "RedBase Blazor Site", "description": "A Blazor site (Interactive Server) on redb: a product list and form and a category tree; runs as is on SQLite with Pro.", "shortName": "redb-blazor", "tags": { "language": "C#", "type": "project" }, "sourceName": "RedbBlazor", "preferNameDirectory": true, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/redb-blazor/Components/App.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/App.razor ---- Path: redb/redb.Templates/templates/redb-blazor/Components/Layout/MainLayout.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Layout/MainLayout.razor ---- @inherits LayoutComponentBase
RedbBlazor Products Categories
@Body
Path: redb/redb.Templates/templates/redb-blazor/Components/Pages/Categories.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Pages/Categories.razor ---- @page "/categories" @inject RedbWork Work Categories

Categories

@code { private List roots = []; private string? newRootName; protected override Task OnInitializedAsync() => LoadAsync(); // Top-level nodes come from a tree query; each one is then loaded with its whole subtree. private async Task LoadAsync() { roots = await Work.RunAsync(async redb => { var top = await redb.TreeQuery().WhereRoots().ToListAsync(); var trees = new List(); foreach (var node in top) trees.Add(await redb.LoadTreeAsync(node.Id)); return trees; }); } private async Task AddRootAsync() { var name = newRootName!.Trim(); await Work.RunAsync(redb => redb.SaveAsync(new TreeRedbObject { Name = name, Props = new Category() })); newRootName = null; await LoadAsync(); } private async Task AddChildAsync((ITreeRedbObject Parent, string Name) request) { await Work.RunAsync(redb => redb.CreateChildAsync( new TreeRedbObject { Name = request.Name, Props = new Category() }, request.Parent)); await LoadAsync(); } // Deleting a node deletes its whole subtree. private async Task DeleteAsync(ITreeRedbObject node) { await Work.RunAsync(redb => redb.DeleteAsync(node.Id)); await LoadAsync(); } } Path: redb/redb.Templates/templates/redb-blazor/Components/Pages/CategoryNodeList.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Pages/CategoryNodeList.razor ---- @* Renders a level of the tree and calls itself for the children. *@
    @foreach (var node in Nodes) {
  • @node.Name @if (adding == node.Id) { } @if (node.Children.Any()) { }
  • }
@code { [Parameter, EditorRequired] public IEnumerable Nodes { get; set; } = []; [Parameter] public EventCallback<(ITreeRedbObject Parent, string Name)> OnAddChild { get; set; } [Parameter] public EventCallback OnDelete { get; set; } private long? adding; private string? childName; private async Task AddAsync(ITreeRedbObject parent) { var name = childName!.Trim(); Cancel(); await OnAddChild.InvokeAsync((parent, name)); } private void Cancel() { adding = null; childName = null; } } Path: redb/redb.Templates/templates/redb-blazor/Components/Pages/Error.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Pages/Error.razor ---- @page "/Error" Error

Something went wrong

The request could not be completed. Check the application log for details.

Path: redb/redb.Templates/templates/redb-blazor/Components/Pages/ProductEdit.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Pages/ProductEdit.razor ---- @page "/products/new" @page "/products/{Id:long}" @inject RedbWork Work @inject NavigationManager Navigation @(Id is null ? "New product" : "Edit product")

@(Id is null ? "New product" : "Edit product")

@if (notFound) {

Product @Id was not found. Back to the list

} else {
Cancel
} @code { [Parameter] public long? Id { get; set; } private ProductInput input = new(); private bool notFound; protected override async Task OnParametersSetAsync() { if (Id is null) return; var product = await Work.RunAsync(redb => redb.LoadAsync(Id.Value)); if (product is null) { notFound = true; return; } input = new ProductInput { Name = product.Name ?? string.Empty, Category = product.Props!.Category, Price = product.Props.Price, InStock = product.Props.InStock, Description = product.Props.Description, }; } private async Task SaveAsync() { await Work.RunAsync(async redb => { // Load, then change: with change tracking on, the save writes only the fields that // differ from what was loaded. var product = Id is null ? new RedbObject { Props = new Product() } : await redb.LoadAsync(Id.Value) ?? throw new InvalidOperationException($"Product {Id} not found."); product.Name = input.Name; product.Props!.Category = input.Category; product.Props.Price = input.Price; product.Props.InStock = input.InStock; product.Props.Description = input.Description; await redb.SaveAsync(product); }); Navigation.NavigateTo(""); } /// What the form edits. Validation lives here, not on the Props class. private sealed class ProductInput { [Required, StringLength(200)] public string Name { get; set; } = string.Empty; [Required, StringLength(100)] public string Category { get; set; } = string.Empty; [Range(0, 1_000_000)] public decimal Price { get; set; } public bool InStock { get; set; } [StringLength(2000)] public string? Description { get; set; } } } Path: redb/redb.Templates/templates/redb-blazor/Components/Pages/Products.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Pages/Products.razor ---- @page "/" @inject RedbWork Work Products

Products

New product

@total product(s)

@foreach (var item in items) { }
NameCategoryPriceIn stock
@item.Name @item.Props!.Category @item.Props.Price.ToString("F2") @(item.Props.InStock ? "yes" : "no")
@code { private const int PageSize = 10; private string? search; private bool inStockOnly; private string sort = "name"; private int pageNumber = 1; private int total; private List> items = []; private int PageCount => Math.Max(1, (total + PageSize - 1) / PageSize); protected override Task OnInitializedAsync() => LoadAsync(); private Task ReloadFromFirstPage() { pageNumber = 1; return LoadAsync(); } private Task GoToAsync(int target) { pageNumber = target; return LoadAsync(); } private async Task DeleteAsync(long id) { await Work.RunAsync(redb => redb.DeleteAsync(id)); await LoadAsync(); } // Count and page in one unit of work. Search, sorting and paging all run in the database. private async Task LoadAsync() { (total, items) = await Work.RunAsync(async redb => { var count = await Filtered(redb).CountAsync(); pageNumber = Math.Clamp(pageNumber, 1, Math.Max(1, (count + PageSize - 1) / PageSize)); var list = await Sorted(Filtered(redb)) .Skip((pageNumber - 1) * PageSize) .Take(PageSize) .ToListAsync(); return (count, list); }); } private IRedbQueryable Filtered(IRedbService redb) { var query = redb.Query(); // Name is the object's own field, so it is filtered with WhereRedb; Props fields use Where. // The value goes through a local, so the expression captures a plain value. var term = search?.Trim(); if (!string.IsNullOrEmpty(term)) query = query.WhereRedb(x => x.Name.Contains(term)); if (inStockOnly) query = query.Where(x => x.InStock); return query; } private IRedbQueryable Sorted(IRedbQueryable query) => sort switch { "price" => query.OrderBy(x => x.Price), "-price" => query.OrderByDescending(x => x.Price), "category" => query.OrderBy(x => x.Category), _ => query.OrderByRedb(x => x.Name), }; } Path: redb/redb.Templates/templates/redb-blazor/Components/Routes.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/Routes.razor ---- Path: redb/redb.Templates/templates/redb-blazor/Components/_Imports.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Components/_Imports.razor ---- @using System.ComponentModel.DataAnnotations @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using static Microsoft.AspNetCore.Components.Web.RenderMode @using redb.Core @using redb.Core.Models.Contracts @using redb.Core.Models.Entities @using redb.Core.Query @using RedbBlazor @using RedbBlazor.Components @using RedbBlazor.Models @using RedbBlazor.Services Path: redb/redb.Templates/templates/redb-blazor/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Dockerfile ---- # Build: docker build -t redbblazor . # Run: docker run -p 8080:8080 -v redbblazor-data:/data redbblazor FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY RedbBlazor.csproj . RUN dotnet restore COPY . . RUN dotnet publish -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app . # The SQLite file goes to a volume, so it survives a new container. The app runs as the # non-root user of the .NET image, which must be able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/app.db" ENV ASPNETCORE_URLS=http://+:8080 VOLUME /data EXPOSE 8080 ENTRYPOINT ["dotnet", "RedbBlazor.dll"] Path: redb/redb.Templates/templates/redb-blazor/Models/Category.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Models/Category.cs ---- using redb.Core.Attributes; namespace RedbBlazor.Models; /// /// A node of the category tree. The hierarchy itself (parent, children) is part of the object, not of /// the Props: a node is a TreeRedbObject<Category>, and deleting a node deletes its subtree. /// [RedbScheme("Category")] public class Category { public int SortOrder { get; set; } } Path: redb/redb.Templates/templates/redb-blazor/Models/Product.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Models/Product.cs ---- using redb.Core.Attributes; namespace RedbBlazor.Models; /// /// The Props of a product. The object's name is not here: it is the object's own field /// (RedbObject.Name). Each property is stored in a typed column, so filters and sorting on /// them run in the database. /// [RedbScheme("Product")] public class Product { public string Category { get; set; } = string.Empty; public decimal Price { get; set; } public bool InStock { get; set; } public string? Description { get; set; } } Path: redb/redb.Templates/templates/redb-blazor/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Program.cs ---- using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.SQLite.Pro.Extensions; using RedbBlazor.Components; using RedbBlazor.Models; using RedbBlazor.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // --- RedBase --- // The connection string lives in appsettings.json ("ConnectionStrings:Redb"). In a container it is // overridden by the ConnectionStrings__Redb environment variable (see deploy/*.yml). var connectionString = builder.Configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); builder.Services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbBlazor.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); // Components use RedbWork, not IRedbService directly: see the remarks in Services/RedbWork.cs. builder.Services.AddSingleton(); var app = builder.Build(); // --- Initialize RedBase once at startup --- // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await app.Services.GetRequiredService().RunAsync(async redb => { await redb.InitializeAsync(ensureCreated: true); await SeedAsync(redb); }); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); } app.UseAntiforgery(); app.MapStaticAssets(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run(); // Sample data on the first run, so the pages are not empty. static async Task SeedAsync(IRedbService redb) { if (!await redb.Query().AnyAsync()) { var samples = new (string Name, string Category, decimal Price, bool InStock)[] { ("Laptop 14", "Laptops", 1299m, true), ("Laptop 16", "Laptops", 1899m, false), ("Monitor 27", "Monitors", 349m, true), ("Keyboard", "Accessories", 79m, true), ("Mouse", "Accessories", 39m, true), }; foreach (var s in samples) { await redb.SaveAsync(new RedbObject { Name = s.Name, Props = new Product { Category = s.Category, Price = s.Price, InStock = s.InStock } }); } } if (!await redb.TreeQuery().AnyAsync()) { var root = new TreeRedbObject { Name = "Electronics", Props = new Category { SortOrder = 1 } }; await redb.SaveAsync(root); var computers = new TreeRedbObject { Name = "Computers", Props = new Category { SortOrder = 1 } }; await redb.CreateChildAsync(computers, root); await redb.CreateChildAsync(new TreeRedbObject { Name = "Laptops", Props = new Category { SortOrder = 1 } }, computers); await redb.CreateChildAsync(new TreeRedbObject { Name = "Monitors", Props = new Category { SortOrder = 2 } }, root); } } Path: redb/redb.Templates/templates/redb-blazor/Properties/launchSettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Properties/launchSettings.json ---- { "profiles": { "RedbBlazor": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "http://localhost:5081", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } Path: redb/redb.Templates/templates/redb-blazor/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/README.md ---- # RedbBlazor A Blazor site (Interactive Server) on RedBase: a product list with search, sorting and paging, a create / edit form, and a category tree. SQLite with Pro, so it runs as is. ## Run ```bash dotnet run ``` Open http://localhost:5081. On the first run the app creates `app.db` next to itself, builds the RedBase tables and adds sample products and categories. ## Where things are | File | What it does | |------|--------------| | `Program.cs` | RedBase registration and settings, startup initialization, sample data | | `Services/RedbWork.cs` | One `IRedbService` per operation (why: see below) | | `Models/Product.cs`, `Models/Category.cs` | The Props classes | | `Components/Pages/Products.razor` | Search, sorting and paging, all in the database | | `Components/Pages/ProductEdit.razor` | Create and edit; with change tracking a save writes only what changed | | `Components/Pages/Categories.razor` | The tree: roots, subtrees, add a child, delete a subtree | | `appsettings.json` | `ConnectionStrings:Redb` | ## Why components do not inject IRedbService In Blazor Server a scoped service lives as long as the user's circuit, and two event handlers of one page can run at the same time. An `IRedbService` is one connection and does not take parallel calls. `RedbWork` opens a scope per operation, the same way `IDbContextFactory` is used with EF Core. ## RedBase settings `Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. ## Another database 1. In `RedbBlazor.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy - `Dockerfile`: the site with SQLite on a volume. `docker build -t redbblazor . && docker run -p 8080:8080 -v redbblazor-data:/data redbblazor` - `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml`: the site with a database server. Switch the provider first (see above); each file has the commands at the top. Path: redb/redb.Templates/templates/redb-blazor/RedbBlazor.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/RedbBlazor.csproj ---- net10.0 enable enable RedbBlazor 4.8.0 false Path: redb/redb.Templates/templates/redb-blazor/Services/RedbWork.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/Services/RedbWork.cs ---- using redb.Core; namespace RedbBlazor.Services; /// /// Runs one unit of work on its own . /// /// /// In Blazor Server a scoped service lives as long as the user's circuit, and two event handlers of /// one page can be in flight at the same time. An is one connection and /// does not take parallel calls, so components do not inject it: each operation opens a scope, uses /// the service of that scope and disposes it. This is the same shape as IDbContextFactory in EF Core. /// public sealed class RedbWork(IServiceScopeFactory scopes) { public async Task RunAsync(Func> work) { await using var scope = scopes.CreateAsyncScope(); return await work(scope.ServiceProvider.GetRequiredService()); } public async Task RunAsync(Func work) { await using var scope = scopes.CreateAsyncScope(); await work(scope.ServiceProvider.GetRequiredService()); } } Path: redb/redb.Templates/templates/redb-blazor/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=app.db" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } Path: redb/redb.Templates/templates/redb-blazor/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/deploy/docker-compose.mssql.yml ---- # The site with SQL Server instead of SQLite. # Before the first run, switch the provider in code (see the comment in Program.cs): # RedbBlazor.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then: docker compose -f deploy/docker-compose.mssql.yml up --build services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql app: build: .. ports: - "8080:8080" environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" depends_on: - db volumes: mssqldata: Path: redb/redb.Templates/templates/redb-blazor/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/deploy/docker-compose.postgres.yml ---- # The site with PostgreSQL instead of SQLite. # Before the first run, switch the provider in code (see the comment in Program.cs): # RedbBlazor.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder: docker compose -f deploy/docker-compose.postgres.yml up --build services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 app: build: .. ports: - "8080:8080" environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" depends_on: db: condition: service_healthy volumes: pgdata: Path: redb/redb.Templates/templates/redb-blazor/wwwroot/app.css Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-blazor/wwwroot/app.css ---- body { font-family: system-ui, sans-serif; margin: 0; color: #1f2328; background: #fff; } header { display: flex; gap: 1.5rem; align-items: center; padding: 0.75rem 1.5rem; border-bottom: 1px solid #d0d7de; } header .brand { font-weight: 600; color: #b3261e; text-decoration: none; } main { max-width: 960px; margin: 0 auto; padding: 1rem 1.5rem; } a { color: #0969da; } .filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 0.5rem; } .muted { color: #656d76; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #d0d7de; } .num { text-align: right; } .pager { display: flex; gap: 0.5rem; margin-top: 1rem; } .pager span { font-weight: 600; } .form { display: grid; gap: 0.35rem; max-width: 480px; } .form input:not([type=checkbox]), .form textarea { padding: 0.35rem; font: inherit; } .form .actions { display: flex; gap: 1rem; align-items: center; margin-top: 0.75rem; } .field-validation-error, .validation-summary-errors { color: #b3261e; } button.link { background: none; border: 0; padding: 0; color: #b3261e; cursor: pointer; font: inherit; } header a.active { font-weight: 600; } .pager button { font: inherit; } .tree { list-style: none; padding-left: 1.25rem; } .tree li { margin: 0.25rem 0; } .tree button.link { margin-left: 0.5rem; } .inline { display: inline-flex; gap: 0.4rem; margin-left: 0.5rem; } Path: redb/redb.Templates/templates/redb-chat/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/.dockerignore ---- **/bin/ **/obj/ *.db *.db-shm *.db-wal data/ deploy/output/ Path: redb/redb.Templates/templates/redb-chat/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Console", "AI", "Chat", "RedBase" ], "identity": "RedBase.Chat.Template", "name": "RedBase LLM Chat", "description": "An LLM chat with its history in redb, in the console and over HTTP, with optional tools and audit; its own host or a Tsak module.", "shortName": "redb-chat", "tags": { "language": "C#", "type": "solution" }, "sourceName": "RedbChat", "preferNameDirectory": true, "symbols": { "tools": { "type": "parameter", "datatype": "choice", "defaultValue": "none", "displayName": "Tools", "description": "Tools the model can call", "choices": [ { "choice": "none", "description": "A plain chat" }, { "choice": "shell", "description": "A route tool that runs a few read-only system commands" }, { "choice": "mcp", "description": "The tools of an MCP server (the filesystem server, needs Node.js)" } ] }, "audit": { "type": "parameter", "datatype": "bool", "defaultValue": "false", "displayName": "Audit", "description": "Stamp the user and audit tags on every stored message, and add an /audit console command" }, "UseShell": { "type": "computed", "value": "(tools == \"shell\")" }, "UseMcp": { "type": "computed", "value": "(tools == \"mcp\")" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ], "modifiers": [ { "condition": "(!UseShell)", "exclude": [ "RedbChat.Module/Tools/ShellToolRouteBuilder.cs" ] }, { "condition": "(!UseMcp)", "exclude": [ "RedbChat.Module/Tools/McpTools.cs" ] }, { "condition": "(!audit)", "exclude": [ "RedbChat.Module/AuditQueries.cs" ] } ] } ] } Path: redb/redb.Templates/templates/redb-chat/Directory.Build.props Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/Directory.Build.props ---- net10.0 enable enable 4.8.0 false Path: redb/redb.Templates/templates/redb-chat/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/Dockerfile ---- # The chat in its own host, without Tsak: the HTTP endpoint, and the console when started with -it. # Build: docker build -t redbchat . # Run: docker run -it -p 5090:5090 -v redbchat-data:/data \ # -e Tsak__Contexts__redbchat__Override__Llm__ApiKey=YOUR_KEY redbchat FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbChat.Module/RedbChat.Module.csproj RedbChat.Module/ COPY RedbChat.Host/RedbChat.Host.csproj RedbChat.Host/ RUN dotnet restore RedbChat.Host/RedbChat.Host.csproj COPY . . RUN dotnet publish RedbChat.Host/RedbChat.Host.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/runtime:10.0 WORKDIR /app COPY --from=build /app . # The chat history goes to a volume. The app runs as the non-root user of the .NET image, which must # be able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/redbchat.db" # Inside a container the endpoint must listen on all interfaces to be reachable through -p. ENV Tsak__Contexts__redbchat__Override__Http__Host=0.0.0.0 VOLUME /data EXPOSE 5090 ENTRYPOINT ["dotnet", "RedbChat.Host.dll"] Path: redb/redb.Templates/templates/redb-chat/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/README.md ---- # RedbChat A chat with an LLM on redb.Route.Llm. The conversation history is kept in RedBase (SQLite with Pro), so a chat goes on after a restart. You talk to it in the console or over HTTP. The same module runs in two places: in its own console host, and on a Tsak worker. ## Run 1. Put your API key into `RedbChat.Host/appsettings.json`, field `ApiKey`. The app stops at startup with a message while it is empty. Instead of the file you can set the environment variable `Tsak__Contexts__redbchat__Override__Llm__ApiKey`. 2. Start it: ```bash dotnet run --project RedbChat.Host ``` 3. Type a message. `/new` starts a new conversation. Over HTTP: ```bash curl -d "hello" -H "X-Chat-Id: my-chat" http://localhost:5090/api/chat ``` `X-Chat-Id` picks the conversation: the same id continues the same history. The model is Anthropic Claude Haiku. For DeepSeek, uncomment the two lines under `ApiKey` in `RedbChat.Host/appsettings.json` (`Provider: deepseek`, `ModelId: deepseek-chat`) and put a DeepSeek key. Other providers of redb.Route.Llm work the same way. ## Options | Option | Values | Default | What it adds | |--------|--------|---------|--------------| | `--tools` | `none`, `shell`, `mcp` | `none` | `shell`: a route tool that runs a few read-only system commands. `mcp`: the tools of the MCP filesystem server, pinned to `data/files` (needs Node.js) | | `--audit` | `true`, `false` | `false` | The user and audit tags on every stored message, and an `/audit` console command that reads them back with a LINQ query | ```bash dotnet new redb-chat -n MyChat --tools shell --audit true ``` ## Where things are | File | What it does | |------|--------------| | `RedbChat.Module/InitRoute.cs` | The module's entry point: components, the model, the history store, tools, routes | | `RedbChat.Module/Routes/ChatRouteBuilder.cs` | `direct:chat` (the chat) and the HTTP endpoint that forwards to it | | `RedbChat.Module/Tools/` | The tool of `--tools shell` or `--tools mcp` | | `RedbChat.Module/AuditQueries.cs` | With `--audit`: the query over stored messages | | `RedbChat.Module/RedbChat.Module.config.json` | Provider, model, system prompt, HTTP host and port | | `RedbChat.Host/Program.cs` | The own host: redb registration and settings, `InitRoute.main`, the console chat | | `RedbChat.Host/appsettings.json` | `ConnectionStrings:Redb` and the `Override` layer: the API key | ## Settings The module reads its settings from its route context. Both hosts fill it the same way: the module's config file first, then `Tsak:Contexts:redbchat:Override`, which wins. The API key belongs only in the Override layer, never in the module's config file, which ships inside the package. The key is checked before anything is created, so a missing key stops the host without leaving an empty database behind. The log level comes from `Logging:LogLevel:Default` in `appsettings.json` (Warning by default, which keeps the chat readable). Set `Logging__LogLevel__Default=Information` to see every route step and the token counts. The HTTP endpoint listens on 127.0.0.1: it has no authentication and every call costs tokens. The Dockerfile opens it to the container network (`Http:Host = 0.0.0.0`); put it behind your own gateway before exposing it further. ## RedBase settings `RedbChat.Host/Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. On Tsak the same settings are environment variables of the worker (`Tsak__Redb__...`, see `deploy/docker-compose.tsak.yml`). The compose file sets no `Tsak__Cluster__NodeId`: a worker is named after its container's host name, so every replica of `docker compose up --scale` is a Tsak node of its own. Set an explicit id only for a single instance or a StatefulSet; two live workers with one id are refused. ## Another database 1. In `RedbChat.Host.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy **Own host** - `Dockerfile`: the host with the history on a volume. `docker build -t redbchat .` then `docker run -it -p 5090:5090 -v redbchat-data:/data -e Tsak__Contexts__redbchat__Override__Llm__ApiKey=YOUR_KEY redbchat` - `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml`: the host with a database server. Switch the provider first (see above); put `LLM_API_KEY` into `deploy/.env`; each file has the commands at the top. **Tsak** 1. `cp deploy/.env.example deploy/.env` and fill in the Tsak values and `LLM_API_KEY`. 2. `pwsh deploy/pack-tpkg.ps1` packs the module into `deploy/output/RedbChat.tpkg`. 3. `docker compose -f deploy/docker-compose.tsak.yml up -d` starts the Tsak stack with the module. 4. `curl -d "hello" http://localhost:5090/api/chat`; the dashboard is at http://localhost:8085. `pack-tpkg.ps1` puts the manifest, the module config, the module DLL and every dependency the worker does not ship itself into the package; `deploy/shipped-module-deps.txt` lists what the worker provides, and `deploy/output/RedbChat.tpkg.contents.txt` shows what went in. To run the module on a Tsak host built locally from the `tsak-worker` template, drop the assemblies that host lacks (`redb.Route.Llm.dll`, `redb.Route.File.dll`, ...) into its `Libs/shared`: the host resolves a module's shared assemblies from `Libs/shared` next to the application, and that template copies `Libs/**` to its output. With `--tools mcp` in a container, the image must have Node.js for `npx`: the .NET runtime image of the `Dockerfile` has none, and neither may your Tsak image. Without it the module stops at startup when it starts the MCP server. Path: redb/redb.Templates/templates/redb-chat/RedbChat.Host/ContextConfiguration.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Host/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace RedbChat.Host; /// /// The context configuration the way a Tsak worker builds it, in miniature. Each layer deep-merges over /// the previous one, later layers win: /// /// the module's RedbChat.Module.config.json, /// Tsak:Contexts:{context}:Override of the host configuration. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. So the /// same keys and the same environment variables work here and on a Tsak worker. /// public static class ContextConfiguration { /// The context the 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 = Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"))); 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) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var child in section.GetChildren()) result[child.Key] = child.GetChildren().Any() ? Read(child) : 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; } } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Host/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Host/Program.cs ---- // The module's own host. It does what a Tsak worker does for the module, plus a console chat: // 1) reads appsettings.json, then environment variables, // 2) registers redb and the HTTP server of the process, initializes redb, // 3) builds the context configuration (module config file, then the Override section), // 4) awaits RedbChat.Module.InitRoute.main(ctx), the method the Tsak worker calls, // 5) starts the context, then reads chat messages from the console until Ctrl+C or SIGTERM. using System.Runtime.InteropServices; 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.Route.Core; using redb.Route.Http; using redb.Route.Llm; using redb.SQLite.Pro.Extensions; using RedbChat.Host; using RedbChat.Module; var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var connectionString = configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); // The module's context and its settings file: the same names a Tsak worker uses. var moduleConfig = Path.Combine(AppContext.BaseDirectory, "RedbChat.Module.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); // Checked before anything is created: otherwise the module would fail later, once the database file // has already been made. if (string.IsNullOrWhiteSpace(configuration[$"Tsak:Contexts:{contextName}:Override:Llm:ApiKey"])) throw new InvalidOperationException( $"The LLM API key is not set for context '{contextName}'. Put it into RedbChat.Host/appsettings.json " + $"(Tsak:Contexts:{contextName}:Override:Llm:ApiKey), or set the environment variable " + $"Tsak__Contexts__{contextName}__Override__Llm__ApiKey."); var services = new ServiceCollection(); services.AddSingleton(configuration); // Warning keeps the chat readable (Information shows every route step and the token counts). // Override it with the standard key, for example Logging__LogLevel__Default=Information. services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(configuration.GetValue("Logging:LogLevel:Default", LogLevel.Warning))); services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbChat.Host.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); // The HTTP servers of the process, one per port, as the Tsak worker registers them. services.AddRedbRouteHttpHosting(); await using var provider = services.BuildServiceProvider(); // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService().InitializeAsync(ensureCreated: true); } var context = new RouteContext(provider, contextName, provider.GetRequiredService()); ContextConfiguration.ApplyTo(context, ContextConfiguration.Build(configuration, contextName, moduleConfig)); await InitRoute.main(context); // <- the exact method the Tsak worker calls await context.Start(); var settings = ModuleSettings.FromContext(context); Console.WriteLine(); Console.WriteLine($"RedbChat: {settings.Provider}/{settings.ModelId}. The history is kept in RedBase between runs."); Console.WriteLine($" HTTP: curl -d \"hello\" -H \"{ChatNames.ChatIdHeader}: my-chat\" http://localhost:{settings.HttpPort}/api/chat"); #if (audit) Console.WriteLine(" Console: type a message; /new starts a new conversation, /audit shows your latest answers."); #else Console.WriteLine(" Console: type a message; /new starts a new conversation."); #endif Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); using var stopping = new CancellationTokenSource(); _ = Task.Run(() => ChatConsoleAsync(context, provider, stopping.Token), stopping.Token); var stop = new TaskCompletionSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; // docker stop sends SIGTERM, not Ctrl+C. using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, c => { c.Cancel = true; stop.TrySetResult(); }); await stop.Task; await stopping.CancelAsync(); await context.DisposeAsync(); // Reads a line, sends it to direct:chat, prints the answer. Without a terminal (a container started // without -it) ReadLine returns null and only the HTTP endpoint is left. static async Task ChatConsoleAsync(RouteContext context, IServiceProvider provider, CancellationToken stopping) { using var producer = new ProducerTemplate(context); producer.Start(); var chatId = "console"; var user = Environment.UserName; while (!stopping.IsCancellationRequested) { Console.Write("> "); var line = Console.ReadLine(); if (line is null) return; line = line.Trim(); if (line.Length == 0) continue; if (line == "/new") { chatId = $"console-{DateTime.UtcNow:yyyyMMddHHmmss}"; Console.WriteLine($"New conversation: {chatId}"); continue; } #if (audit) if (line == "/audit") { await using var scope = provider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); foreach (var a in await AuditQueries.LatestAnswersAsync(redb, user, 5)) Console.WriteLine($"{a.At:u} {a.Model} in={a.TokensIn} out={a.TokensOut}: {a.Text}"); continue; } #endif var message = new Message(line); message.Headers[LlmHeaders.ConversationId] = chatId; message.Headers[ChatNames.UserIdHeader] = user; try { Console.WriteLine(await producer.RequestBody(ChatNames.ChatUri, message, stopping)); } catch (Exception ex) when (ex is not OperationCanceledException) { Console.WriteLine($"The call failed: {ex.Message}"); } } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Host/RedbChat.Host.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Host/RedbChat.Host.csproj ---- Exe Path: redb/redb.Templates/templates/redb-chat/RedbChat.Host/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Host/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=redbchat.db" }, "Logging": { // Warning keeps the chat readable; Information shows every route step and the token counts. // Override with the environment variable Logging__LogLevel__Default=Information. "LogLevel": { "Default": "Warning" } }, "Tsak": { "Contexts": { "redbchat": { // The Override layer of the module's settings: it wins over RedbChat.Module.config.json. // The same keys work on a Tsak worker as environment variables, for example // Tsak__Contexts__redbchat__Override__Llm__ApiKey. "Override": { "Llm": { // Your API key. The app stops at startup with a message while it is empty. "ApiKey": "" // The model is Anthropic Claude Haiku (RedbChat.Module.config.json). For DeepSeek, uncomment // these two lines and put a DeepSeek key above: // ,"Provider": "deepseek" // ,"ModelId": "deepseek-chat" } } } } } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/AuditQueries.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/AuditQueries.cs ---- using redb.Core; using redb.Route.Llm.Storage.Redb.Schemas; namespace RedbChat.Module; /// /// Reading the audit trail back. Every stored message carries the user and the audit tags the chat route /// stamps on it (.User(...), .Audit(...)), and they are typed properties: the filter below, /// including the dictionary lookup, runs in the database. /// public static class AuditQueries { /// The model's latest answers to one user, newest first. public static async Task> LatestAnswersAsync(IRedbService redb, string userId, int count) { var messages = await redb.Query() .Where(m => m.UserId == userId && m.Role == "assistant" && m.AuditTags!["app"] == "redbchat") .OrderByDescending(m => m.CreatedAtUtc) .Take(count) .ToListAsync(); return messages .Select(m => new AuditLine( m.Props!.CreatedAtUtc, m.Props.ModelId, m.Props.InputTokens, m.Props.OutputTokens, string.Concat(m.Props.Content.Select(c => c.Text)))) .ToList(); } } public sealed record AuditLine(DateTimeOffset At, string? Model, int TokensIn, int TokensOut, string Text); Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/ChatNames.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/ChatNames.cs ---- namespace RedbChat.Module; /// Names shared by the routes and the hosts. public static class ChatNames { /// The chat itself: a message in, the model's answer out. The console and HTTP both call it. public const string ChatUri = "direct:chat"; /// The registry name of the LLM connection factory. public const string LlmFactory = "chat-llm"; /// /// The conversation a message belongs to. Messages with the same id share their history, which /// RedBase keeps between restarts. HTTP callers send it as X-Chat-Id. /// public const string ChatIdHeader = "X-Chat-Id"; /// Who is talking. HTTP callers send it as X-User-Id; the console uses the OS user name. public const string UserIdHeader = "X-User-Id"; } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/InitRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; #if (UseShell) using redb.Route.Exec; #endif using redb.Route.Http; using redb.Route.Llm; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using RedbChat.Module.Routes; #if (UseShell || UseMcp) using RedbChat.Module.Tools; #endif namespace RedbChat.Module; /// /// The module's entry point. A Tsak worker finds it by convention (a public static class /// InitRoute with a main(IRouteContext) method) and awaits it when the module loads; /// RedbChat.Host calls the same method, so the chat exists once. /// Order: settings, components, the model connection, the database, the tools, the engine, the routes. /// public static class InitRoute { public static async Task main(IRouteContext context) { var settings = ModuleSettings.FromContext(context); var loggerFactory = context.GetService(); 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. The host registers it: the Tsak worker does, and // so does RedbChat.Host (AddRedbRouteHttpHosting). if (!context.HasComponent("http")) context.AddComponent(new HttpComponent { ServerManager = services.GetRequiredService() }); if (!context.HasComponent("llm")) context.AddComponent(new LlmComponent()); #if (UseShell) if (!context.HasComponent("exec")) context.AddComponent(new ExecComponent()); #endif // The model. Provider and model come from the module's config file, the key from the Override // layer. For DeepSeek set Provider "deepseek" and ModelId "deepseek-chat" (see appsettings.json). context.AddToRegistry(ChatNames.LlmFactory, new LlmConnectionFactory { Name = ChatNames.LlmFactory, Provider = settings.Provider, ModelId = settings.ModelId, ApiKey = settings.ApiKey, Temperature = settings.Temperature, MaxTokens = settings.MaxTokens, }); // The history lives in redb: a conversation and its messages are redb objects, so a chat goes on // after a restart. The schemes are synced here, through a scope of the module's own. await using (var scope = services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); } // Tools: every tool the model may call is a descriptor in this registry. var toolRegistry = new ToolDescriptorRegistry(); context.AddService(typeof(IToolDescriptorRegistry), toolRegistry); var tools = new List(); #if (UseShell) tools.Add(ShellToolRouteBuilder.ToolName); // a route with .AsLlmTool(...) registers itself #endif #if (UseMcp) tools.AddRange(await McpTools.RegisterAsync(context, toolRegistry, settings, loggerFactory)); #endif // The engine runs the model and the tool calls. It sends tool calls through a producer template. var producer = new ProducerTemplate(context); producer.Start(); context.AddService(typeof(IProducerTemplate), producer); context.AddService(typeof(IConversationStore), new RedbConversationStore(context)); context.AddService(typeof(IAgentEngine), AgentEngine.FromContext(context)); var routes = (RouteContext)context; routes.AddRoutes(new ChatRouteBuilder(settings, tools)); #if (UseShell) routes.AddRoutes(new ShellToolRouteBuilder()); #endif loggerFactory?.CreateLogger("RedbChat").LogInformation( "RedbChat module ready: {Provider}/{Model}, HTTP on {Host}:{Port}, tools: {Tools}", settings.Provider, settings.ModelId, settings.HttpHost, settings.HttpPort, tools.Count == 0 ? "none" : string.Join(", ", tools)); return context; } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/ModuleSettings.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/ModuleSettings.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RedbChat.Module; /// /// The module's settings, read from the properties of its route context. Both hosts fill them the same /// way: RedbChat.Module.config.json first, then the Tsak:Contexts:{context}:Override section of /// the host configuration, which wins. The API key belongs only in the Override layer (RedbChat.Host /// appsettings.json, or the environment variable Tsak__Contexts__redbchat__Override__Llm__ApiKey), /// never in the module's config file, which ships inside the package. /// public sealed record ModuleSettings( string Provider, string ModelId, string ApiKey, double Temperature, int MaxTokens, string SystemPrompt, #if (UseMcp) string McpFolder, #endif string HttpHost, int HttpPort) { public static ModuleSettings FromContext(IRouteContext context) { var llm = Section(context, "Llm"); var chat = Section(context, "Chat"); var http = Section(context, "Http"); #if (UseMcp) var mcp = Section(context, "Mcp"); #endif var apiKey = Optional(llm, "ApiKey"); if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException( $"The LLM API key is not set for context '{context.ContextId}'. Put it into " + $"RedbChat.Host/appsettings.json (Tsak:Contexts:{context.ContextId}:Override:Llm:ApiKey), " + $"or set the environment variable Tsak__Contexts__{context.ContextId}__Override__Llm__ApiKey."); return new( Provider: Required(context, llm, "Llm", "Provider"), ModelId: Required(context, llm, "Llm", "ModelId"), ApiKey: apiKey, Temperature: double.Parse(Required(context, llm, "Llm", "Temperature"), CultureInfo.InvariantCulture), MaxTokens: int.Parse(Required(context, llm, "Llm", "MaxTokens"), CultureInfo.InvariantCulture), SystemPrompt: Required(context, chat, "Chat", "SystemPrompt"), #if (UseMcp) // Relative paths resolve against the current directory of the process. McpFolder: Path.GetFullPath(Required(context, mcp, "Mcp", "Folder")), #endif // 127.0.0.1 by default: the endpoint has no authentication and every call costs tokens. A container // sets 0.0.0.0 (see the Dockerfile). HttpHost: Required(context, http, "Http", "Host"), HttpPort: int.Parse(Required(context, http, "Http", "Port"), CultureInfo.InvariantCulture)); } private static IDictionary Section(IRouteContext context, string name) => context.GetProperty>(name) ?? throw Missing(context, name); private static string? Optional(IDictionary section, string key) => section.TryGetValue(key, out var value) ? Convert.ToString(value, CultureInfo.InvariantCulture) : null; private static string Required(IRouteContext context, IDictionary section, string sectionName, string key) => Optional(section, key) is { Length: > 0 } text ? text : throw Missing(context, $"{sectionName}:{key}"); private static InvalidOperationException Missing(IRouteContext context, string key) => new( $"{key} is not configured for context '{context.ContextId}': set it in RedbChat.Module.config.json " + $"or in Tsak:Contexts:{context.ContextId}:Override."); } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/RedbChat.Module.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/RedbChat.Module.config.json ---- { "ContextName": "redbchat", "AutoStart": true, "Llm": { "Provider": "anthropic", "ModelId": "claude-haiku-4-5", "Temperature": 0.2, "MaxTokens": 1024 }, "Chat": { "SystemPrompt": "You are a helpful assistant. Answer briefly and plainly." }, //#if (UseMcp) "Mcp": { "Folder": "data/files" }, //#endif "Http": { "Host": "127.0.0.1", "Port": 5090 } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/RedbChat.Module.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/RedbChat.Module.csproj ---- Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/Routes/ChatRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/Routes/ChatRouteBuilder.cs ---- using redb.Route.Core; using redb.Route.Llm; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace RedbChat.Module.Routes; /// /// The chat: direct:chat takes a message and answers it, and an HTTP endpoint forwards to it. /// The console of RedbChat.Host sends to direct:chat directly. /// public sealed class ChatRouteBuilder(ModuleSettings settings, IReadOnlyList tools) : RouteBuilder { protected override void Configure() { var llm = LlmDsl.Factory(ChatNames.LlmFactory) // The history of the conversation named in the llm.conversation.id header is loaded before the // call and the new messages are stored after it. .ConversationFromHeader() // A tool call and its answer is one iteration; the limit stops a model that keeps calling. .MaxIterations(8) #if (audit) // Stamped on every stored message: who asked, and free-form tags. AuditQueries.cs reads them back. .User("${header.X-User-Id}") .Audit("app", "redbchat") // The prompt's name and version, so a stored answer says which prompt produced it. .PromptTemplate("chat-system", "v1") #endif ; if (tools.Count > 0) llm = llm.Tools(string.Join(",", tools)); From(ChatNames.ChatUri) .RouteId("chat") .ConvertBody() .Process(e => { e.In.Headers[LlmHeaders.SystemPrompt] = settings.SystemPrompt; if (e.In.GetHeader(LlmHeaders.ConversationId) is not { Length: > 0 }) e.In.Headers[LlmHeaders.ConversationId] = "default"; }) .Log("chat ${header.llm.conversation.id}: ${body}") .To(llm.AsUri()) .Log("chat ${header.llm.conversation.id}: tokens in ${header.llm.tokens.in}, out ${header.llm.tokens.out}"); // POST the message as the body. X-Chat-Id picks the conversation, X-User-Id names the caller. From($"http:{settings.HttpHost}:{settings.HttpPort}/api/chat?inOut=true") .RouteId("chat-http") .Process(e => { e.In.Headers[LlmHeaders.ConversationId] = e.In.GetHeader(ChatNames.ChatIdHeader) is { Length: > 0 } chatId ? chatId : "default"; if (e.In.GetHeader(ChatNames.UserIdHeader) is not { Length: > 0 }) e.In.Headers[ChatNames.UserIdHeader] = "anonymous"; }) .To(ChatNames.ChatUri); } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/Tools/McpTools.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/Tools/McpTools.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Mcp; using redb.Route.Llm.Mcp.Transport; namespace RedbChat.Module.Tools; /// /// The tools of an MCP server, given to the model as its own tools. /// /// The server here is the reference filesystem server, started over stdio with npx (Node.js must be /// installed) and pinned to one folder (Mcp:Folder). Any other MCP server works the same way: change /// the command below, for example uvx mcp-server-fetch. /// /// public static class McpTools { private const string ServerName = "files"; /// Starts the server, lists its tools, registers each one and returns the names the model sees. public static async Task> RegisterAsync( IRouteContext context, ToolDescriptorRegistry toolRegistry, ModuleSettings settings, ILoggerFactory? loggerFactory) { Directory.CreateDirectory(settings.McpFolder); // npx is a script on Windows, so it is started through cmd there. string[] server = ["npx", "-y", "@modelcontextprotocol/server-filesystem", settings.McpFolder]; var transport = OperatingSystem.IsWindows() ? McpTransport.Stdio(command: "cmd", arguments: ["/c", .. server]) : McpTransport.Stdio(command: server[0], arguments: server[1..]); // The server process lives as long as this one: it exits when its standard input closes. var client = new StdioMcpClient( serverName: ServerName, transport: transport, logger: loggerFactory?.CreateLogger("Mcp.files") ?? NullLogger.Instance); // The first start downloads the server package, which takes a while. using (var init = new CancellationTokenSource(TimeSpan.FromMinutes(2))) await client.InitializeAsync(init.Token); var mcpRegistry = new McpRegistry(); mcpRegistry.Register(client); context.AddComponent(new McpComponent(mcpRegistry)); var names = new List(); foreach (var tool in await client.ListToolsAsync()) { if (string.IsNullOrWhiteSpace(tool.Name)) continue; var modelName = McpToolDescriptor.BuildModelFacingName(ServerName, tool.Name); toolRegistry.Register(new McpToolDescriptor(ServerName, tool.Name, new LlmToolCapability { Name = modelName, Description = tool.Description ?? $"MCP tool '{tool.Name}' of the '{ServerName}' server.", InputSchema = McpToolDescriptor.BuildInputSchema(tool), Safety = new LlmToolSafety { // The server can write files in its folder; mark it as external so it is audited as such. SideEffect = ToolSideEffect.External, Cost = ToolCostClass.Cheap, RequiresApproval = false, }, })); names.Add(modelName); } return names; } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/Tools/ShellToolRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/Tools/ShellToolRouteBuilder.cs ---- using redb.Route.Core; using redb.Route.Exec; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Extensions; namespace RedbChat.Module.Tools; /// /// A tool is a route: .AsLlmTool(...) after From publishes the route to the model with a /// name, a description and an input schema. The model's call arrives as the body; what the route returns /// goes back to the model. /// /// This one runs a system command through exec:. The allowlist is the security boundary: a command /// outside it is refused before a process starts. It lists single read-only programs on purpose; adding a /// shell (cmd, sh, pwsh) would let the model run anything. /// /// public sealed class ShellToolRouteBuilder : RouteBuilder { public const string ToolName = "system_info"; protected override void Configure() { var allowed = OperatingSystem.IsWindows() ? new[] { "hostname", "whoami", "ipconfig" } : new[] { "hostname", "whoami", "uname", "uptime", "df" }; From("direct:tool-system-info") .AsLlmTool(ToolName) .Description( "Run one read-only system command on the host and return its output. Input: " + "{\"command\":\"\",\"args\":[\"...\"]}. Output: {\"stdout\":\"...\",\"stderr\":\"...\",\"exitCode\":N}. " + $"Allowed commands: {string.Join(", ", allowed)}.") .Input(""" { "type": "object", "properties": { "command": { "type": "string" }, "args": { "type": "array", "items": { "type": "string" } } }, "required": ["command"] } """) .SideEffect(ToolSideEffect.ReadOnly) .Cost(ToolCostClass.Cheap) .Then() .Log("tool " + ToolName + ": ${body}") .To(ExecDsl.Run() .AllowedCommands(allowed) .TimeoutMs(5_000) .MaxStdoutBytes(8_192) .MaxStderrBytes(8_192)); } } Path: redb/redb.Templates/templates/redb-chat/RedbChat.Module/manifest.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.Module/manifest.json ---- { "Name": "RedbChat", "Version": "1.0.0", "EntryPoints": ["RedbChat.Module.dll"], "Dependencies": [] } Path: redb/redb.Templates/templates/redb-chat/RedbChat.slnx Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/RedbChat.slnx ---- Path: redb/redb.Templates/templates/redb-chat/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/deploy/docker-compose.mssql.yml ---- # The chat in its own host with SQL Server instead of SQLite. # Before the first run, switch the provider in code (see the comment in RedbChat.Host/Program.cs): # RedbChat.Host.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then: docker compose -f deploy/docker-compose.mssql.yml up --build # Then: curl -d "hello" http://localhost:5090/api/chat (the key comes from deploy/.env: LLM_API_KEY) services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql chat: build: .. environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" Tsak__Contexts__redbchat__Override__Llm__ApiKey: ${LLM_API_KEY:?LLM_API_KEY required} ports: - "5090:5090" depends_on: - db volumes: mssqldata: Path: redb/redb.Templates/templates/redb-chat/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/deploy/docker-compose.postgres.yml ---- # The chat in its own host with PostgreSQL instead of SQLite. # Before the first run, switch the provider in code (see the comment in RedbChat.Host/Program.cs): # RedbChat.Host.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder: docker compose -f deploy/docker-compose.postgres.yml up --build # Then: curl -d "hello" http://localhost:5090/api/chat (the key comes from deploy/.env: LLM_API_KEY) services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 chat: build: .. environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" Tsak__Contexts__redbchat__Override__Llm__ApiKey: ${LLM_API_KEY:?LLM_API_KEY required} ports: - "5090:5090" depends_on: db: condition: service_healthy volumes: pgdata: Path: redb/redb.Templates/templates/redb-chat/deploy/docker-compose.tsak.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/deploy/docker-compose.tsak.yml ---- # The module on a Tsak worker: the Tsak stack image (worker and dashboard in one container) loads # RedbChat.tpkg from deploy/output. The worker's default redb is SQLite, so nothing else is needed. # # From the project folder: # cp deploy/.env.example deploy/.env # then fill in the Tsak values and LLM_API_KEY # pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbChat.tpkg # docker compose -f deploy/docker-compose.tsak.yml up -d # # Then: curl -d "hello" -H "X-Chat-Id: my-chat" http://localhost:5090/api/chat # Dashboard: http://localhost:8085 (admin and TSAK_WEB_ADMIN_PASSWORD). services: tsak: image: ghcr.io/redbase-app/redb-tsak-stack:${TSAK_VERSION:-4.8.0-net10} restart: unless-stopped ports: - "127.0.0.1:9090:9090" # worker API - "127.0.0.1:8085:8085" # dashboard - "127.0.0.1:5090:5090" # the module's chat endpoint environment: # The worker's default (unnamed) redb, the one the module keeps the history in. The same settings as # the own host: Pro, change tracking, the PVT prefilter. The props cache stays off; to turn it on add # Tsak__Redb__EnablePropsCache=true. - Tsak__Redb__UsePro=true - Tsak__Redb__PropsSaveStrategy=ChangeTracking - Tsak__Redb__EnablePvtPrefilter=true - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://tsak:9090 # No Tsak__Cluster__NodeId: a node is named after its container's host name, so each replica of # `docker compose up --scale` is a node of its own. A fixed id suits one instance or a StatefulSet only. # 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, the same keys the own host reads. - Tsak__Contexts__redbchat__Override__Llm__ApiKey=${LLM_API_KEY:?LLM_API_KEY required} # For DeepSeek: # - Tsak__Contexts__redbchat__Override__Llm__Provider=deepseek # - Tsak__Contexts__redbchat__Override__Llm__ModelId=deepseek-chat - Tsak__Contexts__redbchat__Override__Http__Host=0.0.0.0 volumes: - ./output:/app/modules Path: redb/redb.Templates/templates/redb-chat/deploy/pack-tpkg.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds RedbChat.Module and packs it into RedbChat.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, RedbChat.Module.dll and every dependency the worker does not ship itself. deploy/shipped-module-deps.txt lists what the worker ships (its header says how to regenerate the list), so a dependency missing from that list travels inside the package. The package contents are also written next to it as RedbChat.tpkg.contents.txt. .EXAMPLE ./deploy/pack-tpkg.ps1 ./deploy/pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $module = Join-Path $root "RedbChat.Module" $entryDll = "RedbChat.Module.dll" $publish = Join-Path ([IO.Path]::GetTempPath()) "redbchat-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "redbchat-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "RedbChat.tpkg" $shippedList = Join-Path $PSScriptRoot "shipped-module-deps.txt" # 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 $module "RedbChat.Module.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of RedbChat.Module failed." } # The worker resolves only the assemblies it ships (shipped-module-deps.txt). Every other dependency # has to travel inside the package, otherwise the module fails to load with FileNotFoundException. $shipped = @(Get-Content $shippedList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $extra = @(Get-ChildItem $publish -Filter *.dll | Where-Object { $_.Name -ne $entryDll -and $shipped -notcontains $_.Name }) 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 $module "manifest.json") $staging Copy-Item (Join-Path $module "RedbChat.Module.config.json") $staging Copy-Item (Join-Path $publish $entryDll) $staging foreach ($dependency in $extra) { Copy-Item $dependency.FullName $staging } # Native assets of a dependency (runtimes//native/...), if the module brought any. $runtimes = Join-Path $publish "runtimes" if (Test-Path $runtimes) { Copy-Item $runtimes $staging -Recurse } if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) # What the package holds, next to it: handy when a Tsak node refuses to load the module. $contents = Get-ChildItem $staging -Recurse -File | ForEach-Object { $_.FullName.Substring($staging.Length + 1).Replace('\', '/') } Set-Content -Path ($package + ".contents.txt") -Value $contents -Encoding utf8 Write-Host "Packed $package" Write-Host " module: $entryDll" Write-Host (" packed dependencies: {0}" -f $extra.Count) foreach ($dependency in $extra) { Write-Host (" " + $dependency.Name) } Write-Host (" not packed: {0} assemblies shipped by the worker" -f $shipped.Count) Path: redb/redb.Templates/templates/redb-chat/deploy/shipped-module-deps.txt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-chat/deploy/shipped-module-deps.txt ---- # Assemblies the redb.Tsak worker already provides: /app/*.dll and /app/Libs/shared/*.dll of # redb-tsak-worker:4.8.0, and the assemblies of the ASP.NET Core shared framework of its base image that this # list carries (Microsoft.Extensions.*, System.Diagnostics.EventLog, System.Security.Cryptography.Pkcs). The # worker binds those from /usr/share/dotnet/shared: since 4.8 the SDK publishes no copy of them into /app, and a # copy inside a module would give ILogger, IConfiguration or IOptions a second type identity. A module # dependency present here is NOT packed into the .tpkg; every other dependency travels inside the package. # # The worker resolves these from its own folder and from Libs/shared next to the application # (Libs/shared under the app directory, not the current one). A Tsak host built locally from the # tsak-worker template ships a smaller set: put the assemblies a module needs (redb.Route.File, # redb.Route.GenericFile, ...) into that host project Libs/shared - the template copies Libs/** to # the output - or pack them by removing them from this list. # # Regenerate when the worker image changes: the command gives the /app part; merge it in and keep the # shared-framework entries the list already has. # docker run --rm --entrypoint sh redb-tsak-worker: -c "ls /app/*.dll /app/Libs/shared/*.dll" | sed "s|.*/||" | sort -u # AWSSDK.Core.dll AWSSDK.S3.dll AWSSDK.SQS.dll AWSSDK.SimpleNotificationService.dll Amqp.Net.dll Azure.Core.Amqp.dll Azure.Core.dll Azure.Messaging.ServiceBus.dll BCrypt-Net-Next.dll BouncyCastle.Cryptography.dll Chr.Avro.Binary.dll Chr.Avro.Json.dll Chr.Avro.dll Confluent.Kafka.dll CsvHelper.dll Elastic.Clients.Elasticsearch.dll Elastic.Esql.dll Elastic.Transport.dll FirebaseAdmin.dll FluentFTP.dll FluentValidation.dll Google.Api.CommonProtos.dll Google.Api.Gax.Grpc.dll Google.Api.Gax.Rest.dll Google.Api.Gax.dll Google.Apis.Auth.dll Google.Apis.Core.dll Google.Apis.Storage.v1.dll Google.Apis.dll Google.Cloud.Firestore.V1.dll Google.Cloud.Firestore.dll Google.Cloud.Location.dll Google.Cloud.Storage.V1.dll Google.LongRunning.dll Google.Protobuf.dll Grpc.Auth.dll Grpc.Core.Api.dll Grpc.Net.Client.dll Grpc.Net.Common.dll Humanizer.dll Json.More.dll JsonPath.Net.dll JsonPointer.Net.dll JsonSchema.Net.dll Jsonata.Net.Native.SystemTextJson.dll Jsonata.Net.Native.dll MQTTnet.dll MailKit.dll MessagePack.Annotations.dll MessagePack.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Protocols.MessagePack.dll Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll Microsoft.Azure.Amqp.dll Microsoft.Bcl.AsyncInterfaces.dll Microsoft.Bcl.Cryptography.dll Microsoft.Data.SqlClient.Extensions.Abstractions.dll Microsoft.Data.SqlClient.Internal.Logging.dll Microsoft.Data.SqlClient.dll Microsoft.Data.Sqlite.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.CommandLine.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.Configuration.UserSecrets.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.Diagnostics.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.dll Microsoft.Extensions.Diagnostics.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.Console.dll Microsoft.Extensions.Logging.Debug.dll Microsoft.Extensions.Logging.EventLog.dll Microsoft.Extensions.Logging.EventSource.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.Identity.Client.Extensions.Msal.dll Microsoft.Identity.Client.dll Microsoft.IdentityModel.Abstractions.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Protocols.OpenIdConnect.dll Microsoft.IdentityModel.Protocols.dll Microsoft.IdentityModel.Tokens.dll Microsoft.NET.StringTools.dll Microsoft.SqlServer.Server.dll MimeKit.dll Newtonsoft.Json.dll Novell.Directory.Ldap.NETStandard.dll Npgsql.dll OpenTelemetry.Api.ProviderBuilderExtensions.dll OpenTelemetry.Api.dll OpenTelemetry.Exporter.OpenTelemetryProtocol.dll OpenTelemetry.Exporter.Prometheus.HttpListener.dll OpenTelemetry.Extensions.Hosting.dll OpenTelemetry.Instrumentation.Process.dll OpenTelemetry.Instrumentation.Runtime.dll OpenTelemetry.dll Pipelines.Sockets.Unofficial.dll Quartz.Extensions.DependencyInjection.dll Quartz.Extensions.Hosting.dll Quartz.Serialization.Json.dll Quartz.dll RabbitMQ.Client.OAuth2.dll RabbitMQ.Client.dll Renci.SshNet.dll SQLitePCLRaw.batteries_v2.dll SQLitePCLRaw.core.dll SQLitePCLRaw.provider.e_sqlite3.dll Scriban.dll Serilog.AspNetCore.dll Serilog.Enrichers.Environment.dll Serilog.Enrichers.Process.dll Serilog.Enrichers.Thread.dll Serilog.Extensions.Hosting.dll Serilog.Extensions.Logging.dll Serilog.Formatting.Compact.dll Serilog.Settings.Configuration.dll Serilog.Sinks.Console.dll Serilog.Sinks.Debug.dll Serilog.Sinks.File.dll Serilog.dll StackExchange.Redis.dll System.ClientModel.dll System.CodeDom.dll System.Configuration.ConfigurationManager.dll System.Diagnostics.EventLog.dll System.IO.Hashing.dll System.IdentityModel.Tokens.Jwt.dll System.Management.dll System.Memory.Data.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll Telegram.Bot.dll XPath2.dll YamlDotNet.dll amqmdnetstd.dll amqmxmsstd.dll redb.Core.Pro.dll redb.Core.dll redb.Licensing.dll redb.MSSql.Pro.dll redb.MSSql.dll redb.Postgres.Pro.dll redb.Postgres.dll redb.Route.Amqp.dll redb.Route.As2.dll redb.Route.As4.dll redb.Route.AzureServiceBus.dll redb.Route.Cache.dll redb.Route.Controllers.dll redb.Route.Core.dll redb.Route.DataFormats.Avro.dll redb.Route.DataFormats.Csv.dll redb.Route.DataFormats.Mime.dll redb.Route.DataFormats.Protobuf.dll redb.Route.DataFormats.XmlJson.dll redb.Route.DataFormats.Yaml.dll redb.Route.Elasticsearch.dll redb.Route.Exec.dll redb.Route.File.dll redb.Route.Firebase.dll redb.Route.Ftp.dll redb.Route.GenericFile.dll redb.Route.Grpc.dll redb.Route.Http.Hosting.dll redb.Route.Http.dll redb.Route.IbmMq.dll redb.Route.JsonTransform.dll redb.Route.Kafka.dll redb.Route.Ldap.dll redb.Route.Llm.Abstractions.dll redb.Route.Llm.Mcp.dll redb.Route.Llm.Tools.dll redb.Route.Llm.dll redb.Route.Mail.dll redb.Route.MqttNet.dll redb.Route.Quartz.dll redb.Route.RabbitMQ.dll redb.Route.Redis.dll redb.Route.S3.dll redb.Route.Sftp.dll redb.Route.SignalR.StackExchangeRedis.dll redb.Route.SignalR.dll redb.Route.Soap.dll redb.Route.Sql.dll redb.Route.Sqs.dll redb.Route.Tcp.dll redb.Route.Telegram.dll redb.Route.Templates.dll redb.Route.Validation.Adapters.dll redb.Route.WebSocket.dll redb.Route.XPath2.dll redb.Route.Xml.dll redb.Route.dll redb.SQLite.Pro.dll redb.SQLite.dll redb.Tsak.Contracts.dll redb.Tsak.Core.Pro.dll redb.Tsak.Core.dll redb.Tsak.Worker.dll Path: redb/redb.Templates/templates/redb-console/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-console/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Console", "Database", "RedBase" ], "identity": "RedBase.Console.Template", "name": "RedBase Console Application", "description": "A console application on redb: objects with typed props created, queried, aggregated and arranged in a tree, in SQLite, PostgreSQL or SQL Server.", "shortName": "redb", "tags": { "language": "C#", "type": "project" }, "sourceName": "RedbApp", "preferNameDirectory": true, "symbols": { "db": { "type": "parameter", "datatype": "choice", "defaultValue": "sqlite", "displayName": "Database", "description": "Database provider to use", "choices": [ { "choice": "postgres", "description": "PostgreSQL (via Npgsql)" }, { "choice": "mssql", "description": "Microsoft SQL Server" }, { "choice": "sqlite", "description": "SQLite (embedded; Pro runs in Blazor WASM / mobile)" } ] }, "pro": { "type": "parameter", "datatype": "bool", "defaultValue": "true", "displayName": "Pro features", "description": "Include Pro features (LINQ compilation, change tracking, analytics)" }, "UsePostgres": { "type": "computed", "value": "(db == \"postgres\")" }, "UseMsSql": { "type": "computed", "value": "(db == \"mssql\")" }, "UseSqlite": { "type": "computed", "value": "(db == \"sqlite\")" } }, "sources": [ { "modifiers": [] } ] } Path: redb/redb.Templates/templates/redb-console/Models/Product.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-console/Models/Product.cs ---- using redb.Core.Attributes; namespace RedbApp.Models; /// /// Example product with typed Props. /// RedBase stores each property in a real typed column — not JSON. /// [RedbScheme("Product")] public class Product { public decimal Price { get; set; } public string Category { get; set; } = string.Empty; public bool InStock { get; set; } public string[] Tags { get; set; } = []; } /// /// Category tree node. /// Use CreateChildAsync to build hierarchies. /// RedBase stores parent-child via _id_parent FK with ON DELETE CASCADE. /// [RedbScheme("Category")] public class Category { public int SortOrder { get; set; } } Path: redb/redb.Templates/templates/redb-console/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-console/Program.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; #if (pro) using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; #else using redb.Core.Extensions; #endif #if (UsePostgres && pro) using redb.Postgres.Pro.Extensions; #elif (UsePostgres) using redb.Postgres.Extensions; #elif (UseMsSql && pro) using redb.MSSql.Pro.Extensions; #elif (UseMsSql) using redb.MSSql.Extensions; #elif (UseSqlite && pro) using redb.SQLite.Pro.Extensions; #elif (UseSqlite) using redb.SQLite.Extensions; #endif using RedbApp.Models; namespace RedbApp; class Program { static async Task Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; // --- DI Setup --- var services = new ServiceCollection(); services.AddLogging(b => b .AddConsole() .SetMinimumLevel(LogLevel.Information) .AddFilter("Microsoft.EntityFrameworkCore", LogLevel.Warning)); #if (pro) // Pro: LINQ compilation, change tracking, analytics, window functions. // To switch provider: uncomment the line you want, comment the current one, and swap the // redb.* PackageReference in RedbApp.csproj to match (see the comment there). services.AddRedbPro(options => options #if (UsePostgres) .UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") //.UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s //.UseSqlite(@"Data Source=redb_app.db") #elif (UseMsSql) //.UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") .UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s //.UseSqlite(@"Data Source=redb_app.db") #else //.UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") //.UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s .UseSqlite(@"Data Source=redb_app.db") // Pro tier runs in Blazor WASM / mobile too #endif // .WithLicense("YOUR_LICENSE_KEY") // Not needed: Pro is free and unrestricted .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); #else // Free edition. // To switch provider: uncomment the line you want, comment the current one, and swap the // redb.* PackageReference in RedbApp.csproj to match (see the comment there). services.AddRedb(options => options #if (UsePostgres) .UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") //.UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s //.UseSqlite(@"Data Source=redb_app.db") #elif (UseMsSql) //.UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") .UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s //.UseSqlite(@"Data Source=redb_app.db") #else //.UsePostgres("Host=localhost;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_app;Pooling=true;Include Error Detail=true;Options=-c jit=off") //.UseMsSql("Server=127.0.0.1,1433;Database=redb_app;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1, not localhost: localhost resolves to ::1 first and a container listening on [::]:1433 makes the connect hang ~63s // The Free tier hosts its server-side SQL functions in a native SQLite extension. The // redb.SQLite package ships it and the provider picks it up next to the app, so there is // nothing to install. macOS binaries are not built yet: use Pro there. .UseSqlite(@"Data Source=redb_app.db") #endif ); #endif await using var provider = services.BuildServiceProvider(); // One scope per unit of work. An IRedbService is one connection: a service kept for the life of the process // cannot serve parallel flows (a web request, a job, a message handler each resolve their own from a scope). // A console does its work in one flow, so the scope here only shows the shape that carries over to hosts. await using var scope = provider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // --- Initialize: create the schema if absent, sync schemes, warm up caches --- // ensureCreated builds the redb tables on first run and is idempotent afterwards, so it is // safe to leave on. It does not CREATE DATABASE: for Postgres and SQL Server the database in // the connection string has to exist already. SQLite creates its file by itself. Console.WriteLine("Initializing RedBase..."); await redb.InitializeAsync(ensureCreated: true); Console.WriteLine("Ready."); Console.WriteLine(); // ----------------------------------------------- // 1. Create // ----------------------------------------------- // An object is a plain `new`: Name is the object's own field, Props is your class. var product = new RedbObject { Name = "MacBook Pro 16", Props = new Product { Price = 2499.99m, Category = "Laptops", InStock = true, Tags = ["apple", "laptop", "pro"] } }; await redb.SaveAsync(product); Console.WriteLine($"Created: #{product.Id} {product.Name}"); // ----------------------------------------------- // 2. Load // ----------------------------------------------- var loaded = await redb.LoadAsync(product.Id) ?? throw new InvalidOperationException($"Product {product.Id} was not loaded."); Console.WriteLine($"Loaded: #{loaded.Id} {loaded.Name} — {loaded.Props!.Category}, ${loaded.Props.Price:F2}"); Console.WriteLine($" Tags: {string.Join(", ", loaded.Props.Tags)}"); // ----------------------------------------------- // 3. Update // ----------------------------------------------- loaded.Props.Price = 2299.99m; loaded.Props.Tags = ["apple", "laptop", "pro", "sale"]; await redb.SaveAsync(loaded); Console.WriteLine($"Updated: price -> ${loaded.Props.Price:F2}"); // ----------------------------------------------- // 4. Query — LINQ over your own properties, no SQL // ----------------------------------------------- // Query() is a Free-tier capability. The lambda runs against Props, so the fields you // filter on are the ones you declared in the Product class. var query = redb.Query(); var laptops = await query .Where(x => x.Category == "Laptops" && x.InStock) .OrderByDescending(x => x.Price) .ToListAsync(); Console.WriteLine($"Query: {laptops.Count} laptop(s) in stock"); #if (pro) // ----------------------------------------------- // 5. Pro: Aggregation pushed down to the database // ----------------------------------------------- var avgPrice = await redb.Query().AverageAsync(x => x.Price); Console.WriteLine($"Avg: ${avgPrice:F2}"); #endif // ----------------------------------------------- // Tree: parent-child hierarchy // ----------------------------------------------- Console.WriteLine(); Console.WriteLine("--- Tree Demo ---"); // A node of a hierarchy is a TreeRedbObject; CreateChildAsync takes the node and its // parent, and returns the new id. var root = new TreeRedbObject { Name = "Electronics", Props = new Category { SortOrder = 1 } }; await redb.SaveAsync(root); var child = new TreeRedbObject { Name = "Laptops", Props = new Category { SortOrder = 1 } }; await redb.CreateChildAsync(child, root); var grandchild = new TreeRedbObject { Name = "Gaming Laptops", Props = new Category { SortOrder = 2 } }; await redb.CreateChildAsync(grandchild, child); var tree = await redb.LoadTreeAsync(root.Id); PrintTree(tree, 0); // ----------------------------------------------- // Cleanup // ----------------------------------------------- Console.WriteLine(); await redb.DeleteAsync(product.Id); await redb.DeleteAsync(root.Id); // Cascade deletes children Console.WriteLine("Cleaned up. Done!"); } // ITreeRedbObject, not TreeRedbObject: Children is a collection of the interface, // so a typed parameter would not accept what the recursion hands it. static void PrintTree(ITreeRedbObject node, int indent) { Console.WriteLine($"{new string(' ', indent * 2)}{node.Name} (id={node.Id})"); foreach (var child in node.Children) PrintTree(child, indent + 1); } } Path: redb/redb.Templates/templates/redb-console/RedbApp.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-console/RedbApp.csproj ---- Exe net10.0 enable enable RedbApp 4.8.0 false Path: redb/redb.Templates/templates/redb-identity-app/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/.dockerignore ---- **/bin/ **/obj/ *.db *.db-shm *.db-wal deploy/output/ deploy/.env Path: redb/redb.Templates/templates/redb-identity-app/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Web", "Blazor", "BFF", "API", "Identity", "RedBase" ], "identity": "RedBase.IdentityApp.Template", "name": "RedBase application on redb.Identity", "description": "A Tsak module next to redb.Identity in one worker (bearer tokens checked by introspection over direct-vm, the management API in process) and a Blazor web server that signs users in with OpenID Connect.", "shortName": "redb-identity-app", "tags": { "language": "C#", "type": "solution" }, "sourceName": "RedbIdentityApp", "preferNameDirectory": true, "symbols": { "framework": { "type": "parameter", "datatype": "choice", "choices": [ { "choice": "net10.0", "description": ".NET 10" }, { "choice": "net11.0", "description": ".NET 11" } ], "defaultValue": "net10.0", "displayName": "Target framework", "description": "The target framework of the web server. The module and its contracts load into the Tsak worker and stay on net10.0, the worker's runtime." }, "webTargetFramework": { "type": "generated", "generator": "regex", "parameters": { "source": "framework", "steps": [ { "regex": "^(.*)$", "replacement": "$1" } ] }, "replaces": "net10.0" }, "dotnetImage": { "type": "generated", "generator": "regex", "parameters": { "source": "framework", "steps": [ { "regex": "^net(.*)$", "replacement": "DOTNET_VERSION=$1" } ] }, "replaces": "DOTNET_VERSION=10.0" }, "web": { "type": "parameter", "datatype": "bool", "defaultValue": "true", "displayName": "Web server", "description": "Add the Blazor web server that signs users in with OpenID Connect. Without it, only the module and its API." } }, "SpecialCustomOperations": { "**/*.slnx": { "operations": [ { "type": "conditional", "configuration": { "actionableIf": [ " net10.0 net10.0 enable enable 4.8.0 false 11.0.0 10.0.15 Path: redb/redb.Templates/templates/redb-identity-app/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/README.md ---- # RedbIdentityApp An application on redb.Identity: a Tsak module that runs in the same worker as Identity, and a Blazor web server where users sign in with OpenID Connect. The sample data is a list of notes per user and, for administrators, Identity's user list. - **The module** (`RedbIdentityApp.Module`) is a redb.Route REST API. Every request carries a bearer token, and the module asks Identity about it (token introspection). Identity is in the same process, so the call goes over `direct-vm`: no network, no TLS, no serialization. - **The web server** (`RedbIdentityApp.Web`) is the backend-for-frontend. Users sign in at Identity (code flow with PKCE); the browser holds only a session cookie, the tokens stay on the server, and the server calls the module with the user's access token. The web server is optional: `dotnet new redb-identity-app --web false` creates the module alone, for an API that other clients call. `--framework net10.0` (the default) or `net11.0` sets the target framework of the web server. The module and its contracts load into the Tsak worker, so they stay on `net10.0`, the worker's runtime. ## Run Identity and the module run in the `redb-identity-full` image (Tsak worker, Tsak dashboard, Identity's own sign-in and admin UI). From the project folder: ```bash cp deploy/.env.example deploy/.env # set the secrets: 32 random characters or more each pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbIdentityApp.tpkg docker compose -f deploy/docker-compose.yml up -d --build ``` Open http://localhost:5085 and sign in as `admin` with `IDENTITY_ADMIN_PASSWORD`. Identity answers at https://localhost:5002 with the image's self-signed certificate: the browser warns once. To work on the web server, stop its container (`docker compose -f deploy/docker-compose.yml stop web`) and run it on the host: `dotnet run --project RedbIdentityApp.Web`. In the Development environment it accepts Identity's self-signed certificate and takes its client secret from `appsettings.Development.json`, the same value as `WEB_CLIENT_SECRET` in `deploy/.env.example`. After a change to the module, pack it again: the worker reloads `deploy/output/RedbIdentityApp.tpkg` on its own. ## Projects | Project | What it is | |---------|------------| | `RedbIdentityApp.Contracts` | What the web server and the module exchange. No RedBase | | `RedbIdentityApp.Module` | The module: `InitRoute.main`, the controllers, the calls into Identity | | `RedbIdentityApp.Web` | The web server: Blazor pages, the OpenID Connect sign-in, the token store, the module client | ## Where things are | File | What it does | |------|--------------| | `RedbIdentityApp.Module/InitRoute.cs` | The API endpoint with the bearer check, the gate, the controllers; the route for Identity's events | | `RedbIdentityApp.Module/Identity/TokenIntrospector.cs` | Introspection over direct-vm and its cache | | `RedbIdentityApp.Module/Identity/BearerTokenValidator.cs` | What a token becomes: a principal, a 401, or "Identity is down" | | `RedbIdentityApp.Module/Identity/IdentityGate.cs` | 503 when Identity is down, 403 without the API scope | | `RedbIdentityApp.Module/Identity/IdentityManagement.cs` | The management API in process, with the module's service token | | `RedbIdentityApp.Module/Identity/IdentitySetup.cs` | The module's scopes and clients at Identity, created and kept up to date | | `RedbIdentityApp.Module/Identity/RevocationEvents.cs` | Drops cached token checks when Identity reports a revocation | | `RedbIdentityApp.Module/Controllers/` | `/api/me`, `/api/notes`, `/api/admin/users` | | `RedbIdentityApp.Web/Program.cs` | The cookie session, the OpenID Connect handler, sign-in and sign-out | | `RedbIdentityApp.Web/Auth/` | The server-side token store and the refresh | | `RedbIdentityApp.Web/Services/ModuleClient.cs` | The module's API with the user's token | ## How the module checks a token The API endpoint has `inboundAuth=bearer`: redb.Route takes the bearer token and hands it to `BearerTokenValidator`, which asks Identity (RFC 7662). The module introspects as its own client, the **resource client** `redbidentityapp-api`, with its own secret. Identity decides whether the token is good: signature, expiry, revocation. The module checks what is left to a resource server (RFC 9068 §4): the token is an access token, and its audience names the resource client. A token names that client in `aud` only when it was issued with a scope whose `Resources` list it, the API scope `redbidentityapp.api` or the administrative one. Identity itself answers `active: false` to a client outside a token's audience; the module checks `aud` as well, so a token issued for another client or API is turned away even by an Identity that does not. | The request | The answer | |-------------|------------| | No token, or one Identity calls inactive (expired, revoked, issued for another API) | 401, `WWW-Authenticate: Bearer realm="redbidentityapp", error="invalid_token"` | | A good token without the API scope | 403, `WWW-Authenticate: Bearer error="insufficient_scope", scope="redbidentityapp.api"` | | A good token, an administrative call, no administrative scope | 403, the same header with `scope="redbidentityapp.admin"` | | Identity down, not started yet, or refusing the module's own secret | 503 with `Retry-After`; never 401, because the token may be good | Answers are cached by the SHA-256 of the token (the token itself is not stored): - an active answer for `Identity:Introspection:CacheSeconds` (60), never past the token's own expiry; - an inactive one for `InactiveCacheSeconds` (10); - concurrent requests with one token share one introspection; - nothing is cached when Identity could not be asked. ### Revocation A cached answer outlives a revocation by at most the cache time, unless Identity reports it. The compose file makes it report: Identity's audit sends its events to `direct-vm://redbidentityapp-identity-events` (`Identity:Audit:Targets` of `identity.core`), and the module drops the cached answers of the user named in a revocation, a sign-out, a password change, a disabled or deleted account; a changed client or signing key drops all of them, and so does an event that names no user. Removing the module means removing that audit target too, otherwise Identity logs an error for every event it cannot deliver. ## Administrators and the management API The administrative scope `redbidentityapp.admin` is attached to Identity's `admin` role, and Identity's `AdminScopeEntitlement:GatedScopes` lists it (compose file): Identity puts it into a token only for users whose role carries it, and drops it for everyone else. The web server asks for it for every user; the module answers 403 when it is missing. A role only entitles a scope the client asked for, so a token of some other client never carries the module's administrative scope. Assign the `admin` role in Identity's UI to make someone an administrator; the change applies at their next sign-in or token refresh. `/api/admin/users` reads Identity's management API in process. The call runs as the module's service client (Identity's `SeedBackchannelClient`, scope `identity:manage`), not as the user: the user's token proves the right, the module does the work. Every management route is closed until the same exchange has passed Identity's management gate with that token (`IdentityManagement.CallAsync`). ## What the module sets up at Identity On every start, in the background, the module brings Identity to its settings (`IdentitySetup`): 1. the scopes `redbidentityapp.api` and `redbidentityapp.admin`, with the resource client in their `Resources`; 2. the resource client, allowed to introspect; 3. the web server's client: confidential, code flow with PKCE, refresh tokens, no consent page, the redirect addresses of `Identity:WebRedirectUris` and `Identity:WebPostLogoutRedirectUris`; 4. the administrative scope on the `admin` role. A client or scope that exists already is updated to the settings (permissions, redirect addresses, resources), so a changed address takes effect at the next start. Secrets cannot be read back: after a changed secret Identity answers `invalid_client`, the log names the client, and the fix is to rotate the secret in Identity's UI and set the new value, or to start with an empty database. While Identity is still starting, the setup retries; the API answers 503 meanwhile. ## The web server - Sign-in: `/account/login` redirects to Identity; the answer comes back on `/signin-oidc` in the query of a top-level redirect, so every cookie can be `SameSite=Lax`. - The tokens go to `UserTokenStore` (an `IDistributedCache`, encrypted with DataProtection); the cookie holds a random session key and the granted scopes. A cookie whose tokens are gone is no session, and the user goes through Identity again, usually without a password. - `AccessTokens` refreshes the access token a minute before it expires, one refresh per session at a time, because Identity rotates refresh tokens. A refused refresh ends the session; Identity being unreachable does not: the current token is used while it is valid, then the page says to try again. - Sign-out (`POST /account/logout`) revokes the refresh token at Identity and ends the session there too. The token store is in memory: one server, and a restart signs users out of this application. For several replicas register a shared cache (`AddStackExchangeRedisCache`) and a shared DataProtection key ring. ## Settings The module reads its route context: `RedbIdentityApp.Module.config.json` first, then `Tsak:Contexts:redbidentityapp:Override`, which wins. The secrets exist only in the Override layer, as environment variables of the worker (`deploy/.env`): | Environment variable | What it is | |----------------------|------------| | `Tsak__Contexts__redbidentityapp__Override__Identity__ResourceClientSecret` | The resource client's secret | | `Tsak__Contexts__redbidentityapp__Override__Identity__ManagementClientSecret` | Identity's `SeedBackchannelClient:ClientSecret` | | `Tsak__Contexts__redbidentityapp__Override__Identity__WebClientSecret` | The web server's client secret, also `Identity__ClientSecret` of the web server | The web server reads `appsettings.json`: Identity's address, its client, the scopes, the module's address. ## Deploy | File | What runs | |------|-----------| | `deploy/docker-compose.yml` | Identity and the module in the `redb-identity-full` image on SQLite, and the web server | | `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml` | Add them with a second `-f`: the same on a database server | For a real deployment: - give Identity a real certificate and its public https address as the issuer (`Identity:Issuer` of `identity.core` and `IdentityTransport:Issuer` of `identity.http`), and drop the development certificate lines of `RedbIdentityApp.Web/Dockerfile`; - set the web server's public address in `Identity:WebRedirectUris` and `Identity:WebPostLogoutRedirectUris` of the module, and `Identity__Authority` of the web server; - keep the module's API port inside the worker's network: only the web server calls it. `pack-tpkg.ps1` puts the manifest, the module config, the module DLL and the dependencies the worker does not provide into the package. `deploy/shipped-module-deps.txt` lists what the worker provides, including `redb.Identity.Contracts.dll`, which comes from Identity's contracts carrier: a second copy in the package would split the contract types between the module and Identity. ## Talking to Identity over the network instead This template puts the module next to Identity on purpose: the calls are in process. An application that runs elsewhere uses Identity's HTTP endpoints instead (discovery, `/connect/token`, `/connect/introspect`, the management API under `/api/v1/identity`), as the scripts in redb.Identity's `demos` folder do. Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Contracts/Dtos.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Contracts/Dtos.cs ---- using System.ComponentModel.DataAnnotations; namespace RedbIdentityApp.Contracts; /// Who the module sees behind the bearer token: what Identity answered to the introspection. public sealed class MeDto { public string Subject { get; set; } = ""; public long? UserId { get; set; } public string? UserName { get; set; } public string? ClientId { get; set; } public List Scopes { get; set; } = []; public List Roles { get; set; } = []; public DateTimeOffset? ExpiresAt { get; set; } } /// A note of the signed-in user. Each user sees only their own notes. public sealed class NoteDto { public long Id { get; set; } [Required, StringLength(200, MinimumLength = 1)] public string Title { get; set; } = ""; [StringLength(4000)] public string? Text { get; set; } public DateTimeOffset CreatedAt { get; set; } } /// One row of the administrator's user list, read from Identity's management API. public sealed class UserSummaryDto { public long Id { get; set; } public string Login { get; set; } = ""; public string? Name { get; set; } public string? Email { get; set; } public bool Enabled { get; set; } } /// A page of a list. public sealed class Page { public List Items { get; set; } = []; public int Total { get; set; } } /// An error answer of the module; the message is meant for the user. public sealed class ApiError { public string Message { get; set; } = ""; } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Contracts/RedbIdentityApp.Contracts.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Contracts/RedbIdentityApp.Contracts.csproj ---- Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/AdminController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/AdminController.cs ---- using System.Globalization; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Route.Controllers.Attributes; using RedbIdentityApp.Contracts; using RedbIdentityApp.Module.Identity; namespace RedbIdentityApp.Module.Controllers; /// /// Administration: reads Identity's management API in process. Open only to a token that holds the /// administrative scope, which Identity issues to users of its admin role alone (see IdentitySetup). /// The management call runs as the module's service client, not as the user: the user's token proves /// the right, the module does the work. /// [Route("/api/admin")] public sealed class AdminController : ApiController { public const int PageSize = 20; /// GET /api/admin/users?page=: Identity's users, a page at a time. [HttpGet("users")] public async Task Users([FromQuery("page")] string? page) { if (RequireScope(Settings.AdminScope) is { } denied) return denied; var number = Math.Max(1, int.TryParse(page, CultureInfo.InvariantCulture, out var p) ? p : 1); IdentityAnswer answer; try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); answer = await Service().CallAsync(IdentityEndpoints.ManageUsers, "list", new ListRequest { Offset = (number - 1) * PageSize, Count = PageSize }, timeout.Token); } catch (IdentityUnavailableException) { Exchange.Out ??= Exchange.In.Clone(); Exchange.Out.Headers["Retry-After"] = IdentityGate.RetryAfterSeconds.ToString(CultureInfo.InvariantCulture); return Status(503, new ApiError { Message = "The sign-in service is not available. Try again shortly." }); } catch (IdentityRefusedException) { return Status(502, new ApiError { Message = "Identity refused the module's management client; see the module's log." }); } if (answer.IsError) return Status(502, new ApiError { Message = $"Identity answered {answer.Error}: {answer.ErrorDescription}" }); var users = answer.Body as PagedResult ?? throw new InvalidOperationException($"Unexpected answer of {IdentityEndpoints.ManageUsers}: {answer.Body?.GetType().Name}."); return new Page { Total = users.Total, Items = users.Items.Select(u => new UserSummaryDto { Id = u.Id, Login = u.Login ?? "", Name = u.DisplayName, Email = u.Email, Enabled = !string.Equals(u.Status, "disabled", StringComparison.OrdinalIgnoreCase), }).ToList(), }; } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/ApiController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/ApiController.cs ---- using System.ComponentModel.DataAnnotations; using System.Security.Claims; using redb.Core; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Http; using redb.Route.RedbCore.Extensions; using RedbIdentityApp.Contracts; using RedbIdentityApp.Module.Identity; namespace RedbIdentityApp.Module.Controllers; /// /// What the controllers of the module share. A controller is created for each request, without DI: what /// it needs comes from Context (the route context, whose registry holds the module's services) /// and Exchange (the request, whose principal is the checked bearer token). /// public abstract class ApiController : RedbController { /// The redb service of this request, scoped to the exchange. The empty name is the worker's default redb. protected IRedbService Redb => Context.GetRedbService("", Exchange); /// The caller: what Identity said about the token (). protected ClaimsPrincipal Caller => ExchangePrincipal.Get(Exchange) ?? throw new InvalidOperationException("The API route runs without a bearer check."); /// The token's subject: a stable, public id of the user (or of the client, for a service token). protected string Subject => Caller.FindFirst(BearerTokenValidator.SubjectClaim)!.Value; /// True for a user's token; a client-credentials token has no user. protected bool IsUser => Caller.HasClaim(c => c.Type == BearerTokenValidator.UserIdClaim); protected ModuleSettings Settings => Service(); protected T Service() where T : class => Context.GetFromRegistry(typeof(T).FullName!) ?? throw new InvalidOperationException($"{typeof(T).Name} is not registered."); /// /// Null when the token holds ; otherwise sets 403 with /// error="insufficient_scope" and returns the body to return. /// protected ApiError? RequireScope(string scope) { if (Caller.HasClaim(BearerTokenValidator.ScopeClaim, scope)) return null; IdentityGate.InsufficientScope(Exchange, Context.ContextId, scope); return new ApiError { Message = $"The token lacks the scope {scope}." }; } /// Sets the status code of the answer; the returned object is still the body. protected T Status(int code, T body) { Exchange.Out ??= Exchange.In.Clone(); Exchange.Out.Headers[HttpHeaders.ResponseCode] = code; return body; } protected ApiError NotFound(string message) => Status(404, new ApiError { Message = message }); /// The web server validates the form, but the module cannot trust that: the same attributes are checked here. protected ApiError? Invalid(object dto) { var errors = new List(); return Validator.TryValidateObject(dto, new ValidationContext(dto), errors, validateAllProperties: true) ? null : Status(400, new ApiError { Message = string.Join(" ", errors.Select(r => r.ErrorMessage)) }); } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/MeController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/MeController.cs ---- using redb.Route.Controllers.Attributes; using RedbIdentityApp.Contracts; using RedbIdentityApp.Module.Identity; namespace RedbIdentityApp.Module.Controllers; /// GET /api/me: who the module sees behind the token. Handy to check a token by hand. [Route("/api/me")] public sealed class MeController : ApiController { [HttpGet] public MeDto Get() { var caller = Caller; return new MeDto { Subject = Subject, UserId = long.TryParse(caller.FindFirst(BearerTokenValidator.UserIdClaim)?.Value, out var id) ? id : null, UserName = caller.FindFirst(BearerTokenValidator.NameClaim)?.Value, ClientId = caller.FindFirst(BearerTokenValidator.ClientIdClaim)?.Value, Scopes = caller.FindAll(BearerTokenValidator.ScopeClaim).Select(c => c.Value).ToList(), ExpiresAt = long.TryParse(caller.FindFirst(BearerTokenValidator.ExpiresClaim)?.Value, out var exp) ? DateTimeOffset.FromUnixTimeSeconds(exp) : null, }; } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/NotesController.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Controllers/NotesController.cs ---- using redb.Core.Models.Entities; using redb.Route.Controllers.Attributes; using RedbIdentityApp.Contracts; using RedbIdentityApp.Module.Props; namespace RedbIdentityApp.Module.Controllers; /// /// The notes of the signed-in user. Every query is filtered by the token's subject: a user never reaches /// another user's note, not even by its id. /// [Route("/api/notes")] public sealed class NotesController : ApiController { /// GET /api/notes: the caller's notes, newest first. [HttpGet] public async Task List() { if (!IsUser) return Status(403, new ApiError { Message = "Notes belong to users; a client token has none." }); var owner = Subject; var notes = await Redb.Query() .Where(n => n.Owner == owner) .OrderByDescendingRedb(n => n.DateCreate) .Take(100) .ToListAsync(); return notes.Select(ToDto).ToList(); } /// POST /api/notes: a new note of the caller. [HttpPost] public async Task Create([FromBody] NoteDto note) { if (!IsUser) return Status(403, new ApiError { Message = "Notes belong to users; a client token has none." }); if (Invalid(note) is { } invalid) return invalid; var saved = new RedbObject { Name = note.Title.Trim(), Props = new Note { Owner = Subject, Text = note.Text }, }; await Redb.SaveAsync(saved); return Status(201, ToDto(saved)); } /// DELETE /api/notes/{id}: only a note of the caller; any other id is "not found". [HttpDelete("{id}")] public async Task Delete(long id) { var note = await Redb.LoadAsync(id); if (note is null || note.Props.Owner != Subject) return NotFound("No such note."); return await Redb.DeleteAsync(id) ? null : NotFound("No such note."); } private static NoteDto ToDto(RedbObject note) => new() { Id = note.Id, Title = note.Name ?? "", Text = note.Props.Text, CreatedAt = note.DateCreate, }; } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/BearerTokenValidator.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/BearerTokenValidator.cs ---- using System.Security.Claims; using Microsoft.Extensions.Logging; using redb.Route.Http; namespace RedbIdentityApp.Module.Identity; /// /// The bearer check of the API endpoint (inboundAuth=bearer&tokenValidator=#... in InitRoute): /// redb.Route calls it before a controller runs. /// /// No token, or one Identity calls inactive (expired, revoked, issued for another API): it /// returns null, and redb.Route answers 401 with /// WWW-Authenticate: Bearer realm="...", error="invalid_token". /// An active token: a principal with the token's subject, user, client and scopes. /// Identity unreachable or refusing the module's own credentials: a principal marked /// . The validator's interface knows only "principal or null", and /// null would tell a client with a good token that its token is bad; /// turns the mark into 503. /// /// public sealed class BearerTokenValidator(TokenIntrospector introspector, ILogger logger) : IHttpTokenValidator { public const string RegistryName = "identity-introspection"; public const string AuthenticationType = "redb.Identity"; /// Marks a principal whose token could not be checked; the value says why. public const string UnavailableClaim = "redb:identity-unavailable"; public const string SubjectClaim = "sub"; public const string UserIdClaim = "redb:user_id"; public const string NameClaim = "name"; public const string ClientIdClaim = "client_id"; public const string ScopeClaim = "scope"; public const string ExpiresClaim = "exp"; public async Task ValidateAsync(string token, CancellationToken ct) { Introspection result; try { result = await introspector.IntrospectAsync(token, ct).ConfigureAwait(false); } catch (IdentityUnavailableException ex) { logger.LogWarning(ex, "Bearer token not checked: {Reason}", ex.Message); return Unavailable("Identity is not available"); } catch (IdentityRefusedException ex) { logger.LogError("Bearer token not checked: {Reason}", ex.Message); return Unavailable("Identity refused the module's client"); } if (!result.Active || result.Subject is null) return null; var claims = new List { new(SubjectClaim, result.Subject) }; if (result.UserId is { } userId) claims.Add(new(UserIdClaim, userId)); if (result.UserName is { } name) claims.Add(new(NameClaim, name)); if (result.ClientId is { } clientId) claims.Add(new(ClientIdClaim, clientId)); if (result.ExpiresAt is { } exp) claims.Add(new(ExpiresClaim, exp.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture))); claims.AddRange(result.Scopes.Select(scope => new Claim(ScopeClaim, scope))); return new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType, NameClaim, roleType: null)); } // Authenticated on purpose: an unauthenticated principal is a 401 in redb.Route. private static ClaimsPrincipal Unavailable(string reason) => new(new ClaimsIdentity([new Claim(UnavailableClaim, reason)], AuthenticationType)); } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityCalls.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityCalls.cs ---- using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; namespace RedbIdentityApp.Module.Identity; /// /// Calls into redb.Identity over direct-vm: Identity runs in the same Tsak worker, so a call is a method /// call on Identity's route, without a socket, TLS or serialization. /// /// One for the module, created once: it caches the producer of each /// endpoint. Each call gets an exchange of its own with a DI scope of its own, so parallel calls never /// share a database connection, and the exchange is always disposed. /// /// /// A failure inside Identity arrives as , not as a throw, and Identity's /// own error handling may already have marked it handled: the exception alone decides. /// /// public sealed class IdentityCalls : IDisposable { private readonly ProducerTemplate _producer; private readonly IServiceScopeFactory _scopes; public IdentityCalls(IRouteContext context, IServiceScopeFactory scopes) { _producer = new ProducerTemplate(context); _producer.Start(); _scopes = scopes; } /// /// Sends to and returns Identity's answer. The /// exchange is handed to first (headers, a preceding call on the same /// exchange) and disposed afterwards. Throws when Identity /// failed or did not answer in time. /// public async Task SendAsync( string endpoint, object? body, Func>? prepare, CancellationToken ct) { var exchange = new Exchange(new Message { Body = body }, _scopes); try { if (prepare is not null && await prepare(exchange, ct).ConfigureAwait(false) is { } refused) return refused; await _producer.RequestAsync(endpoint, exchange, ct).ConfigureAwait(false); if (exchange.Exception is { } failure) throw new IdentityUnavailableException($"redb.Identity failed at {endpoint}.", failure); return IdentityAnswer.From(exchange); } catch (OperationCanceledException ex) { // The caller's token carries the timeout (see the callers). throw new IdentityUnavailableException($"redb.Identity did not answer at {endpoint} in time.", ex); } catch (Exception ex) when (ex is not IdentityUnavailableException) { // The call itself failed: Identity's routes are not started yet (the worker is still loading // it), or it was unloaded and the direct-vm endpoint has no consumer. throw new IdentityUnavailableException($"redb.Identity could not be called at {endpoint}.", ex); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// Runs one more call on an exchange that is already open (Identity's management gate). public Task RequestOnAsync(string endpoint, IExchange exchange, CancellationToken ct) => _producer.RequestAsync(endpoint, exchange, ct); public void Dispose() => _producer.Dispose(); } /// /// What Identity answered: the body, plus the error code when the body is an OAuth or management error /// ({ error, error_description }). Identity answers with typed objects, dictionaries or anonymous /// objects depending on the route; reads any of them the same way. /// public sealed record IdentityAnswer(object? Body, string? Error, string? ErrorDescription) { public bool IsError => Error is not null; /// The body as JSON, whatever its .NET type. public JsonElement Json => Body switch { null => default, JsonElement element => element, byte[] bytes => JsonDocument.Parse(bytes).RootElement.Clone(), string text when text.TrimStart().StartsWith('{') || text.TrimStart().StartsWith('[') => JsonDocument.Parse(text).RootElement.Clone(), _ => JsonSerializer.SerializeToElement(Body, Body.GetType()), }; public static IdentityAnswer From(IExchange exchange) { var body = exchange.Out?.Body ?? exchange.In.Body; var answer = new IdentityAnswer(body, null, null); var json = body is null ? default : answer.Json; return json.ValueKind == JsonValueKind.Object && json.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String ? answer with { Error = error.GetString(), ErrorDescription = json.TryGetProperty("error_description", out var description) ? description.GetString() : null, } : answer; } public static IdentityAnswer Refused(string error, string? description) => new(null, error, description); } /// Identity failed, timed out, or is not running: the module answers 503, never 401. public sealed class IdentityUnavailableException : Exception { public IdentityUnavailableException(string message) : base(message) { } public IdentityUnavailableException(string message, Exception inner) : base(message, inner) { } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityGate.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityGate.cs ---- using System.Globalization; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Http; namespace RedbIdentityApp.Module.Identity; /// /// The first step of the API route, after redb.Route's bearer check. No controller runs unless it lets /// the request through: /// /// the token could not be checked because Identity is down or refuses the module /// (): 503 with Retry-After; /// the token is good but was not issued for this API's scope: 403 with /// WWW-Authenticate: Bearer error="insufficient_scope" (RFC 6750 §3.1). /// /// A missing or bad token never gets here: redb.Route has answered 401 already. /// public sealed class IdentityGate(string realm, string apiScope) { public const int RetryAfterSeconds = 5; public Task Process(IExchange exchange, CancellationToken ct) { var principal = ExchangePrincipal.Get(exchange); if (principal?.FindFirst(BearerTokenValidator.UnavailableClaim)?.Value is { } reason) { Answer(exchange, 503, new { message = $"The sign-in service is not available ({reason}). Try again shortly." }); exchange.Out!.Headers["Retry-After"] = RetryAfterSeconds.ToString(CultureInfo.InvariantCulture); exchange.Stop(); } else if (principal?.HasClaim(BearerTokenValidator.ScopeClaim, apiScope) != true) { InsufficientScope(exchange, realm, apiScope); exchange.Stop(); } return Task.CompletedTask; } /// 403 for a token without ; the body is what the controller returns. public static void InsufficientScope(IExchange exchange, string realm, string scope) { Answer(exchange, 403, new { message = $"The token lacks the scope {scope}." }); exchange.Out!.Headers["WWW-Authenticate"] = $"Bearer realm=\"{realm}\", error=\"insufficient_scope\", error_description=\"The token lacks the scope {scope}\", scope=\"{scope}\""; } private static void Answer(IExchange exchange, int status, object body) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Headers[HttpHeaders.ResponseCode] = status; exchange.Out.Headers[HttpHeaders.ContentType] = "application/json"; exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(body, body.GetType()); } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityManagement.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentityManagement.cs ---- using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Routes; namespace RedbIdentityApp.Module.Identity; /// /// Identity's management API in process. Every identity-manage-* route is closed unless the same /// exchange first passed Identity's management gate () with /// a token holding identity:manage; there is no in-process shortcut around it, on purpose. /// /// The token is the module's service token: client credentials of the management client (Identity's /// SeedBackchannelClient), kept until a minute before it expires. A token the gate refuses is dropped, /// so the next call asks for a new one. /// /// public sealed class IdentityManagement(IdentityCalls calls, ModuleSettings settings, ILogger logger) { private const string ManageScope = "identity:manage"; private static readonly TimeSpan RenewBefore = TimeSpan.FromMinutes(1); private readonly SemaphoreSlim _tokenLock = new(1, 1); private string? _token; private DateTimeOffset _tokenExpiresAt; /// /// Runs on a management route (, /// , ...). Identity's own refusals come back as an answer with /// set (duplicate, not_found, validation_error); /// a refused service token throws , Identity being down throws /// . /// public async Task CallAsync(string endpoint, string operation, object? body, CancellationToken ct) { var token = await ServiceTokenAsync(ct).ConfigureAwait(false); var gateRefused = false; var answer = await calls.SendAsync(endpoint, body, async (exchange, c) => { exchange.In.Headers["Authorization"] = "Bearer " + token; await calls.RequestOnAsync(IdentityEndpoints.AuthManagement, exchange, c).ConfigureAwait(false); if (!exchange.IsStopped && exchange.Exception is null) { exchange.In.Headers["operation"] = operation; return null; } gateRefused = true; var refused = IdentityAnswer.From(exchange); return refused.IsError ? refused : IdentityAnswer.Refused("access_denied", "The management gate refused the service token."); }, ct).ConfigureAwait(false); if (gateRefused) { Forget(token); throw new IdentityRefusedException( $"Identity's management gate refused the service token of '{settings.ManagementClientId}': {answer.ErrorDescription ?? answer.Error}. " + $"The client needs the scope {ManageScope}."); } return answer; } private async Task ServiceTokenAsync(CancellationToken ct) { if (_token is { } cached && DateTimeOffset.UtcNow < _tokenExpiresAt - RenewBefore) return cached; await _tokenLock.WaitAsync(ct).ConfigureAwait(false); try { if (_token is { } fresh && DateTimeOffset.UtcNow < _tokenExpiresAt - RenewBefore) return fresh; var request = new Dictionary(StringComparer.Ordinal) { ["grant_type"] = "client_credentials", ["client_id"] = settings.ManagementClientId, ["client_secret"] = settings.ManagementClientSecret, ["scope"] = ManageScope, }; var answer = await calls.SendAsync(IdentityEndpoints.Token, request, (exchange, _) => { // For Identity's audit and per-client throttle; the credentials themselves are in the body. exchange.In.Headers["client_id"] = settings.ManagementClientId; return Task.FromResult(null); }, ct).ConfigureAwait(false); if (answer.IsError) { throw new IdentityRefusedException( $"Identity refused client credentials of '{settings.ManagementClientId}': {answer.ErrorDescription ?? answer.Error}. " + "Check Identity:ManagementClientSecret against Identity's SeedBackchannelClient:ClientSecret."); } var json = answer.Json; var token = json.GetProperty("access_token").GetString() ?? throw new IdentityRefusedException("Identity's token answer has no access_token."); var lifetime = json.TryGetProperty("expires_in", out var expiresIn) ? Seconds(expiresIn) : 300; _token = token; _tokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(lifetime); logger.LogDebug("Management token of {ClientId} obtained, valid for {Seconds} s", settings.ManagementClientId, lifetime); return token; } finally { _tokenLock.Release(); } } private void Forget(string token) { if (ReferenceEquals(Volatile.Read(ref _token), token)) Volatile.Write(ref _token, null); } // expires_in is a number, sometimes a string. private static long Seconds(JsonElement value) => value.ValueKind == JsonValueKind.Number ? value.GetInt64() : long.Parse(value.GetString() ?? "300", CultureInfo.InvariantCulture); } /// Identity answered, but refused the module's own credentials: a configuration error. public sealed class IdentityRefusedException(string message) : Exception(message); Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentitySetup.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/IdentitySetup.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Roles; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Scopes; namespace RedbIdentityApp.Module.Identity; /// /// Puts at Identity what the module needs, through the management API, and keeps it that way on every /// start: /// /// the API scope and the administrative scope, both with the resource client in their /// Resources, so a token issued with them names that client in aud; /// the resource client, allowed to introspect; /// the web server's client (when configured): code flow with PKCE, refresh tokens, the redirect /// addresses from the settings; /// the administrative scope attached to Identity's admin role, so Identity issues it to /// administrators only. /// /// A client or scope that exists already is brought to the settings (permissions, redirect addresses, /// resources) instead of being skipped. A secret cannot be read back: when it differs from the setting, /// Identity answers invalid_client and the log says which one to fix. /// /// Runs in the background, after the context has started, and retries while Identity is still starting /// or unreachable; the API answers 503 meanwhile, because introspection fails the same way. /// /// public sealed class IdentitySetup(IdentityManagement management, ModuleSettings settings, ILogger logger) { private const string AdminRole = "admin"; private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web); private static readonly TimeSpan CallTimeout = TimeSpan.FromSeconds(15); public async Task RunAsync(CancellationToken ct) { var delay = TimeSpan.FromSeconds(2); while (!ct.IsCancellationRequested) { try { await ApplyAsync(ct).ConfigureAwait(false); logger.LogInformation("Identity set up for the module: scopes {Api}, {Admin}; clients {Resource}{Web}", settings.ApiScope, settings.AdminScope, settings.ResourceClientId, settings.WebClientId is null ? "" : ", " + settings.WebClientId); return; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } catch (IdentityUnavailableException ex) { logger.LogInformation("Identity is not available yet ({Reason}); next try in {Seconds} s", ex.Message, (int)delay.TotalSeconds); } catch (Exception ex) { // A refused client secret or an answer the module did not expect: retrying will not fix // it by itself, but the operator can, so keep trying, slowly and loudly. logger.LogError(ex, "Identity setup failed; next try in {Seconds} s", (int)delay.TotalSeconds); } await Task.Delay(delay, ct).ConfigureAwait(false); delay = TimeSpan.FromSeconds(Math.Min(delay.TotalSeconds * 2, 60)); } } private async Task ApplyAsync(CancellationToken ct) { await EnsureScopeAsync(settings.ApiScope, "RedbIdentityApp API", ct).ConfigureAwait(false); var adminScope = await EnsureScopeAsync(settings.AdminScope, "RedbIdentityApp administration", ct).ConfigureAwait(false); // OpenIddict permission names, written out: the module does not reference OpenIddict. await EnsureClientAsync(new CreateApplicationRequest { ClientId = settings.ResourceClientId, ClientSecret = settings.ResourceClientSecret, DisplayName = "RedbIdentityApp API", ClientType = "confidential", ApplicationType = "web", Permissions = ["ept:introspection"], }, ct).ConfigureAwait(false); if (settings.WebClientId is { } webClientId) { await EnsureClientAsync(new CreateApplicationRequest { ClientId = webClientId, ClientSecret = settings.WebClientSecret, DisplayName = "RedbIdentityApp", ClientType = "confidential", ApplicationType = "web", // The application is first party: no consent page. ConsentType = "implicit", Permissions = [ // Pushed authorization requests: ASP.NET Core 9+ uses them whenever Identity offers them. "ept:authorization", "ept:pushed_authorization", "ept:token", "ept:end_session", "ept:revocation", "gt:authorization_code", "gt:refresh_token", "rst:code", "scp:openid", "scp:profile", "scp:email", "scp:offline_access", "scp:" + settings.ApiScope, "scp:" + settings.AdminScope, ], Requirements = ["ft:pkce"], RedirectUris = [.. settings.WebRedirectUris], PostLogoutRedirectUris = [.. settings.WebPostLogoutRedirectUris], }, ct).ConfigureAwait(false); } await AttachToAdminRoleAsync(adminScope, ct).ConfigureAwait(false); } private async Task EnsureScopeAsync(string name, string displayName, CancellationToken ct) { var existing = await ReadAsync(IdentityEndpoints.ManageScopes, new Dictionary { ["name"] = name }, ct) .ConfigureAwait(false); if (existing is null) { var created = await CallAsync(IdentityEndpoints.ManageScopes, "create", new CreateScopeRequest { Name = name, DisplayName = displayName, Resources = [settings.ResourceClientId] }, ct).ConfigureAwait(false); if (created.Error != "duplicate") // another node created it at the same moment { logger.LogInformation("Scope {Scope} created", name); return Expect(created, $"create scope {name}"); } existing = await ReadAsync(IdentityEndpoints.ManageScopes, new Dictionary { ["name"] = name }, ct).ConfigureAwait(false) ?? throw new InvalidOperationException($"Scope {name} is reported as a duplicate but cannot be read."); } if (existing.Resources?.Contains(settings.ResourceClientId, StringComparer.Ordinal) == true) return existing; var updated = await CallAsync(IdentityEndpoints.ManageScopes, "update", new UpdateScopeRequest { Id = existing.Id, DisplayName = existing.DisplayName, Description = existing.Description, Resources = [.. existing.Resources ?? [], settings.ResourceClientId], ConcurrencyToken = existing.ConcurrencyToken, }, ct).ConfigureAwait(false); logger.LogInformation("Scope {Scope}: resource {Resource} added", name, settings.ResourceClientId); return Expect(updated, $"update scope {name}"); } private async Task EnsureClientAsync(CreateApplicationRequest desired, CancellationToken ct) { var read = new Dictionary { ["clientId"] = desired.ClientId }; var existing = await ReadAsync(IdentityEndpoints.ManageApps, read, ct).ConfigureAwait(false); if (existing is null) { var created = await CallAsync(IdentityEndpoints.ManageApps, "create", desired, ct).ConfigureAwait(false); if (created.Error != "duplicate") { Expect(created, $"create client {desired.ClientId}"); logger.LogInformation("Client {ClientId} created", desired.ClientId); return; } existing = await ReadAsync(IdentityEndpoints.ManageApps, read, ct).ConfigureAwait(false) ?? throw new InvalidOperationException($"Client {desired.ClientId} is reported as a duplicate but cannot be read."); } if (Same(existing.Permissions, desired.Permissions) && Same(existing.Requirements, desired.Requirements) && Same(existing.RedirectUris, desired.RedirectUris) && Same(existing.PostLogoutRedirectUris, desired.PostLogoutRedirectUris)) return; var updated = await CallAsync(IdentityEndpoints.ManageApps, "update", new UpdateApplicationRequest { Id = existing.Id, Permissions = desired.Permissions ?? [], Requirements = desired.Requirements ?? [], RedirectUris = desired.RedirectUris ?? [], PostLogoutRedirectUris = desired.PostLogoutRedirectUris ?? [], ConcurrencyToken = existing.ConcurrencyToken, }, ct).ConfigureAwait(false); Expect(updated, $"update client {desired.ClientId}"); logger.LogInformation("Client {ClientId} brought to the settings (permissions, redirect addresses)", desired.ClientId); } private async Task AttachToAdminRoleAsync(ScopeResponse adminScope, CancellationToken ct) { var search = await CallAsync(IdentityEndpoints.ManageRoles, "search", new Dictionary { ["query"] = AdminRole, ["count"] = 50 }, ct).ConfigureAwait(false); var role = Expect>(search, "find the admin role").Items .FirstOrDefault(r => string.Equals(r.Name, AdminRole, StringComparison.Ordinal)) ?? throw new InvalidOperationException($"Identity has no role '{AdminRole}'."); var attached = await CallAsync(IdentityEndpoints.ManageRoles, "list-scopes", new Dictionary { ["roleId"] = role.Id }, ct).ConfigureAwait(false); if (Expect>(attached, "list the admin role's scopes") .Any(s => string.Equals(s.ScopeName, adminScope.Name, StringComparison.Ordinal))) return; var attach = await CallAsync(IdentityEndpoints.ManageRoles, "attach-scope", new Dictionary { ["roleId"] = role.Id, ["scopeId"] = long.Parse(adminScope.Id, System.Globalization.CultureInfo.InvariantCulture) }, ct).ConfigureAwait(false); if (attach.IsError) throw new InvalidOperationException($"Identity refused to attach {adminScope.Name} to the role '{AdminRole}': {attach.ErrorDescription ?? attach.Error}"); logger.LogInformation("Scope {Scope} attached to the role '{Role}'", adminScope.Name, AdminRole); } // A read that answers not_found is "nothing there", not an error. private async Task ReadAsync(string endpoint, Dictionary key, CancellationToken ct) where T : class { var answer = await CallAsync(endpoint, "read", key, ct).ConfigureAwait(false); return answer.Error == "not_found" ? null : Expect(answer, $"read {string.Join(",", key.Values)}"); } private async Task CallAsync(string endpoint, string operation, object body, CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(CallTimeout); return await management.CallAsync(endpoint, operation, body, timeout.Token).ConfigureAwait(false); } // The typed answer; Identity answers in process with its contract types, so this is normally a cast. private static T Expect(IdentityAnswer answer, string what) where T : class { if (answer.IsError) throw new InvalidOperationException($"Identity refused to {what}: {answer.Error} {answer.ErrorDescription}"); return answer.Body as T ?? answer.Json.Deserialize(Web) ?? throw new InvalidOperationException($"Identity gave no answer to {what}."); } private static bool Same(string[]? current, string[]? desired) => new HashSet(current ?? [], StringComparer.Ordinal).SetEquals(desired ?? []); } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/RevocationEvents.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/RevocationEvents.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Events; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; namespace RedbIdentityApp.Module.Identity; /// /// Identity's audit events, delivered to the module's own direct-vm address /// (). Identity sends them only when its operator lists that /// address as an audit target (deploy/docker-compose.yml, README "Revocation"); without it the cache still /// expires after . /// /// A revocation for a user drops the cached answers for that user; a change to a client or a signing key /// drops all of them. Every other event is ignored. The step only bumps counters, so it never holds up /// Identity's event pipeline. /// /// public sealed class RevocationEvents(TokenIntrospector introspector, ILogger logger) { // Events after which a token of the user may no longer be good. private static readonly HashSet UserEvents = new(StringComparer.Ordinal) { IdentityAuditEventIds.TokenRevoked, IdentityAuditEventIds.TokensRevokedByUser, IdentityAuditEventIds.SessionRevoked, IdentityAuditEventIds.AllSessionsRevoked, IdentityAuditEventIds.SidRevoked, IdentityAuditEventIds.UserLoggedOut, IdentityAuditEventIds.UserUpdated, IdentityAuditEventIds.UserDeleted, IdentityAuditEventIds.PasswordChanged, IdentityAuditEventIds.PasswordResetCompleted, IdentityAuditEventIds.ConsentRevoked, IdentityAuditEventIds.AllConsentsRevoked, IdentityAuditEventIds.ScimUserReplaced, IdentityAuditEventIds.ScimUserPatched, IdentityAuditEventIds.ScimUserDeleted, }; // Events after which any token may no longer be good. private static readonly HashSet GlobalEvents = new(StringComparer.Ordinal) { IdentityAuditEventIds.ClientUpdated, IdentityAuditEventIds.ClientDeleted, IdentityAuditEventIds.ClientSecretRotated, IdentityAuditEventIds.SigningKeyRetired, IdentityAuditEventIds.ScopeUpdated, IdentityAuditEventIds.ScopeDeleted, }; public Task Process(IExchange exchange, CancellationToken ct) { var identityEvent = Read(exchange.In.Body); if (identityEvent is null) { logger.LogWarning("An Identity event the module could not read: {Type}", exchange.In.Body?.GetType().Name ?? "null"); return Task.CompletedTask; } if (GlobalEvents.Contains(identityEvent.EventType)) { introspector.RevokeAll(); logger.LogInformation("{Event}: cached token checks dropped", identityEvent.EventType); } else if (UserEvents.Contains(identityEvent.EventType)) { // The user is named by the internal id or, from some emitters, by the subject; the cache // keeps both. An event that names nobody drops everything rather than nothing. if (string.IsNullOrEmpty(identityEvent.UserId)) introspector.RevokeAll(); else introspector.RevokeUser(identityEvent.UserId); logger.LogInformation("{Event} for user {User}: cached token checks dropped", identityEvent.EventType, identityEvent.UserId ?? "(unknown)"); } return Task.CompletedTask; } // Identity hands its targets the event as JSON bytes; an in-process sender may pass the object. private static IdentityEvent? Read(object? body) { try { return body switch { IdentityEvent typed => typed, byte[] bytes => JsonSerializer.Deserialize(bytes), string text => JsonSerializer.Deserialize(text), _ => null, }; } catch (JsonException) { return null; } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/TokenIntrospector.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Identity/TokenIntrospector.cs ---- using System.Collections.Concurrent; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Routes; namespace RedbIdentityApp.Module.Identity; /// /// Checks a bearer token by asking Identity (RFC 7662 introspection over direct-vm) as the module's /// resource client, and keeps the answer for a short while. /// /// Identity decides whether the token is good: signature, expiry, revocation. What introspection leaves /// to the resource server, this class checks: the token must be an access token, and its audience must /// name this API's resource client (RFC 9068 §4). Identity answers active: false to a client outside /// a token's audience as well; the check here keeps the API closed to a token issued for another client or /// API even against an Identity that does not. /// /// /// Cache: keyed by the SHA-256 of the token (the token itself is never stored). An active answer lives /// , never past the token's own exp; an inactive /// one lives . A revocation Identity reports /// () bumps a generation, and every answer cached under an older /// generation is asked again. Concurrent requests with the same token share one introspection. /// When Identity cannot be reached, nothing is cached and the caller answers 503. /// /// public sealed class TokenIntrospector : IDisposable { private readonly IdentityCalls _calls; private readonly ModuleSettings _settings; private readonly ILogger _logger; private readonly MemoryCache _cache = new(new MemoryCacheOptions { SizeLimit = 50_000 }); private readonly ConcurrentDictionary> _inFlight = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _userGenerations = new(StringComparer.Ordinal); private long _globalGeneration; private long _revocations; public TokenIntrospector(IdentityCalls calls, ModuleSettings settings, ILogger logger) { _calls = calls; _settings = settings; _logger = logger; } /// The introspection of , from the cache or from Identity. public async Task IntrospectAsync(string token, CancellationToken ct) { var key = Hash(token); if (_cache.TryGetValue(key, out CachedIntrospection? cached) && cached is not null && IsCurrent(cached)) return cached.Result; var pending = _inFlight.GetOrAdd(key, StartAsking, token); return await pending.WaitAsync(ct).ConfigureAwait(false); } /// Identity reported a revocation for a user: every answer cached for them is asked again. public void RevokeUser(string userKey) { _userGenerations.AddOrUpdate(userKey, 1, (_, generation) => generation + 1); Interlocked.Increment(ref _revocations); } /// A change that may concern any token (a client, a signing key): the whole cache is asked again. public void RevokeAll() { Interlocked.Increment(ref _globalGeneration); Interlocked.Increment(ref _revocations); } // One question per token at a time; the task leaves the table when it completes. private Task StartAsking(string key, string token) { var task = AskIdentityAsync(key, token); task.ContinueWith(t => _inFlight.TryRemove(new KeyValuePair>(key, t)), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); return task; } private async Task AskIdentityAsync(string key, string token) { // Never completes synchronously, so the task is in the table before it leaves it. await Task.Yield(); // A revocation reported while Identity is answering: the answer is used once and not cached. var revocationsBefore = Interlocked.Read(ref _revocations); var global = Interlocked.Read(ref _globalGeneration); using var timeout = new CancellationTokenSource(_settings.IntrospectionTimeout); var request = new Dictionary(StringComparer.Ordinal) { ["token"] = token, ["token_type_hint"] = "access_token", ["client_id"] = _settings.ResourceClientId, ["client_secret"] = _settings.ResourceClientSecret, }; var answer = await _calls.SendAsync(IdentityEndpoints.Introspect, request, (exchange, _) => { exchange.In.Headers["client_id"] = _settings.ResourceClientId; // audit and throttle only return Task.FromResult(null); }, timeout.Token).ConfigureAwait(false); if (answer.IsError) { // invalid_client: the resource client or its secret is wrong, a configuration error of this // module, not a bad token. Anything else (a token Identity will not discuss with this client, // e.g. issued for another audience) is an inactive token. if (answer.Error == "invalid_client") throw new IdentityRefusedException( $"Identity refused introspection by '{_settings.ResourceClientId}': {answer.ErrorDescription ?? answer.Error}. " + "Check Identity:ResourceClientSecret."); _logger.LogDebug("Introspection refused: {Error} {Description}", answer.Error, answer.ErrorDescription); return Store(key, Introspection.Inactive, global, revocationsBefore, null); } var result = Introspection.Read(answer.Json); if (result.Active && result.TokenUsage is { } usage && usage != "access_token") result = Introspection.Inactive; // a refresh or id token is not a bearer for an API if (result.Active && !result.Audiences.Contains(_settings.ResourceClientId, StringComparer.Ordinal)) { // Issued for another API (RFC 9068 §4): Identity may still describe it to an introspecting // client, but this API is not its audience. _logger.LogDebug("Token of {Client} rejected: audience {Audiences} lacks {Resource}", result.ClientId, string.Join(' ', result.Audiences), _settings.ResourceClientId); result = Introspection.Inactive; } return Store(key, result, global, revocationsBefore, result.Active ? result.ExpiresAt : null); } private Introspection Store(string key, Introspection result, long global, long revocationsBefore, DateTimeOffset? expiresAt) { if (Interlocked.Read(ref _revocations) != revocationsBefore) return result; var ttl = result.Active ? _settings.IntrospectionCacheTtl : _settings.InactiveCacheTtl; if (expiresAt is { } exp && exp - DateTimeOffset.UtcNow < ttl) ttl = exp - DateTimeOffset.UtcNow; if (ttl <= TimeSpan.Zero) return result; var entry = new CachedIntrospection(result, global, Generation(result.Subject), Generation(result.UserId)); _cache.Set(key, entry, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl, Size = 1 }); return result; } private bool IsCurrent(CachedIntrospection cached) => cached.GlobalGeneration == Interlocked.Read(ref _globalGeneration) && cached.SubjectGeneration == Generation(cached.Result.Subject) && cached.UserIdGeneration == Generation(cached.Result.UserId); private long Generation(string? userKey) => userKey is not null && _userGenerations.TryGetValue(userKey, out var generation) ? generation : 0; private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); public void Dispose() => _cache.Dispose(); private sealed record CachedIntrospection(Introspection Result, long GlobalGeneration, long SubjectGeneration, long UserIdGeneration); } /// What Identity said about a token (RFC 7662), reduced to what the API uses. public sealed record Introspection( bool Active, string? Subject, string? UserId, string? UserName, string? ClientId, IReadOnlyList Scopes, IReadOnlyList Audiences, string? TokenUsage, DateTimeOffset? ExpiresAt) { public static readonly Introspection Inactive = new(false, null, null, null, null, [], [], null, null); public static Introspection Read(JsonElement json) { if (json.ValueKind != JsonValueKind.Object || !json.TryGetProperty("active", out var active) || active.ValueKind != JsonValueKind.True) return Inactive; return new Introspection( Active: true, Subject: Text(json, "sub"), // The internal user id Identity adds for user tokens; client-credentials tokens have none. UserId: Text(json, "redb:user_id"), UserName: Text(json, "username"), ClientId: Text(json, "client_id"), Scopes: Text(json, "scope")?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? [], Audiences: Strings(json, "aud"), TokenUsage: Text(json, "token_usage"), ExpiresAt: json.TryGetProperty("exp", out var exp) && exp.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null); } private static string? Text(JsonElement json, string name) => json.TryGetProperty(name, out var value) ? value.ValueKind switch { JsonValueKind.String => value.GetString(), JsonValueKind.Number => value.GetRawText(), _ => null, } : null; // "aud" is a string or an array of strings. private static IReadOnlyList Strings(JsonElement json, string name) { if (!json.TryGetProperty(name, out var value)) return []; return value.ValueKind == JsonValueKind.Array ? value.EnumerateArray().Where(v => v.ValueKind == JsonValueKind.String).Select(v => v.GetString()!).ToList() : value.ValueKind == JsonValueKind.String ? [value.GetString()!] : []; } public override string ToString() => Active ? string.Create(CultureInfo.InvariantCulture, $"active sub={Subject} client={ClientId} scope={string.Join(' ', Scopes)}") : "inactive"; } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/InitRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Core; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Extensions; using redb.Route.Core; using redb.Route.Http; using RedbIdentityApp.Module.Controllers; using RedbIdentityApp.Module.Identity; using RedbIdentityApp.Module.Props; namespace RedbIdentityApp.Module; /// /// The module's entry point. The Tsak worker finds it by convention (a public static class /// InitRoute with a main(IRouteContext) method) and awaits it when the module loads, after /// redb.Identity (manifest.json lists it as a dependency). /// /// Order: settings, the services that talk to Identity, the database, the routes; then, once the context /// has started, the setup of the module's clients and scopes at Identity, in the background. /// /// /// Identity runs in the same worker, so every call to it is in process over direct-vm. An application /// that runs elsewhere talks to Identity over HTTP instead (discovery, token, introspection endpoints); /// redb.Identity's demos show that client side. /// /// public static class InitRoute { public static async Task main(IRouteContext context) { var settings = ModuleSettings.FromContext(context); var services = context.GetServiceProvider() ?? throw new InvalidOperationException("The route context has no service provider; redb is not available."); var loggers = services.GetService() ?? NullLoggerFactory.Instance; var logger = loggers.CreateLogger("RedbIdentityApp"); // One HTTP server per port for the whole process; the Tsak worker registers it. if (!context.HasComponent("http")) context.AddComponent(new HttpComponent { ServerManager = services.GetRequiredService() }); // The services that talk to Identity, shared by the routes and the controllers (through the registry). var calls = new IdentityCalls(context, services.GetRequiredService()); var introspector = new TokenIntrospector(calls, settings, loggers.CreateLogger("RedbIdentityApp.Introspection")); var management = new IdentityManagement(calls, settings, loggers.CreateLogger("RedbIdentityApp.Management")); context.AddToRegistry(BearerTokenValidator.RegistryName, new BearerTokenValidator(introspector, loggers.CreateLogger("RedbIdentityApp.Bearer"))); context.AddToRegistry(typeof(ModuleSettings).FullName!, settings); context.AddToRegistry(typeof(IdentityManagement).FullName!, management); // The module's scheme, through a scope of its own: the connection goes back to the pool at once. await using (var scope = services.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService().SyncSchemeAsync(); } var routes = (RouteContext)context; // Revocations reported by Identity's audit (README, "Revocation"). var revocations = new RevocationEvents(introspector, loggers.CreateLogger("RedbIdentityApp.Revocation")); routes.AddRoutes(r => r .From(settings.EventsEndpoint(context)) .RouteId("identity-events") .Process(revocations.Process)); // The API: the bearer check (introspection), the gate (503 when Identity is down, 403 without the // API scope), then every controller of this assembly. The dispatcher matches the method and the path // against the [Route] and [HttpGet] attributes; no match answers 404. var registry = new ControllerRegistry(); registry.RegisterAssembly(typeof(NotesController).Assembly); var gate = new IdentityGate(context.ContextId, settings.ApiScope); routes.AddRoutes(r => r .From($"http:{settings.ApiHost}:{settings.ApiPort}/{{**path}}?inOut=true" + $"&inboundAuth=bearer&tokenValidator=#{BearerTokenValidator.RegistryName}&inboundRealm={context.ContextId}") .RouteId("api") .Process(gate.Process) .RedbHttpController(registry)); context.AddLifecycleListener(new ModuleLifecycle(new IdentitySetup(management, settings, logger), [introspector, calls])); logger.LogInformation("RedbIdentityApp API on {Host}:{Port}; Identity events at {Events}", settings.ApiHost, settings.ApiPort, settings.EventsEndpoint(context)); return context; } /// Starts the Identity setup once the context runs, and stops it with the context. private sealed class ModuleLifecycle(IdentitySetup setup, IDisposable[] owned) : IRouteLifecycleListener { private readonly CancellationTokenSource _stopping = new(); private Task? _setup; public Task OnContextStarted(IRouteContext context, CancellationToken ct) { _setup = Task.Run(() => setup.RunAsync(_stopping.Token)); return Task.CompletedTask; } public async Task OnContextStopping(IRouteContext context, CancellationToken ct) { await _stopping.CancelAsync(); if (_setup is not null) await _setup.ConfigureAwait(false); } public Task OnContextStopped(IRouteContext context, CancellationToken ct) { foreach (var resource in owned) resource.Dispose(); _stopping.Dispose(); return Task.CompletedTask; } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/ModuleSettings.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/ModuleSettings.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RedbIdentityApp.Module; /// /// The module's settings, read from the properties of its route context. The Tsak worker fills them from /// RedbIdentityApp.Module.config.json, then from the Tsak:Contexts:{context}:Override section of /// its configuration, which wins. The three client secrets belong only in the Override layer /// (environment variables, deploy/.env), never in the module's config file. /// public sealed record ModuleSettings( string ApiHost, int ApiPort, string ResourceClientId, string ResourceClientSecret, string ApiScope, string AdminScope, string ManagementClientId, string ManagementClientSecret, string? WebClientId, string? WebClientSecret, IReadOnlyList WebRedirectUris, IReadOnlyList WebPostLogoutRedirectUris, TimeSpan IntrospectionCacheTtl, TimeSpan InactiveCacheTtl, TimeSpan IntrospectionTimeout) { /// The direct-vm address Identity's audit sends its events to; see README, "Revocation". public string EventsEndpoint(IRouteContext context) => $"direct-vm://{context.ContextId}-identity-events"; public static ModuleSettings FromContext(IRouteContext context) { var api = Section(context, context.GetProperty>("Api"), "Api"); var identity = Section(context, context.GetProperty>("Identity"), "Identity"); var introspection = identity.TryGetValue("Introspection", out var raw) && raw is IDictionary section ? section : new Dictionary(); var webClientId = Optional(identity, "WebClientId"); return new( // 127.0.0.1 by default: the web server shares the worker's network namespace. ApiHost: Required(context, api, "Api", "Host"), ApiPort: int.Parse(Required(context, api, "Api", "Port"), CultureInfo.InvariantCulture), ResourceClientId: Required(context, identity, "Identity", "ResourceClientId"), ResourceClientSecret: Secret(context, identity, "ResourceClientSecret"), ApiScope: Required(context, identity, "Identity", "ApiScope"), AdminScope: Required(context, identity, "Identity", "AdminScope"), ManagementClientId: Required(context, identity, "Identity", "ManagementClientId"), ManagementClientSecret: Secret(context, identity, "ManagementClientSecret"), WebClientId: webClientId, WebClientSecret: webClientId is null ? null : Secret(context, identity, "WebClientSecret"), WebRedirectUris: List(identity, "WebRedirectUris"), WebPostLogoutRedirectUris: List(identity, "WebPostLogoutRedirectUris"), IntrospectionCacheTtl: Seconds(introspection, "CacheSeconds", 60), InactiveCacheTtl: Seconds(introspection, "InactiveCacheSeconds", 10), IntrospectionTimeout: Seconds(introspection, "TimeoutSeconds", 5)); } private static IDictionary Section(IRouteContext context, IDictionary? section, string name) => section ?? throw new InvalidOperationException( $"{name} is not configured for context '{context.ContextId}': see RedbIdentityApp.Module.config.json."); private static string? Optional(IDictionary section, string key) => section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text ? text.Trim() : null; private static string Required(IRouteContext context, IDictionary section, string sectionName, string key) => Optional(section, key) ?? throw new InvalidOperationException( $"{sectionName}:{key} is not configured for context '{context.ContextId}': set it in " + $"RedbIdentityApp.Module.config.json or in Tsak:Contexts:{context.ContextId}:Override."); // A client secret: only from the environment, and long enough not to be guessed. private static string Secret(IRouteContext context, IDictionary section, string key) { var value = Optional(section, key) ?? throw new InvalidOperationException( $"Identity:{key} is not set for context '{context.ContextId}': set " + $"Tsak__Contexts__{context.ContextId}__Override__Identity__{key} in the worker's environment."); return value.Length >= 32 ? value : throw new InvalidOperationException($"Identity:{key} of context '{context.ContextId}' must be at least 32 characters."); } // A list is written as one string, items separated by commas or spaces: the same text works in the // config file and in one environment variable. private static IReadOnlyList List(IDictionary section, string key) => Optional(section, key)?.Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? []; private static TimeSpan Seconds(IDictionary section, string key, int fallback) => TimeSpan.FromSeconds(Optional(section, key) is { } text ? int.Parse(text, CultureInfo.InvariantCulture) : fallback); } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Props/Note.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/Props/Note.cs ---- using redb.Core.Attributes; namespace RedbIdentityApp.Module.Props; /// /// A note of a user, stored in the worker's default redb. The title is the object's name; the owner is /// the token's subject, so each user sees only their own notes. /// [RedbScheme("redbidentityapp.note")] public class Note { public string Owner { get; set; } = ""; public string? Text { get; set; } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/RedbIdentityApp.Module.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/RedbIdentityApp.Module.config.json ---- { "ContextName": "redbidentityapp", "AutoStart": true, "Api": { // 127.0.0.1: the web server shares the worker's network namespace (deploy/docker-compose.yml), so // the API needs no published port. "Host": "127.0.0.1", "Port": 5094 }, "Identity": { // The module's own client at Identity: a resource server that may introspect the access tokens // issued for its API. Its secret comes from the environment: // Tsak__Contexts__redbidentityapp__Override__Identity__ResourceClientSecret. "ResourceClientId": "redbidentityapp-api", // The scope a client requests to call the API. Its Resources name the resource client above, so a // token issued with it carries that client in "aud", and only then may the module introspect it. "ApiScope": "redbidentityapp.api", // The scope of the administrative endpoints. Identity issues it only to users whose role carries // it: the module attaches it to the "admin" role, and Identity must list it in // AdminScopeEntitlement:GatedScopes (deploy/docker-compose.yml). "AdminScope": "redbidentityapp.admin", // The service client the module sets things up with and reads the management API with: Identity's // SeedBackchannelClient, which holds identity:manage. Secret: // Tsak__Contexts__redbidentityapp__Override__Identity__ManagementClientSecret. "ManagementClientId": "identity-backchannel", //#if (web) // The web server's client (code flow with PKCE, refresh tokens). The module creates it and keeps its // redirect addresses as listed here. Secret: // Tsak__Contexts__redbidentityapp__Override__Identity__WebClientSecret. "WebClientId": "redbidentityapp-web", "WebRedirectUris": "http://localhost:5085/signin-oidc", "WebPostLogoutRedirectUris": "http://localhost:5085/signout-callback-oidc", //#endif "Introspection": { // How long an introspection answer is reused. Never past the token's own expiry; a revocation // that Identity reports (see README, "Revocation") drops it at once. "CacheSeconds": 60, // How long a token Identity called inactive is answered 401 without asking again. "InactiveCacheSeconds": 10, // How long the module waits for Identity before it answers 503. "TimeoutSeconds": 5 } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/RedbIdentityApp.Module.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/RedbIdentityApp.Module.csproj ---- Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/manifest.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Module/manifest.json ---- { "Name": "RedbIdentityApp", "Version": "1.0.0", "EntryPoints": ["RedbIdentityApp.Module.dll"], "Dependencies": ["redb.Identity.Core.Module"] } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/AccessTokens.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/AccessTokens.cs ---- using System.Collections.Concurrent; using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace RedbIdentityApp.Web.Auth; /// /// A valid access token for the user's session, refreshed shortly before it expires. /// /// Identity refuses the refresh (invalid_grant: the session was revoked, the user disabled, /// the refresh token expired): the session is over, . /// Identity cannot be reached: while the current access token is still valid it is used; after /// that . A network error never ends a session. /// /// One refresh per session at a time: Identity rotates refresh tokens, and two parallel refreshes with /// the same one would race. The lock is per process; with several replicas, keep a user on one of them /// or accept that the slower refresh is refused and the user signs in again. /// public sealed class AccessTokens( UserTokenStore store, IHttpClientFactory httpClients, IOptionsMonitor oidc, IOptions identity, ILogger logger) { /// The name of the HttpClient that talks to Identity (Program.cs). public const string HttpClientName = "identity"; private static readonly TimeSpan RefreshBefore = TimeSpan.FromSeconds(60); private readonly ConcurrentDictionary _locks = new(StringComparer.Ordinal); public async Task GetAsync(string sessionKey, CancellationToken ct) { var tokens = await store.GetAsync(sessionKey, ct) ?? throw new SessionEndedException(); if (tokens.ExpiresAt - DateTimeOffset.UtcNow > RefreshBefore) return tokens.AccessToken; var gate = _locks.GetOrAdd(sessionKey, _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(ct); try { // Another request may have refreshed while this one waited. tokens = await store.GetAsync(sessionKey, ct) ?? throw new SessionEndedException(); if (tokens.ExpiresAt - DateTimeOffset.UtcNow > RefreshBefore) return tokens.AccessToken; if (tokens.RefreshToken is null) return StillValid(tokens) ?? throw new SessionEndedException(); var refreshed = await RefreshAsync(sessionKey, tokens, ct); return refreshed?.AccessToken ?? StillValid(tokens) ?? throw new IdentityUnavailableException(); } finally { gate.Release(); } } /// Ends the session here and at Identity: the refresh token is revoked (RFC 7009). public async Task EndSessionAsync(string sessionKey, CancellationToken ct) { var tokens = await store.GetAsync(sessionKey, ct); await store.RemoveAsync(sessionKey, ct); _locks.TryRemove(sessionKey, out _); if (tokens?.RefreshToken is { } refreshToken) { try { var configuration = await ConfigurationAsync(ct); if (configuration.AdditionalData.TryGetValue("revocation_endpoint", out var endpoint) && endpoint is string url) { using var response = await PostAsync(url, new Dictionary { ["token"] = refreshToken, ["token_type_hint"] = "refresh_token", }, ct); if (!response.IsSuccessStatusCode) logger.LogWarning("Identity answered {Status} to the revocation of a refresh token", (int)response.StatusCode); } } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException) { // The session is over here anyway; the refresh token expires at Identity on its own. logger.LogWarning(ex, "The refresh token could not be revoked at Identity"); } } return tokens?.IdToken; } private async Task RefreshAsync(string sessionKey, UserTokens tokens, CancellationToken ct) { HttpResponseMessage response; try { var configuration = await ConfigurationAsync(ct); response = await PostAsync(configuration.TokenEndpoint, new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = tokens.RefreshToken!, }, ct); } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException) { logger.LogWarning(ex, "Token refresh failed: Identity is not reachable"); return null; } using (response) { var body = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode) { using var json = JsonDocument.Parse(body); var root = json.RootElement; var refreshed = new UserTokens( AccessToken: root.GetProperty("access_token").GetString()!, // Identity rotates refresh tokens; keep the old one only if no new one came. RefreshToken: root.TryGetProperty("refresh_token", out var rt) ? rt.GetString() : tokens.RefreshToken, IdToken: root.TryGetProperty("id_token", out var it) ? it.GetString() : tokens.IdToken, ExpiresAt: DateTimeOffset.UtcNow.AddSeconds(root.TryGetProperty("expires_in", out var e) && e.TryGetInt32(out var s) ? s : 300), Scopes: root.TryGetProperty("scope", out var sc) ? sc.GetString()!.Split(' ', StringSplitOptions.RemoveEmptyEntries) : tokens.Scopes); await store.SaveAsync(sessionKey, refreshed, ct); return refreshed; } // 400 with an OAuth error is Identity's answer about the grant; anything else is Identity unwell. if (response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized && OAuthError(body) is { } error) { logger.LogInformation("Identity refused the refresh ({Error}): the session is over", error); await store.RemoveAsync(sessionKey, ct); throw new SessionEndedException(); } logger.LogWarning("Token refresh failed: Identity answered {Status}", (int)response.StatusCode); return null; } } private async Task PostAsync(string url, Dictionary form, CancellationToken ct) { var options = identity.Value; form["client_id"] = options.ClientId; form["client_secret"] = options.ClientSecret; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(10)); return await httpClients.CreateClient(HttpClientName).PostAsync(url, new FormUrlEncodedContent(form), timeout.Token); } private Task ConfigurationAsync(CancellationToken ct) => oidc.Get(OpenIdConnectDefaults.AuthenticationScheme).ConfigurationManager?.GetConfigurationAsync(ct) ?? throw new InvalidOperationException("The OpenID Connect handler has no configuration manager yet."); // The "error" of an OAuth error answer (RFC 6749 §5.2), or null when the body is not one. private static string? OAuthError(string body) { try { using var json = JsonDocument.Parse(body); return json.RootElement.ValueKind == JsonValueKind.Object && json.RootElement.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String ? error.GetString() : null; } catch (JsonException) { return null; } } private static string? StillValid(UserTokens tokens) => tokens.ExpiresAt > DateTimeOffset.UtcNow ? tokens.AccessToken : null; } /// The user's session is over (revoked, expired, or never stored): sign in again. public sealed class SessionEndedException() : Exception("Your session has ended. Sign in again."); /// Identity cannot be reached and the access token has expired: try again shortly. public sealed class IdentityUnavailableException() : Exception("The sign-in service is not available. Try again shortly."); Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/UserTokenStore.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/UserTokenStore.cs ---- using System.Security.Cryptography; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Caching.Distributed; namespace RedbIdentityApp.Web.Auth; /// /// The user's tokens, kept on this server: the session cookie carries only a random session key. A /// token never reaches the browser, and the cookie stays small whatever the tokens weigh. /// /// Storage is , encrypted with DataProtection. Program.cs registers the /// in-memory cache: one server, and a restart signs users out of this application (Identity's own /// session signs them back in without a password). For several replicas register a shared cache /// (Redis: AddStackExchangeRedisCache) and a shared DataProtection key ring. /// /// public sealed class UserTokenStore(IDistributedCache cache, IDataProtectionProvider protection) { /// The cookie claim that holds the session key. public const string SessionClaim = "redbidentityapp:session"; private readonly IDataProtector _protector = protection.CreateProtector("RedbIdentityApp.UserTokens"); /// How long a session outlives its last use; the cookie uses the same. public static readonly TimeSpan SessionLifetime = TimeSpan.FromHours(8); public async Task CreateAsync(UserTokens tokens, CancellationToken ct) { var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); await SaveAsync(key, tokens, ct); return key; } public async Task GetAsync(string key, CancellationToken ct) { var protectedBytes = await cache.GetAsync(CacheKey(key), ct); if (protectedBytes is null) return null; try { return JsonSerializer.Deserialize(_protector.Unprotect(protectedBytes)); } catch (CryptographicException) { // Keys changed (a new DataProtection ring): the entry is unreadable, the session is over. await RemoveAsync(key, ct); return null; } } public Task SaveAsync(string key, UserTokens tokens, CancellationToken ct) => cache.SetAsync(CacheKey(key), _protector.Protect(JsonSerializer.SerializeToUtf8Bytes(tokens)), new DistributedCacheEntryOptions { SlidingExpiration = SessionLifetime }, ct); public Task RemoveAsync(string key, CancellationToken ct) => cache.RemoveAsync(CacheKey(key), ct); private static string CacheKey(string key) => "redbidentityapp:tokens:" + key; } /// What the token endpoint gave the user's session. public sealed record UserTokens( string AccessToken, string? RefreshToken, string? IdToken, DateTimeOffset ExpiresAt, string[] Scopes); Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/WebIdentityOptions.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Auth/WebIdentityOptions.cs ---- namespace RedbIdentityApp.Web.Auth; /// The Identity section of appsettings.json: where users sign in, and as which client. public sealed class WebIdentityOptions { /// Identity's issuer, an https address. The browser and this server both reach it there. public string Authority { get; set; } = ""; /// This server's client; the module creates it at Identity (Identity:WebClientId of the module). public string ClientId { get; set; } = ""; /// The client's secret, the same value as the module's Identity:WebClientSecret. Environment only. public string ClientSecret { get; set; } = ""; /// The scope that lets the access token call the module's API. public string ApiScope { get; set; } = ""; /// The administrative scope; Identity grants it to administrators only and drops it for others. public string AdminScope { get; set; } = ""; /// /// Development only: accept any certificate from Identity, for the self-signed one of the /// redb-identity-full image on your machine. Refused outside the Development environment; a container /// trusts that certificate through its CA store instead (Dockerfile). /// public bool AcceptAnyServerCertificate { get; set; } public void Validate(IHostEnvironment environment) { if (!Uri.TryCreate(Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps) throw new InvalidOperationException("Identity:Authority must be the https address of redb.Identity."); if (string.IsNullOrWhiteSpace(ClientId) || string.IsNullOrWhiteSpace(ApiScope) || string.IsNullOrWhiteSpace(AdminScope)) throw new InvalidOperationException("Identity:ClientId, Identity:ApiScope and Identity:AdminScope are required."); if (ClientSecret.Length < 32) throw new InvalidOperationException("Identity:ClientSecret is missing or shorter than 32 characters: set Identity__ClientSecret."); if (AcceptAnyServerCertificate && !environment.IsDevelopment()) throw new InvalidOperationException("Identity:AcceptAnyServerCertificate is for the Development environment only."); } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/App.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/App.razor ---- @* Sign-in and sign-out are plain endpoints (Program.cs), so every page can be interactive. *@ Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Layout/MainLayout.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Layout/MainLayout.razor ---- @inherits LayoutComponentBase
RedbIdentityApp Notes Me Users @context.User.Identity?.Name @* A plain POST: sign-out clears the cookie and goes to Identity, which only a plain request can do. *@
Sign in
@Body
Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/ModuleError.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/ModuleError.razor ---- @inject NavigationManager Navigation @* What a failed module call means for the user. *@ @switch (Error) { case null: break; case SessionEndedException:

Your session has ended. Sign in again

break; case IdentityUnavailableException:

The sign-in service is not available right now. Try again in a few seconds.

break; case ModuleException { Forbidden: true } forbidden:

Not allowed: @forbidden.Message

break; default:

@Error.Message

break; } @code { [Parameter] public Exception? Error { get; set; } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/AdminUsers.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/AdminUsers.razor ---- @page "/admin/users" @attribute [Authorize(Policy = "admin")] @inject ModuleClient Module Users

Users

Read by the module from Identity's management API, in process.

@data.Total user(s)

@foreach (var user in data.Items) { }
IdLoginNameE-mailEnabled
@user.Id @user.Login @user.Name @user.Email @(user.Enabled ? "yes" : "no")
@code { private const int PageSize = 20; private Page data = new(); private int current = 1; private Exception? error; protected override Task OnInitializedAsync() => LoadAsync(1); private async Task LoadAsync(int number) { error = null; try { data = await Module.UsersAsync(number); current = number; } catch (Exception ex) when (ex is SessionEndedException or IdentityUnavailableException or ModuleException) { error = ex; } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Error.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Error.razor ---- @page "/Error" Error

Something went wrong

The request could not be completed. Check the application log for details.

Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Home.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Home.razor ---- @page "/" RedbIdentityApp

RedbIdentityApp

An application on redb.Identity. You sign in at Identity; this server keeps your session and calls the application's module with your access token. The module checks every token with Identity.

Signed in as @context.User.Identity?.Name. Open your notes.

Sign in to see your notes.

Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Me.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Me.razor ---- @page "/me" @attribute [Authorize] @inject ModuleClient Module Me

Who the module sees

@if (me is not null) {
Subject@me.Subject
User id@me.UserId
User name@me.UserName
Client@me.ClientId
Scopes@string.Join(" ", me.Scopes)
Token expires@me.ExpiresAt?.ToLocalTime().ToString("u")
} @code { private MeDto? me; private Exception? error; protected override async Task OnInitializedAsync() { try { me = await Module.MeAsync(); } catch (Exception ex) when (ex is SessionEndedException or IdentityUnavailableException or ModuleException) { error = ex; } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Notes.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Pages/Notes.razor ---- @page "/notes" @attribute [Authorize] @inject ModuleClient Module Notes

My notes

@foreach (var note in notes) { }
TitleTextCreated
@note.Title @note.Text @note.CreatedAt.ToLocalTime().ToString("g")
@code { private List notes = []; private NoteDto draft = new(); private Exception? error; protected override Task OnInitializedAsync() => RunAsync(LoadAsync); private Task AddAsync() => RunAsync(async () => { await Module.AddNoteAsync(draft); draft = new(); await LoadAsync(); }); private Task DeleteAsync(long id) => RunAsync(async () => { await Module.DeleteNoteAsync(id); await LoadAsync(); }); private async Task LoadAsync() => notes = await Module.NotesAsync(); private async Task RunAsync(Func call) { error = null; try { await call(); } catch (Exception ex) when (ex is SessionEndedException or IdentityUnavailableException or ModuleException) { error = ex; } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/RedirectToLogin.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/RedirectToLogin.razor ---- @inject NavigationManager Navigation @code { // A full page load: the sign-in endpoint redirects to Identity. protected override void OnInitialized() => Navigation.NavigateTo($"account/login?returnUrl={Uri.EscapeDataString("/" + Navigation.ToBaseRelativePath(Navigation.Uri))}", forceLoad: true); } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Routes.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/Routes.razor ---- @* Checks the page's [Authorize]; a user without a session goes to Identity to sign in. *@ @if (context.User.Identity?.IsAuthenticated == true) {

Not allowed

Your account does not have access to this page.

} else { }
Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/_Imports.razor Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Components/_Imports.razor ---- @using System.ComponentModel.DataAnnotations @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @using static Microsoft.AspNetCore.Components.Web.RenderMode @using RedbIdentityApp.Contracts @using RedbIdentityApp.Web @using RedbIdentityApp.Web.Auth @using RedbIdentityApp.Web.Components @using RedbIdentityApp.Web.Services Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Dockerfile ---- # The web server. Build from the solution folder: # docker build -f RedbIdentityApp.Web/Dockerfile -t redbidentityapp-web . ARG DOTNET_VERSION=10.0 # The Identity image of the same release: the web server trusts its development certificate. ARG IDENTITY_IMAGE=ghcr.io/redbase-app/redb-identity-full:4.8.0 FROM ${IDENTITY_IMAGE} AS identity FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build WORKDIR /src COPY Directory.Build.props . COPY RedbIdentityApp.Contracts/RedbIdentityApp.Contracts.csproj RedbIdentityApp.Contracts/ COPY RedbIdentityApp.Web/RedbIdentityApp.Web.csproj RedbIdentityApp.Web/ RUN dotnet restore RedbIdentityApp.Web/RedbIdentityApp.Web.csproj COPY . . RUN dotnet publish RedbIdentityApp.Web/RedbIdentityApp.Web.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} WORKDIR /app # Identity's self-signed development certificate, trusted through the CA store: the certificate is # checked as any other, nothing is switched off. With a real certificate on Identity, delete these two # lines and the identity stage above. COPY --from=identity /usr/local/share/ca-certificates/redb-identity-dev.crt /usr/local/share/ca-certificates/ RUN update-ca-certificates COPY --from=build /app . # The DataProtection key ring goes to a volume. The app runs as the non-root user of the .NET image, # which must be able to write there. RUN mkdir /keys && chown $APP_UID /keys USER $APP_UID ENV ASPNETCORE_URLS=http://+:5085 ENV Web__DataProtectionKeysPath=/keys VOLUME /keys EXPOSE 5085 ENTRYPOINT ["dotnet", "RedbIdentityApp.Web.dll"] Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Program.cs ---- using System.Security.Claims; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.DataProtection; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using RedbIdentityApp.Web.Auth; using RedbIdentityApp.Web.Components; using RedbIdentityApp.Web.Services; var builder = WebApplication.CreateBuilder(args); var identity = builder.Configuration.GetSection("Identity").Get() ?? throw new InvalidOperationException("The Identity section is missing in appsettings.json."); identity.Validate(builder.Environment); builder.Services.Configure(builder.Configuration.GetSection("Identity")); // --- DataProtection: the session cookie and the stored tokens are encrypted with it --- // A key ring in a directory survives a restart; in a container the directory is a volume (deploy/). var dataProtection = builder.Services.AddDataProtection().SetApplicationName("RedbIdentityApp"); if (builder.Configuration["Web:DataProtectionKeysPath"] is { Length: > 0 } keysPath) dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath)); // --- The tokens stay on this server (Auth/UserTokenStore.cs) --- builder.Services.AddDistributedMemoryCache(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); // The HttpClient that talks to Identity: the OpenID Connect handler (metadata, code exchange, user info) // and AccessTokens (refresh, revocation). Identity's certificate is checked like any other; only the // Development flag accepts the self-signed one of a local image. builder.Services.AddHttpClient(AccessTokens.HttpClientName) .ConfigurePrimaryHttpMessageHandler(() => identity.AcceptAnyServerCertificate ? new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator } : new HttpClientHandler()); // --- Sign-in: OpenID Connect at redb.Identity, then this server's session cookie --- builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie(options => { options.Cookie.Name = "RedbIdentityApp"; options.Cookie.HttpOnly = true; // Lax, not Strict: the browser comes back from Identity with a top-level redirect. options.Cookie.SameSite = SameSiteMode.Lax; // Secure when the request is HTTPS. Behind a TLS-terminating proxy, add UseForwardedHeaders so the // request scheme is the real one. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = UserTokenStore.SessionLifetime; options.SlidingExpiration = true; options.LoginPath = "/account/login"; options.AccessDeniedPath = "/"; // A cookie whose tokens are gone (a restart with the in-memory store, a revoked session) is no // session: the user goes through Identity again, usually without a password. options.Events.OnValidatePrincipal = async context => { var key = context.Principal?.FindFirst(UserTokenStore.SessionClaim)?.Value; var store = context.HttpContext.RequestServices.GetRequiredService(); if (key is null || await store.GetAsync(key, context.HttpContext.RequestAborted) is null) { context.RejectPrincipal(); await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } }; }) .AddOpenIdConnect(options => { options.Authority = identity.Authority; options.ClientId = identity.ClientId; options.ClientSecret = identity.ClientSecret; options.RequireHttpsMetadata = true; // Authorization code with PKCE. The answer comes back in the query of a top-level GET, so the // correlation and nonce cookies can be SameSite=Lax and also work over plain http on localhost. options.ResponseType = OpenIdConnectResponseType.Code; options.UsePkce = true; options.ResponseMode = OpenIdConnectResponseMode.Query; options.CorrelationCookie.SameSite = SameSiteMode.Lax; options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.NonceCookie.SameSite = SameSiteMode.Lax; options.NonceCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.Scope.Clear(); foreach (var scope in new[] { "openid", "profile", "email", "offline_access", identity.ApiScope, identity.AdminScope }) options.Scope.Add(scope); // The tokens go to UserTokenStore, not into the cookie. options.SaveTokens = false; options.GetClaimsFromUserInfoEndpoint = true; options.MapInboundClaims = false; options.TokenValidationParameters.NameClaimType = "name"; options.TokenValidationParameters.RoleClaimType = "roles"; options.SignedOutCallbackPath = "/signout-callback-oidc"; options.Events.OnTokenValidated = async context => { var response = context.TokenEndpointResponse ?? throw new InvalidOperationException("Identity's token endpoint gave no answer."); var tokens = new UserTokens( AccessToken: response.AccessToken, RefreshToken: response.RefreshToken, IdToken: response.IdToken, ExpiresAt: DateTimeOffset.UtcNow.AddSeconds(int.TryParse(response.ExpiresIn, out var seconds) ? seconds : 300), Scopes: response.Scope?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []); var store = context.HttpContext.RequestServices.GetRequiredService(); var key = await store.CreateAsync(tokens, context.HttpContext.RequestAborted); // The cookie gets the session key and the granted scopes (to show or hide pages); the module // checks the token itself on every call, whatever the page shows. var user = (ClaimsIdentity)context.Principal!.Identity!; user.AddClaim(new Claim(UserTokenStore.SessionClaim, key)); foreach (var scope in tokens.Scopes) user.AddClaim(new Claim("scope", scope)); }; // Sign-out at Identity names the session that ends (OIDC RP-Initiated Logout). options.Events.OnRedirectToIdentityProviderForSignOut = context => { if (context.HttpContext.Items["id_token_hint"] is string idToken) context.ProtocolMessage.IdTokenHint = idToken; return Task.CompletedTask; }; }); // The handler's backchannel goes through the same HttpClient as the refresh. builder.Services.AddOptions(OpenIdConnectDefaults.AuthenticationScheme) .Configure((options, clients) => options.Backchannel = clients.CreateClient(AccessTokens.HttpClientName)); builder.Services.AddAuthorizationBuilder() // Only a page decision: the module refuses an administrative call without the scope on its own. .AddPolicy("admin", policy => policy.RequireClaim("scope", identity.AdminScope)); builder.Services.AddCascadingAuthenticationState(); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // --- The module's API --- var moduleUrl = builder.Configuration["Module:BaseUrl"] ?? throw new InvalidOperationException("Module:BaseUrl is missing in appsettings.json."); builder.Services.AddHttpClient(http => http.BaseAddress = new Uri(moduleUrl)); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); } app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); // UseStaticFiles rather than MapStaticAssets: the same code for .NET 10 and 11. app.UseStaticFiles(); // --- Sign-in and sign-out --- // Both are plain requests: a challenge redirects and a sign-out clears the cookie, which an interactive // circuit cannot do once its response has started. app.MapGet("/account/login", (string? returnUrl) => Results.Challenge(new AuthenticationProperties { RedirectUri = LocalPath(returnUrl) }, [OpenIdConnectDefaults.AuthenticationScheme])); app.MapPost("/account/logout", async (HttpContext http, IAntiforgery antiforgery, AccessTokens tokens) => { // The sign-out form carries an antiforgery token: another site cannot sign the user out. if (!await antiforgery.IsRequestValidAsync(http)) { http.Response.Redirect("/"); return; } if (http.User.FindFirst(UserTokenStore.SessionClaim)?.Value is { } key) http.Items["id_token_hint"] = await tokens.EndSessionAsync(key, http.RequestAborted); await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await http.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" }); }).DisableAntiforgery(); // checked above, so a stale form goes home instead of failing app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run(); // Only ever a local path, never an address from the query. static string LocalPath(string? returnUrl) => returnUrl is { Length: > 0 } && returnUrl.StartsWith('/') && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\") ? returnUrl : "/"; Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Properties/launchSettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Properties/launchSettings.json ---- { "profiles": { "RedbIdentityApp.Web": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "http://localhost:5085", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/RedbIdentityApp.Web.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/RedbIdentityApp.Web.csproj ---- $(WebTargetFramework) Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Services/ModuleClient.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/Services/ModuleClient.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using Microsoft.AspNetCore.Components.Authorization; using RedbIdentityApp.Contracts; using RedbIdentityApp.Web.Auth; namespace RedbIdentityApp.Web.Services; /// /// The module's API, called with the signed-in user's access token. The HttpClient comes configured from /// Program.cs (the module's address). What the module answers becomes something a page can show: /// /// 401: the token is no longer good (revoked at Identity): the session ends, /// ; /// 403: the user lacks the right (); /// 503: Identity is down (). /// /// The user is taken from the circuit's authentication state, which the client follows through /// from its creation until the circuit's scope /// disposes it, so a call never goes out with a state that has changed since. /// public sealed class ModuleClient : IDisposable { private readonly HttpClient http; private readonly AuthenticationStateProvider authentication; private readonly AccessTokens tokens; private readonly UserTokenStore store; private Task? state; public ModuleClient(HttpClient http, AuthenticationStateProvider authentication, AccessTokens tokens, UserTokenStore store) { this.http = http; this.authentication = authentication; this.tokens = tokens; this.store = store; authentication.AuthenticationStateChanged += OnAuthenticationStateChanged; } public void Dispose() => authentication.AuthenticationStateChanged -= OnAuthenticationStateChanged; private void OnAuthenticationStateChanged(Task changed) => state = changed; public Task MeAsync() => SendAsync(HttpMethod.Get, "api/me", null); public Task> NotesAsync() => SendAsync>(HttpMethod.Get, "api/notes", null); public Task AddNoteAsync(NoteDto note) => SendAsync(HttpMethod.Post, "api/notes", note); public Task DeleteNoteAsync(long id) => SendAsync(HttpMethod.Delete, $"api/notes/{id}", null); public Task> UsersAsync(int page) => SendAsync>(HttpMethod.Get, $"api/admin/users?page={page}", null); private async Task SendAsync(HttpMethod method, string uri, object? body) { var sessionKey = (await (state ??= authentication.GetAuthenticationStateAsync())).User.FindFirst(UserTokenStore.SessionClaim)?.Value ?? throw new SessionEndedException(); var accessToken = await tokens.GetAsync(sessionKey, CancellationToken.None); using var request = new HttpRequestMessage(method, uri); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); if (body is not null) request.Content = JsonContent.Create(body, body.GetType()); using var response = await http.SendAsync(request); switch (response.StatusCode) { case HttpStatusCode.Unauthorized: await store.RemoveAsync(sessionKey, CancellationToken.None); throw new SessionEndedException(); case HttpStatusCode.ServiceUnavailable: throw new IdentityUnavailableException(); case HttpStatusCode.NoContent: return default!; } if (response.IsSuccessStatusCode) return (await response.Content.ReadFromJsonAsync())!; var error = response.Content.Headers.ContentType?.MediaType == "application/json" ? await response.Content.ReadFromJsonAsync() : null; throw new ModuleException( error?.Message ?? $"The module answered {(int)response.StatusCode} {response.ReasonPhrase}.", response.StatusCode == HttpStatusCode.Forbidden); } } /// A module call that did not succeed; the message is meant for the user. public sealed class ModuleException(string message, bool forbidden) : Exception(message) { public bool Forbidden { get; } = forbidden; } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/appsettings.Development.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/appsettings.Development.json ---- { "Identity": { // For your machine only, the same value as WEB_CLIENT_SECRET in deploy/.env.example. Everywhere else the // secret comes from the environment (Identity__ClientSecret) and this file is not deployed. "ClientSecret": "local-development-web-client-secret-change-me", // The redb-identity-full image serves a self-signed certificate for localhost. On your machine this // server accepts it; in any other environment the setting is refused at start (Auth/WebIdentityOptions.cs). "AcceptAnyServerCertificate": true } } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/appsettings.json ---- { "Identity": { // redb.Identity's issuer: the redb-identity-full image of deploy/docker-compose.yml answers here. "Authority": "https://localhost:5002", // This server's client and the module's scopes: the same names as in // RedbIdentityApp.Module/RedbIdentityApp.Module.config.json, where the module creates them at Identity. "ClientId": "redbidentityapp-web", "ApiScope": "redbidentityapp.api", "AdminScope": "redbidentityapp.admin" // ClientSecret: never here. Identity__ClientSecret in the environment, the same value as // WEB_CLIENT_SECRET in deploy/.env. }, "Module": { // The module's API inside the Tsak worker. "BaseUrl": "http://127.0.0.1:5094/" }, "Web": { // Where the DataProtection key ring is kept; empty: the default folder of the user. A container sets // a volume here (deploy/docker-compose.yml). "DataProtectionKeysPath": "" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/wwwroot/app.css Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.Web/wwwroot/app.css ---- body { font-family: system-ui, sans-serif; margin: 0; color: #1f2328; background: #fff; } header { display: flex; gap: 1.5rem; align-items: center; padding: 0.75rem 1.5rem; border-bottom: 1px solid #d0d7de; } header .brand { font-weight: 600; color: #b3261e; text-decoration: none; } main { max-width: 960px; margin: 0 auto; padding: 1rem 1.5rem; } a { color: #0969da; } .filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 0.5rem; } .muted { color: #656d76; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #d0d7de; } .num { text-align: right; } .pager { display: flex; gap: 0.5rem; margin-top: 1rem; } .pager span { font-weight: 600; } .form { display: grid; gap: 0.35rem; max-width: 480px; } .form input:not([type=checkbox]), .form textarea { padding: 0.35rem; font: inherit; } .form .actions { display: flex; gap: 1rem; align-items: center; margin-top: 0.75rem; } .field-validation-error, .validation-summary-errors { color: #b3261e; } button.link { background: none; border: 0; padding: 0; color: #b3261e; cursor: pointer; font: inherit; } header a.active { font-weight: 600; } .pager button { font: inherit; } .tree { list-style: none; padding-left: 1.25rem; } .tree li { margin: 0.25rem 0; } .tree button.link { margin-left: 0.5rem; } .inline { display: inline-flex; gap: 0.4rem; margin-left: 0.5rem; } header .who { margin-left: auto; color: #656d76; } .error { color: #b3261e; } header form { display: inline; } Path: redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.slnx Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/RedbIdentityApp.slnx ---- Path: redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.mssql.yml ---- # SQL Server instead of SQLite, on top of docker-compose.yml. RedBase creates its tables but not the # database: create it once, then start everything. From the project folder: # docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_identity_app" # docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.mssql.yml up -d --build # # One database for Identity and the module; every Identity context gets the override, as in # docker-compose.postgres.yml. x-identity-mssql: &identity-mssql "Server=db,1433;Database=redb_identity_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" services: db: image: mcr.microsoft.com/mssql/server:2022-latest restart: unless-stopped environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql identity: depends_on: - db environment: # The image runs the worker in cluster mode; with a database server the Quartz job store is shared # and must be clustered too, even for one node. Quartz__quartz.jobStore.clustered: "true" # The worker's default redb: the module's notes. Tsak__Redb__Provider: mssql ConnectionStrings__MSSql: *identity-mssql # Every Identity context on the same store. Tsak__Contexts__identity.contracts__Override__RedbInstanceName: identity-mssql Tsak__Contexts__identity.contracts__Override__Redb__identity-mssql__ConnectionString: *identity-mssql Tsak__Contexts__identity.core__Override__RedbInstanceName: identity-mssql Tsak__Contexts__identity.core__Override__Identity__RedbInstanceName: identity-mssql Tsak__Contexts__identity.core__Override__Redb__identity-mssql__ConnectionString: *identity-mssql Tsak__Contexts__identity.http__Override__RedbInstanceName: identity-mssql Tsak__Contexts__identity.http__Override__Redb__identity-mssql__ConnectionString: *identity-mssql Tsak__Contexts__identity.grpc__Override__RedbInstanceName: identity-mssql Tsak__Contexts__identity.grpc__Override__Redb__identity-mssql__ConnectionString: *identity-mssql Tsak__Contexts__identity.soap__Override__RedbInstanceName: identity-mssql Tsak__Contexts__identity.soap__Override__Redb__identity-mssql__ConnectionString: *identity-mssql volumes: mssqldata: Path: redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.postgres.yml ---- # PostgreSQL instead of SQLite, on top of docker-compose.yml. From the project folder: # docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.postgres.yml up -d --build # # One database for Identity and the module. Identity is several Tsak contexts, and each one opens its # own redb instance: all of them have to point at the same store (the DataProtection key ring lives # there), so every context gets the override, the ones that do not start included. The module works in # the worker's default redb (Tsak__Redb__*). x-identity-pg: &identity-pg "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_identity_app;Pooling=true" services: db: image: postgres:17 restart: unless-stopped environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_identity_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_identity_app"] interval: 5s retries: 10 identity: depends_on: db: condition: service_healthy environment: # The image runs the worker in cluster mode; with a database server the Quartz job store is shared # and must be clustered too, even for one node. Quartz__quartz.jobStore.clustered: "true" # The worker's default redb: the module's notes. Tsak__Redb__Provider: postgres ConnectionStrings__Postgres: *identity-pg # Every Identity context on the same store. Tsak__Contexts__identity.contracts__Override__RedbInstanceName: identity-pg Tsak__Contexts__identity.contracts__Override__Redb__identity-pg__ConnectionString: *identity-pg Tsak__Contexts__identity.core__Override__RedbInstanceName: identity-pg Tsak__Contexts__identity.core__Override__Identity__RedbInstanceName: identity-pg Tsak__Contexts__identity.core__Override__Redb__identity-pg__ConnectionString: *identity-pg Tsak__Contexts__identity.http__Override__RedbInstanceName: identity-pg Tsak__Contexts__identity.http__Override__Redb__identity-pg__ConnectionString: *identity-pg Tsak__Contexts__identity.grpc__Override__RedbInstanceName: identity-pg Tsak__Contexts__identity.grpc__Override__Redb__identity-pg__ConnectionString: *identity-pg Tsak__Contexts__identity.soap__Override__RedbInstanceName: identity-pg Tsak__Contexts__identity.soap__Override__Redb__identity-pg__ConnectionString: *identity-pg volumes: pgdata: Path: redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/deploy/docker-compose.yml ---- # redb.Identity and the application module in one Tsak worker (the redb-identity-full image: worker, # Tsak dashboard, Identity's own sign-in and admin UI) #if (web) # and the application's web server. #endif # # From the project folder: # cp deploy/.env.example deploy/.env # then set the secrets # pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbIdentityApp.tpkg # docker compose -f deploy/docker-compose.yml up -d --build # #if (web) # Then open http://localhost:5085 (the application) and sign in as admin with IDENTITY_ADMIN_PASSWORD. #else # Then call the module's API on http://localhost:5094/api/me with an access token from Identity. #endif # Identity's own UI: http://localhost:8087; the Tsak dashboard: http://localhost:8085. # # Identity answers at https://localhost:5002 with the image's self-signed certificate: the browser warns #if (web) # once, the web server trusts it through its CA store (RedbIdentityApp.Web/Dockerfile). For a real #else # once. For a real #endif # deployment put a real certificate and the public https address on Identity (see README, "Deploy"). services: identity: image: ghcr.io/redbase-app/redb-identity-full:${IDENTITY_VERSION:-4.8.0} restart: unless-stopped ports: # Identity's issuer: the port is part of it, so it is the same inside and outside. - "127.0.0.1:5002:5002" - "127.0.0.1:8087:8087" # Identity's sign-in and admin UI - "127.0.0.1:8085:8085" # Tsak dashboard # The module's API, for a web server started on the host with dotnet run. - "127.0.0.1:5094:5094" #if (web) # The application's web server: it shares this container's network (network_mode below). - "127.0.0.1:5085:5085" #endif environment: # The worker's management API has no API keys in this image: it listens on 127.0.0.1 only, where the # Tsak dashboard of the same container reaches it, and its port is not published. Tsak__Api__Host: 127.0.0.1 # The dashboard's sign-in (login admin). Tsak__Web__AdminPassword: ${TSAK_WEB_ADMIN_PASSWORD:?TSAK_WEB_ADMIN_PASSWORD required} # The application module: a second module folder of the worker. Tsak__Modules__AssemblyPaths__1: /app/modules # The module listens on all interfaces of the container, so the published port above reaches it. Tsak__Contexts__redbidentityapp__Override__Api__Host: 0.0.0.0 # --- Identity --- # The first administrator: replaces the default admin/admin while it is untouched. Tsak__Contexts__identity.core__Override__Identity__SeedAdmin__Password: ${IDENTITY_ADMIN_PASSWORD:?IDENTITY_ADMIN_PASSWORD required} # The service client the module and Identity's own UI use for the management API. Tsak__Contexts__identity.core__Override__Identity__SeedBackchannelClient__ClientSecret: ${MANAGEMENT_CLIENT_SECRET:?MANAGEMENT_CLIENT_SECRET required} Identity__BackchannelClient__ClientSecret: ${MANAGEMENT_CLIENT_SECRET:?MANAGEMENT_CLIENT_SECRET required} # The application's administrative scope is issued only to users whose role carries it (the module # attaches it to the admin role). scim is Identity's own default and stays. Tsak__Contexts__identity.core__Override__Identity__AdminScopeEntitlement__GatedScopes__0: scim Tsak__Contexts__identity.core__Override__Identity__AdminScopeEntitlement__GatedScopes__1: redbidentityapp.admin # Identity reports revocations to the module, which then drops its cached token checks at once. # Remove these three lines together with the module: Identity logs an error for every event it # cannot deliver. Tsak__Contexts__identity.core__Override__Identity__Audit__Targets__0__Name: redbidentityapp Tsak__Contexts__identity.core__Override__Identity__Audit__Targets__0__Enabled: "true" Tsak__Contexts__identity.core__Override__Identity__Audit__Targets__0__Uri: direct-vm://redbidentityapp-identity-events # --- The module's secrets --- Tsak__Contexts__redbidentityapp__Override__Identity__ResourceClientSecret: ${RESOURCE_CLIENT_SECRET:?RESOURCE_CLIENT_SECRET required} Tsak__Contexts__redbidentityapp__Override__Identity__ManagementClientSecret: ${MANAGEMENT_CLIENT_SECRET:?MANAGEMENT_CLIENT_SECRET required} #if (web) Tsak__Contexts__redbidentityapp__Override__Identity__WebClientSecret: ${WEB_CLIENT_SECRET:?WEB_CLIENT_SECRET required} #endif volumes: - identity_data:/app/data # SQLite: Identity's store and the worker's (the module's notes) - identity_dp_keys:/root/.aspnet/DataProtection-Keys # key rings of the Tsak worker and dashboard - identity_web_keys:/app/web-keys # Identity UI's key ring: its sign-ins survive a recreated container - identity_web_logs:/app/web-logs - ./output:/app/modules:ro # RedbIdentityApp.tpkg (pack-tpkg.ps1) #if (web) web: build: context: .. dockerfile: RedbIdentityApp.Web/Dockerfile restart: unless-stopped # One network namespace with Identity: https://localhost:5002 is Identity for the browser and for this # server alike, and the module's API is 127.0.0.1:5094. network_mode: "service:identity" environment: Identity__ClientSecret: ${WEB_CLIENT_SECRET:?WEB_CLIENT_SECRET required} volumes: - web_keys:/keys # this server's key ring: sessions survive a recreated container depends_on: - identity #endif volumes: identity_data: identity_dp_keys: identity_web_keys: identity_web_logs: #if (web) web_keys: #endif Path: redb/redb.Templates/templates/redb-identity-app/deploy/pack-tpkg.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds RedbIdentityApp.Module and packs it into RedbIdentityApp.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, RedbIdentityApp.Module.dll and every dependency the worker does not ship itself (RedbIdentityApp.Contracts, for example). deploy/shipped-module-deps.txt lists what the worker ships (its header says how to regenerate the list); the package contents are written next to it as RedbIdentityApp.tpkg.contents.txt. .EXAMPLE ./deploy/pack-tpkg.ps1 ./deploy/pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $module = Join-Path $root "RedbIdentityApp.Module" $entryDll = "RedbIdentityApp.Module.dll" $publish = Join-Path ([IO.Path]::GetTempPath()) "redbidentityapp-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "redbidentityapp-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "RedbIdentityApp.tpkg" $shippedList = Join-Path $PSScriptRoot "shipped-module-deps.txt" # 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 $module "RedbIdentityApp.Module.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of RedbIdentityApp.Module failed." } # The worker resolves only the assemblies it ships (shipped-module-deps.txt). Every other dependency, # RedbIdentityApp.Contracts included, has to travel inside the package, otherwise the module fails to load. $shipped = @(Get-Content $shippedList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $extra = @(Get-ChildItem $publish -Filter *.dll | Where-Object { $_.Name -ne $entryDll -and $shipped -notcontains $_.Name }) 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 $module "manifest.json") $staging Copy-Item (Join-Path $module "RedbIdentityApp.Module.config.json") $staging Copy-Item (Join-Path $publish $entryDll) $staging foreach ($dependency in $extra) { Copy-Item $dependency.FullName $staging } # Native assets of a dependency (runtimes//native/...), if the module brought any. $runtimes = Join-Path $publish "runtimes" if (Test-Path $runtimes) { Copy-Item $runtimes $staging -Recurse } if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) # What the package holds, next to it: handy when a Tsak node refuses to load the module. $contents = Get-ChildItem $staging -Recurse -File | ForEach-Object { $_.FullName.Substring($staging.Length + 1).Replace('\', '/') } Set-Content -Path ($package + ".contents.txt") -Value $contents -Encoding utf8 Write-Host "Packed $package" Write-Host " module: $entryDll" Write-Host (" packed dependencies: {0}" -f $extra.Count) foreach ($dependency in $extra) { Write-Host (" " + $dependency.Name) } Write-Host (" not packed: {0} assemblies shipped by the worker" -f $shipped.Count) Path: redb/redb.Templates/templates/redb-identity-app/deploy/shipped-module-deps.txt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-identity-app/deploy/shipped-module-deps.txt ---- # Assemblies the worker of redb-identity-full:4.8.0 already provides. A module dependency present here is # NOT packed into the .tpkg; every other dependency travels inside the package. # # Two sources: # - the Tsak worker itself: /app/worker/*.dll and /app/worker/Libs/shared/*.dll of the image (the same set # as redb-tsak-worker:4.8.0), and the ASP.NET Core shared-framework assemblies of its base image that this # list carries (Microsoft.Extensions.*, System.Diagnostics.EventLog, System.Security.Cryptography.Pkcs): the # worker binds them from /usr/share/dotnet/shared, and a copy inside the package would give ILogger, # IConfiguration or IOptions a second type identity; # - the redb.Identity modules loaded in that worker: redb.Identity.Contracts.dll comes from the # identity.contracts carrier, one copy per process. A second copy inside this package would be a second # type identity, and every contract type the module exchanges with Identity would stop matching. # # Regenerate the worker part when the image changes: the command gives the /app/worker part; merge it in and keep # the shared-framework entries the list already has. # docker run --rm --entrypoint sh ghcr.io/redbase-app/redb-identity-full: -c "ls /app/worker/*.dll /app/worker/Libs/shared/*.dll" | sed "s|.*/||" | sort -u # # Provided by the redb.Identity modules: redb.Identity.Contracts.dll # # Provided by the Tsak worker: AWSSDK.Core.dll AWSSDK.S3.dll AWSSDK.SQS.dll AWSSDK.SimpleNotificationService.dll Amqp.Net.dll Azure.Core.Amqp.dll Azure.Core.dll Azure.Messaging.ServiceBus.dll BCrypt-Net-Next.dll BouncyCastle.Cryptography.dll Chr.Avro.Binary.dll Chr.Avro.Json.dll Chr.Avro.dll Confluent.Kafka.dll CsvHelper.dll Elastic.Clients.Elasticsearch.dll Elastic.Esql.dll Elastic.Transport.dll FirebaseAdmin.dll FluentFTP.dll FluentValidation.dll Google.Api.CommonProtos.dll Google.Api.Gax.Grpc.dll Google.Api.Gax.Rest.dll Google.Api.Gax.dll Google.Apis.Auth.dll Google.Apis.Core.dll Google.Apis.Storage.v1.dll Google.Apis.dll Google.Cloud.Firestore.V1.dll Google.Cloud.Firestore.dll Google.Cloud.Location.dll Google.Cloud.Storage.V1.dll Google.LongRunning.dll Google.Protobuf.dll Grpc.Auth.dll Grpc.Core.Api.dll Grpc.Net.Client.dll Grpc.Net.Common.dll Humanizer.dll Json.More.dll JsonPath.Net.dll JsonPointer.Net.dll JsonSchema.Net.dll Jsonata.Net.Native.SystemTextJson.dll Jsonata.Net.Native.dll MQTTnet.dll MailKit.dll MessagePack.Annotations.dll MessagePack.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Protocols.MessagePack.dll Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll Microsoft.Azure.Amqp.dll Microsoft.Bcl.AsyncInterfaces.dll Microsoft.Bcl.Cryptography.dll Microsoft.Data.SqlClient.Extensions.Abstractions.dll Microsoft.Data.SqlClient.Internal.Logging.dll Microsoft.Data.SqlClient.dll Microsoft.Data.Sqlite.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.CommandLine.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.Configuration.UserSecrets.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.Diagnostics.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.dll Microsoft.Extensions.Diagnostics.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.Console.dll Microsoft.Extensions.Logging.Debug.dll Microsoft.Extensions.Logging.EventLog.dll Microsoft.Extensions.Logging.EventSource.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.Identity.Client.Extensions.Msal.dll Microsoft.Identity.Client.dll Microsoft.IdentityModel.Abstractions.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Protocols.OpenIdConnect.dll Microsoft.IdentityModel.Protocols.dll Microsoft.IdentityModel.Tokens.dll Microsoft.NET.StringTools.dll Microsoft.SqlServer.Server.dll MimeKit.dll Newtonsoft.Json.dll Novell.Directory.Ldap.NETStandard.dll Npgsql.dll OpenTelemetry.Api.ProviderBuilderExtensions.dll OpenTelemetry.Api.dll OpenTelemetry.Exporter.OpenTelemetryProtocol.dll OpenTelemetry.Exporter.Prometheus.HttpListener.dll OpenTelemetry.Extensions.Hosting.dll OpenTelemetry.Instrumentation.Process.dll OpenTelemetry.Instrumentation.Runtime.dll OpenTelemetry.dll Pipelines.Sockets.Unofficial.dll Quartz.Extensions.DependencyInjection.dll Quartz.Extensions.Hosting.dll Quartz.Serialization.Json.dll Quartz.dll RabbitMQ.Client.OAuth2.dll RabbitMQ.Client.dll Renci.SshNet.dll SQLitePCLRaw.batteries_v2.dll SQLitePCLRaw.core.dll SQLitePCLRaw.provider.e_sqlite3.dll Scriban.dll Serilog.AspNetCore.dll Serilog.Enrichers.Environment.dll Serilog.Enrichers.Process.dll Serilog.Enrichers.Thread.dll Serilog.Extensions.Hosting.dll Serilog.Extensions.Logging.dll Serilog.Formatting.Compact.dll Serilog.Settings.Configuration.dll Serilog.Sinks.Console.dll Serilog.Sinks.Debug.dll Serilog.Sinks.File.dll Serilog.dll StackExchange.Redis.dll System.ClientModel.dll System.CodeDom.dll System.Configuration.ConfigurationManager.dll System.Diagnostics.EventLog.dll System.IO.Hashing.dll System.IdentityModel.Tokens.Jwt.dll System.Management.dll System.Memory.Data.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll Telegram.Bot.dll XPath2.dll YamlDotNet.dll amqmdnetstd.dll amqmxmsstd.dll redb.Core.Pro.dll redb.Core.dll redb.Licensing.dll redb.MSSql.Pro.dll redb.MSSql.dll redb.Postgres.Pro.dll redb.Postgres.dll redb.Route.Amqp.dll redb.Route.As2.dll redb.Route.As4.dll redb.Route.AzureServiceBus.dll redb.Route.Cache.dll redb.Route.Controllers.dll redb.Route.Core.dll redb.Route.DataFormats.Avro.dll redb.Route.DataFormats.Csv.dll redb.Route.DataFormats.Mime.dll redb.Route.DataFormats.Protobuf.dll redb.Route.DataFormats.XmlJson.dll redb.Route.DataFormats.Yaml.dll redb.Route.Elasticsearch.dll redb.Route.Exec.dll redb.Route.File.dll redb.Route.Firebase.dll redb.Route.Ftp.dll redb.Route.GenericFile.dll redb.Route.Grpc.dll redb.Route.Http.Hosting.dll redb.Route.Http.dll redb.Route.IbmMq.dll redb.Route.JsonTransform.dll redb.Route.Kafka.dll redb.Route.Ldap.dll redb.Route.Llm.Abstractions.dll redb.Route.Llm.Mcp.dll redb.Route.Llm.Tools.dll redb.Route.Llm.dll redb.Route.Mail.dll redb.Route.MqttNet.dll redb.Route.Quartz.dll redb.Route.RabbitMQ.dll redb.Route.Redis.dll redb.Route.S3.dll redb.Route.Sftp.dll redb.Route.SignalR.StackExchangeRedis.dll redb.Route.SignalR.dll redb.Route.Soap.dll redb.Route.Sql.dll redb.Route.Sqs.dll redb.Route.Tcp.dll redb.Route.Telegram.dll redb.Route.Templates.dll redb.Route.Validation.Adapters.dll redb.Route.WebSocket.dll redb.Route.XPath2.dll redb.Route.Xml.dll redb.Route.dll redb.SQLite.Pro.dll redb.SQLite.dll redb.Tsak.Contracts.dll redb.Tsak.Core.Pro.dll redb.Tsak.Core.dll redb.Tsak.Worker.dll Path: redb/redb.Templates/templates/redb-razor/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/.dockerignore ---- bin/ obj/ *.db *.db-shm *.db-wal Path: redb/redb.Templates/templates/redb-razor/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Web", "Razor Pages", "Database", "RedBase" ], "identity": "RedBase.Razor.Template", "name": "RedBase Razor Pages Site", "description": "A Razor Pages site on redb: a product list with search, sorting and paging, and a create and edit form; runs as is on SQLite with Pro.", "shortName": "redb-razor", "tags": { "language": "C#", "type": "project" }, "sourceName": "RedbRazor", "preferNameDirectory": true, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/redb-razor/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Dockerfile ---- # Build: docker build -t redbrazor . # Run: docker run -p 8080:8080 -v redbrazor-data:/data redbrazor FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY RedbRazor.csproj . RUN dotnet restore COPY . . RUN dotnet publish -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app . # The SQLite file goes to a volume, so it survives a new container. The app runs as the # non-root user of the .NET image, which must be able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/app.db" ENV ASPNETCORE_URLS=http://+:8080 VOLUME /data EXPOSE 8080 ENTRYPOINT ["dotnet", "RedbRazor.dll"] Path: redb/redb.Templates/templates/redb-razor/Models/Product.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Models/Product.cs ---- using redb.Core.Attributes; namespace RedbRazor.Models; /// /// The Props of a product. The object's name is not here: it is the object's own field /// (RedbObject.Name). Each property is stored in a typed column, so filters and sorting on /// them run in the database. /// [RedbScheme("Product")] public class Product { public string Category { get; set; } = string.Empty; public decimal Price { get; set; } public bool InStock { get; set; } public string? Description { get; set; } } Path: redb/redb.Templates/templates/redb-razor/Pages/Edit.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Edit.cshtml ---- @page "{id:long?}" @model EditModel @{ ViewData["Title"] = Model.Id is null ? "New product" : "Edit product"; }

@ViewData["Title"]

Cancel
Path: redb/redb.Templates/templates/redb-razor/Pages/Edit.cshtml.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Edit.cshtml.cs ---- using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using redb.Core; using redb.Core.Models.Entities; using RedbRazor.Models; namespace RedbRazor.Pages; /// /// Create (no id) and edit (with id) on one page. /// public class EditModel(IRedbService redb) : PageModel { [BindProperty] public ProductInput Input { get; set; } = new(); public long? Id { get; private set; } public async Task OnGetAsync(long? id) { if (id is null) return Page(); var product = await redb.LoadAsync(id.Value); if (product is null) return NotFound(); Id = product.Id; Input = new ProductInput { Name = product.Name ?? string.Empty, Category = product.Props!.Category, Price = product.Props.Price, InStock = product.Props.InStock, Description = product.Props.Description, }; return Page(); } public async Task OnPostAsync(long? id) { Id = id; if (!ModelState.IsValid) return Page(); RedbObject product; if (id is null) { product = new RedbObject { Props = new Product() }; } else { // Load, then change: with change tracking on, the save writes only the fields that // differ from what was loaded. product = await redb.LoadAsync(id.Value) ?? throw new InvalidOperationException($"Product {id} not found."); } product.Name = Input.Name; product.Props!.Category = Input.Category; product.Props.Price = Input.Price; product.Props.InStock = Input.InStock; product.Props.Description = Input.Description; await redb.SaveAsync(product); return RedirectToPage("/Index"); } /// What the form posts. Validation lives here, not on the Props class. public class ProductInput { [Required, StringLength(200)] public string Name { get; set; } = string.Empty; [Required, StringLength(100)] public string Category { get; set; } = string.Empty; [Range(0, 1_000_000)] public decimal Price { get; set; } public bool InStock { get; set; } [StringLength(2000)] public string? Description { get; set; } } } Path: redb/redb.Templates/templates/redb-razor/Pages/Error.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Error.cshtml ---- @page @{ ViewData["Title"] = "Error"; }

Something went wrong

The request could not be completed. Check the application log for details.

Path: redb/redb.Templates/templates/redb-razor/Pages/Index.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Index.cshtml ---- @page @model IndexModel @{ ViewData["Title"] = "Products"; }

Products

@Model.Total product(s)

@foreach (var item in Model.Items) { }
NameCategoryPriceIn stock
@item.Name @item.Props!.Category @item.Props.Price.ToString("F2", System.Globalization.CultureInfo.InvariantCulture) @(item.Props.InStock ? "yes" : "no")
Path: redb/redb.Templates/templates/redb-razor/Pages/Index.cshtml.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Index.cshtml.cs ---- using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using RedbRazor.Models; namespace RedbRazor.Pages; /// /// Product list. Search, sorting and paging all run in the database: the page never loads more than /// one page of objects. /// public class IndexModel(IRedbService redb) : PageModel { public const int PageSize = 10; [BindProperty(SupportsGet = true)] public string? Search { get; set; } [BindProperty(SupportsGet = true)] public bool InStockOnly { get; set; } [BindProperty(SupportsGet = true)] public string Sort { get; set; } = "name"; [BindProperty(SupportsGet = true, Name = "p")] public int PageNumber { get; set; } = 1; public List> Items { get; private set; } = []; public int Total { get; private set; } public int PageCount => Math.Max(1, (Total + PageSize - 1) / PageSize); public async Task OnGetAsync() { Total = await Filtered().CountAsync(); PageNumber = Math.Clamp(PageNumber, 1, PageCount); Items = await Sorted(Filtered()) .Skip((PageNumber - 1) * PageSize) .Take(PageSize) .ToListAsync(); } public async Task OnPostDeleteAsync(long id) { await redb.DeleteAsync(id); return RedirectToPage(new { Search, InStockOnly, Sort, p = PageNumber }); } // The filter is built from scratch for the count and for the page, so the two queries do not // share state. private IRedbQueryable Filtered() { var query = redb.Query(); // Name is the object's own field, so it is filtered with WhereRedb; Props fields use Where. // The value goes through a local, so the expression captures a plain value, not the page model. var search = Search?.Trim(); if (!string.IsNullOrEmpty(search)) query = query.WhereRedb(x => x.Name.Contains(search)); if (InStockOnly) query = query.Where(x => x.InStock); return query; } private IRedbQueryable Sorted(IRedbQueryable query) => Sort switch { "price" => query.OrderBy(x => x.Price), "-price" => query.OrderByDescending(x => x.Price), "category" => query.OrderBy(x => x.Category), _ => query.OrderByRedb(x => x.Name), }; } Path: redb/redb.Templates/templates/redb-razor/Pages/Shared/_Layout.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/Shared/_Layout.cshtml ---- @ViewData["Title"] - RedbRazor
RedbRazor New product
@RenderBody()
Path: redb/redb.Templates/templates/redb-razor/Pages/_ViewImports.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/_ViewImports.cshtml ---- @using RedbRazor @using RedbRazor.Models @namespace RedbRazor.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers Path: redb/redb.Templates/templates/redb-razor/Pages/_ViewStart.cshtml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Pages/_ViewStart.cshtml ---- @{ Layout = "_Layout"; } Path: redb/redb.Templates/templates/redb-razor/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Program.cs ---- using System.Globalization; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.SQLite.Pro.Extensions; using RedbRazor.Models; var builder = WebApplication.CreateBuilder(args); // --- Culture --- // The forms carry a decimal price, so parsing must not depend on the locale of the machine the site // runs on: with a comma locale (ru-RU, de-DE) the value "123.45" a browser sends would not bind, and // the answer would differ per deployment. Pinning the invariant culture makes input, output and the // HTML number input agree. To accept the caller's locale instead, use RequestLocalization (see README). CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; builder.Services.AddRazorPages(); // --- RedBase --- // The connection string lives in appsettings.json ("ConnectionStrings:Redb"). In a container it is // overridden by the ConnectionStrings__Redb environment variable (see deploy/*.yml). var connectionString = builder.Configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); builder.Services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbRazor.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); var app = builder.Build(); // --- Initialize RedBase once at startup --- // IRedbService is scoped: one per request, one connection. Startup work takes its own scope. // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await using (var scope = app.Services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await SeedAsync(redb); } if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.MapRazorPages(); app.Run(); // A few products on the first run, so the list is not empty. static async Task SeedAsync(IRedbService redb) { if (await redb.Query().AnyAsync()) return; var samples = new (string Name, string Category, decimal Price, bool InStock)[] { ("Laptop 14", "Laptops", 1299m, true), ("Laptop 16", "Laptops", 1899m, false), ("Monitor 27", "Monitors", 349m, true), ("Keyboard", "Accessories", 79m, true), ("Mouse", "Accessories", 39m, true), }; foreach (var s in samples) { await redb.SaveAsync(new RedbObject { Name = s.Name, Props = new Product { Category = s.Category, Price = s.Price, InStock = s.InStock } }); } } Path: redb/redb.Templates/templates/redb-razor/Properties/launchSettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/Properties/launchSettings.json ---- { "profiles": { "RedbRazor": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "http://localhost:5080", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } Path: redb/redb.Templates/templates/redb-razor/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/README.md ---- # RedbRazor A Razor Pages site on RedBase: a product list with search, sorting and paging, and a create / edit form. SQLite with Pro, so it runs as is. ## Run ```bash dotnet run ``` Open http://localhost:5080. On the first run the app creates `app.db` next to itself, builds the RedBase tables and adds a few sample products. ## Where things are | File | What it does | |------|--------------| | `Program.cs` | RedBase registration and settings, startup initialization, sample data | | `Models/Product.cs` | The Props class: one scheme, typed properties | | `Pages/Index.cshtml.cs` | Search, sorting and paging, all in the database | | `Pages/Edit.cshtml.cs` | Create and edit; with change tracking a save writes only what changed | | `appsettings.json` | `ConnectionStrings:Redb` | ## RedBase settings `Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. ## Culture The edit form carries a decimal price, so `Program.cs` pins the invariant culture: a machine set to a comma locale (ru-RU, de-DE) would otherwise reject the `123.45` a browser sends for a ``, and the site would answer differently per deployment. `Pages/Index.cshtml` formats the price with the same culture, so input and output agree. To follow the caller's locale instead, replace the two `CultureInfo.DefaultThreadCurrent*` lines with request localization: ```csharp builder.Services.Configure(o => o .SetDefaultCulture("en-US") .AddSupportedCultures("en-US", "ru-RU") .AddSupportedUICultures("en-US", "ru-RU")); // ... app.UseRequestLocalization(); ``` Mind the trade-off: then "123.45" posts from an en-US browser and "123,45" from a ru-RU one, so the same form accepts different input per caller. `InvariantCulture.Parse("1299,5")` is 12995 (a comma is a group separator there), which is why the invariant choice keeps the decimal point meaningful. ## Another database 1. In `RedbRazor.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy - `Dockerfile`: the site with SQLite on a volume. `docker build -t redbrazor . && docker run -p 8080:8080 -v redbrazor-data:/data redbrazor` - `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml`: the site with a database server. Switch the provider first (see above); each file has the commands at the top. Path: redb/redb.Templates/templates/redb-razor/RedbRazor.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/RedbRazor.csproj ---- net10.0 enable enable RedbRazor 4.8.0 false Path: redb/redb.Templates/templates/redb-razor/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=app.db" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } Path: redb/redb.Templates/templates/redb-razor/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/deploy/docker-compose.mssql.yml ---- # The site with SQL Server instead of SQLite. # Before the first run, switch the provider in code (see the comment in Program.cs): # RedbRazor.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then: docker compose -f deploy/docker-compose.mssql.yml up --build services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql app: build: .. ports: - "8080:8080" environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" depends_on: - db volumes: mssqldata: Path: redb/redb.Templates/templates/redb-razor/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/deploy/docker-compose.postgres.yml ---- # The site with PostgreSQL instead of SQLite. # Before the first run, switch the provider in code (see the comment in Program.cs): # RedbRazor.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder: docker compose -f deploy/docker-compose.postgres.yml up --build services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 app: build: .. ports: - "8080:8080" environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" depends_on: db: condition: service_healthy volumes: pgdata: Path: redb/redb.Templates/templates/redb-razor/wwwroot/css/site.css Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-razor/wwwroot/css/site.css ---- body { font-family: system-ui, sans-serif; margin: 0; color: #1f2328; background: #fff; } header { display: flex; gap: 1.5rem; align-items: center; padding: 0.75rem 1.5rem; border-bottom: 1px solid #d0d7de; } header .brand { font-weight: 600; color: #b3261e; text-decoration: none; } main { max-width: 960px; margin: 0 auto; padding: 1rem 1.5rem; } a { color: #0969da; } .filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 0.5rem; } .muted { color: #656d76; } table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #d0d7de; } .num { text-align: right; } .pager { display: flex; gap: 0.5rem; margin-top: 1rem; } .pager span { font-weight: 600; } .form { display: grid; gap: 0.35rem; max-width: 480px; } .form input:not([type=checkbox]), .form textarea { padding: 0.35rem; font: inherit; } .form .actions { display: flex; gap: 1rem; align-items: center; margin-top: 0.75rem; } .field-validation-error, .validation-summary-errors { color: #b3261e; } button.link { background: none; border: 0; padding: 0; color: #b3261e; cursor: pointer; font: inherit; } Path: redb/redb.Templates/templates/redb-worker/.dockerignore Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/.dockerignore ---- **/bin/ **/obj/ *.db *.db-shm *.db-wal data/ deploy/output/ Path: redb/redb.Templates/templates/redb-worker/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Worker", "Integration", "Database", "RedBase" ], "identity": "RedBase.Worker.Template", "name": "RedBase Integration Worker", "description": "An integration worker on redb.Route and redb: a folder inbox, an XSD check, one transaction and a receipt; its own host or a Tsak module.", "shortName": "redb-worker", "tags": { "language": "C#", "type": "solution" }, "sourceName": "RedbWorker", "preferNameDirectory": true, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "**/*.db", "**/*.db-shm", "**/*.db-wal", "data/**", "runtime/**", "deploy/output/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/redb-worker/Directory.Build.props Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/Directory.Build.props ---- net10.0 enable enable 4.8.0 false Path: redb/redb.Templates/templates/redb-worker/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/Dockerfile ---- # The worker in its own host, without Tsak. # Build: docker build -t redbworker . # Run: docker run -v redbworker-data:/data redbworker # then put order files into the volume's inbox folder. FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY Directory.Build.props . COPY RedbWorker.Module/RedbWorker.Module.csproj RedbWorker.Module/ COPY RedbWorker.Host/RedbWorker.Host.csproj RedbWorker.Host/ RUN dotnet restore RedbWorker.Host/RedbWorker.Host.csproj COPY . . RUN dotnet publish RedbWorker.Host/RedbWorker.Host.csproj -c Release -o /app --no-restore FROM mcr.microsoft.com/dotnet/runtime:10.0 WORKDIR /app COPY --from=build /app . # The database and the folders go to a volume. The app runs as the non-root user of the .NET image, # which must be able to write there. RUN mkdir /data && chown $APP_UID /data USER $APP_UID ENV ConnectionStrings__Redb="Data Source=/data/redbworker.db" ENV Tsak__Contexts__redbworker__Override__Folders__Inbox=/data/inbox ENV Tsak__Contexts__redbworker__Override__Folders__Outbox=/data/outbox ENV Tsak__Contexts__redbworker__Override__Folders__Archive=/data/archive ENV Tsak__Contexts__redbworker__Override__Folders__Error=/data/error VOLUME /data ENTRYPOINT ["dotnet", "RedbWorker.Host.dll"] Path: redb/redb.Templates/templates/redb-worker/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/README.md ---- # RedbWorker An integration worker on RedBase and redb.Route: order files arrive in a folder, are checked against an XSD schema, stored in RedBase in one transaction, and answered with a receipt file. SQLite with Pro, so it runs as is. The same module runs in two places: in its own console host, and on a Tsak worker. ## Run ```bash dotnet run --project RedbWorker.Host ``` On the first run the host creates `redbworker.db` and the folders under `data/` in the current directory. In a second terminal: ```bash cp samples/order-1001.xml data/inbox/ # accepted cp samples/order-1001.xml data/inbox/again.xml # duplicate: the same order id cp samples/order-invalid.xml data/inbox/ # rejected: violates the schema ``` Every file taken from the inbox gets a receipt in `data/outbox` and moves to `data/archive`. A file that violates the schema - a negative amount, a currency that is not three capitals - and a file that is not XML at all are both answered with `Rejected`: the schema check wraps a parsing error in the same `ValidationException`. A file that fails for another reason (the database is down, the runtime cannot process it) moves to `data/error` and is picked up again on the next poll. ## Where things are | File | What it does | |------|--------------| | `RedbWorker.Module/InitRoute.cs` | The module's entry point: components, schemes, routes. Tsak calls the same method | | `RedbWorker.Module/Routes/OrderInboxRouteBuilder.cs` | inbox -> schema -> `.Transacted()` -> receipt | | `RedbWorker.Module/Routes/ExceptionRouteBuilder.cs` | A schema violation becomes a Rejected receipt | | `RedbWorker.Module/Services/OrderService.cs` | Stores the order; the order id is the object's unique key | | `RedbWorker.Module/Xml/` | `Order.xsd` and the XML classes | | `RedbWorker.Module/RedbWorker.Module.config.json` | The module's settings: folders | | `RedbWorker.Host/Program.cs` | The own host: redb registration and settings, then `InitRoute.main` | | `RedbWorker.Host/appsettings.json` | `ConnectionStrings:Redb` and the `Override` layer of the module settings | ## Settings The module reads its settings from its route context. Both hosts fill it the same way: the module's config file first, then `Tsak:Contexts:redbworker:Override`, which wins. So an environment variable such as `Tsak__Contexts__redbworker__Override__Folders__Inbox=/data/inbox` works in both. ## RedBase settings `RedbWorker.Host/Program.cs` turns on the PVT prefilter and change tracking. The props cache is off; the comment next to it shows the three lines that turn it on. On Tsak the same settings are environment variables of the worker (`Tsak__Redb__...`, see `deploy/docker-compose.tsak.yml`). The compose file sets no `Tsak__Cluster__NodeId`: a worker is named after its container's host name, so every replica of `docker compose up --scale` is a Tsak node of its own. Set an explicit id only for a single instance or a StatefulSet; two live workers with one id are refused. ## Other transports The route reads a local folder. For another source, replace the `From(...)` line: - SFTP: package `redb.Route.Sftp`, `From(Sftp.Directory("orders").ConnectionFactory("partner"))` - AS2: package `redb.Route.As2`, `From(As2.Receive(...))` - a database table: package `redb.Route.Sql`, `From(Sql.Poll(...))` ## Another database 1. In `RedbWorker.Host.csproj` replace `redb.SQLite.Pro` with `redb.Postgres.Pro` or `redb.MSSql.Pro`. 2. In `Program.cs` replace `using redb.SQLite.Pro.Extensions` and `.UseSqlite(...)` as the comment there says. 3. Put the connection string into `appsettings.json`. The database must exist: RedBase creates its tables, not the database. ## Deploy **Own host** - `Dockerfile`: the host with SQLite and the folders on a volume. `docker build -t redbworker . && docker run -v redbworker-data:/data redbworker` - `deploy/docker-compose.postgres.yml`, `deploy/docker-compose.mssql.yml`: the host with a database server. Switch the provider first (see above); each file has the commands at the top. **Tsak** 1. `cp deploy/.env.example deploy/.env` and fill in the four values. 2. `pwsh deploy/pack-tpkg.ps1` packs the module into `deploy/output/RedbWorker.tpkg`. 3. `docker compose -f deploy/docker-compose.tsak.yml up -d` starts the Tsak stack with the module. 4. Put a sample into `runtime/inbox`; the dashboard is at http://localhost:8085. `pack-tpkg.ps1` puts the manifest, the module config, the module DLL and every dependency the worker does not ship itself into the package; `deploy/shipped-module-deps.txt` lists what the worker provides, and `deploy/output/RedbWorker.tpkg.contents.txt` shows what went in. To run the module on a Tsak host built locally from the `tsak-worker` template, drop the assemblies that host lacks (`redb.Route.File.dll`, `redb.Route.GenericFile.dll`, ...) into its `Libs/shared`: the host resolves a module's shared assemblies from `Libs/shared` next to the application, and that template copies `Libs/**` to its output. Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Host/ContextConfiguration.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Host/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace RedbWorker.Host; /// /// The context configuration the way a Tsak worker builds it, in miniature. Each layer deep-merges over /// the previous one, later layers win: /// /// the module's RedbWorker.Module.config.json, /// Tsak:Contexts:{context}:Override of the host configuration. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. So the /// same keys and the same environment variables work here and on a Tsak worker. /// public static class ContextConfiguration { /// The context the 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 = Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"))); 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) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var child in section.GetChildren()) result[child.Key] = child.GetChildren().Any() ? Read(child) : 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; } } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Host/Program.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Host/Program.cs ---- // The module's own host. It does what a Tsak worker does for the module, and nothing more: // 1) reads appsettings.json, then environment variables, // 2) registers redb and initializes it, // 3) builds the context configuration (module config file, then the Override section), // 4) awaits RedbWorker.Module.InitRoute.main(ctx), the method the Tsak worker calls, // 5) starts the context and runs until Ctrl+C or SIGTERM. using System.Runtime.InteropServices; 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.Route.Core; using redb.SQLite.Pro.Extensions; using RedbWorker.Host; using RedbWorker.Module; var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var connectionString = configuration.GetConnectionString("Redb") ?? throw new InvalidOperationException("ConnectionStrings:Redb is missing in appsettings.json."); var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); services.AddRedbPro(options => options .UseSqlite(connectionString) // To use PostgreSQL or SQL Server instead: swap the package in RedbWorker.Host.csproj // (redb.Postgres.Pro / redb.MSSql.Pro), replace the using redb.SQLite.Pro.Extensions above // with redb.Postgres.Pro.Extensions / redb.MSSql.Pro.Extensions, and use one of: //.UsePostgres(connectionString) //.UseMsSql(connectionString) .Configure(c => { // Narrows the object set before the pivot step, so a selective filter does not scan the // whole scheme. It never changes results. c.EnablePvtPrefilter = true; // Saves only the properties that changed since the object was loaded. c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Props cache: off by default. Turn it on when the same objects are read again and // again; the limit is per process, entries past the TTL are loaded again. // c.EnablePropsCache = true; // c.PropsCacheMaxSize = 10_000; // c.PropsCacheTtl = TimeSpan.FromMinutes(60); })); await using var provider = services.BuildServiceProvider(); // ensureCreated builds the RedBase tables on the first run and is idempotent afterwards. It does not // create the database itself: for PostgreSQL and SQL Server the database has to exist already. await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService().InitializeAsync(ensureCreated: true); } var moduleConfig = Path.Combine(AppContext.BaseDirectory, "RedbWorker.Module.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); var context = new RouteContext(provider, contextName, provider.GetRequiredService()); ContextConfiguration.ApplyTo(context, ContextConfiguration.Build(configuration, contextName, moduleConfig)); await InitRoute.main(context); // <- the exact method the Tsak worker calls await context.Start(); var settings = ModuleSettings.FromContext(context); Console.WriteLine(); Console.WriteLine("RedbWorker is running."); Console.WriteLine($" Drop an order file into {settings.Inbox}"); Console.WriteLine($" Receipts arrive in {settings.Outbox}"); Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); var stop = new TaskCompletionSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; // docker stop sends SIGTERM, not Ctrl+C. using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, c => { c.Cancel = true; stop.TrySetResult(); }); await stop.Task; await context.DisposeAsync(); Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Host/RedbWorker.Host.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Host/RedbWorker.Host.csproj ---- Exe Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Host/appsettings.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Host/appsettings.json ---- { "ConnectionStrings": { "Redb": "Data Source=redbworker.db" }, "Tsak": { "Contexts": { "redbworker": { "Override": { } } } } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Headers.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Headers.cs ---- namespace RedbWorker.Module; /// Headers the module sets on an exchange. public static class WorkerHeaders { public const string FileName = "worker.fileName"; public const string OrderId = "worker.orderId"; public const string Status = "worker.status"; } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/InitRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.File; using RedbWorker.Module.Models; using RedbWorker.Module.Routes; namespace RedbWorker.Module; /// /// The module's entry point. A Tsak worker finds it by convention (a public static class /// InitRoute with a main(IRouteContext) method) and awaits it when the module loads; /// RedbWorker.Host calls the same method, so the route code exists once. /// Order: settings, components, the database, then the routes. /// public static class InitRoute { public static async Task main(IRouteContext context) { var settings = ModuleSettings.FromContext(context); settings.EnsureFolders(); var logger = context.GetService()?.CreateLogger("RedbWorker"); var services = context.GetServiceProvider() ?? throw new InvalidOperationException("The route context has no service provider; redb is not available."); if (!context.HasComponent("file")) context.AddComponent(new FileComponent()); // The module's schemes, through a scope of its own: the connection goes back to the pool as soon // as this is done. Every ProcessWithRedb step gets its own IRedbService the same way: the host's // default redb, registered in its DI container. Under Tsak that is Tsak:Redb:Provider. await using (var scope = services.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); } var routes = (RouteContext)context; routes.AddRoutes(new ExceptionRouteBuilder()); routes.AddRoutes(new OrderInboxRouteBuilder()); logger?.LogInformation("RedbWorker module ready: inbox {Inbox}, receipts to {Outbox}", settings.Inbox, settings.Outbox); return context; } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Models/Order.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Models/Order.cs ---- using redb.Core.Attributes; namespace RedbWorker.Module.Models; /// An accepted order, stored in redb. The order id is also the object's unique key. [RedbScheme("Order")] public class Order { public string OrderId { get; set; } = ""; public string Customer { get; set; } = ""; public decimal Amount { get; set; } public string Currency { get; set; } = ""; /// The name of the file the order came in. public string SourceFile { get; set; } = ""; } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/ModuleSettings.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/ModuleSettings.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RedbWorker.Module; /// /// The module's settings, read from the properties of its route context. Both hosts fill them the same /// way: RedbWorker.Module.config.json first, then the Tsak:Contexts:{context}:Override section /// of the host configuration, which wins. An environment variable such as /// Tsak__Contexts__redbworker__Override__Folders__Inbox works in both. /// public sealed record ModuleSettings(string Inbox, string Outbox, string Archive, string Error) { public static ModuleSettings FromContext(IRouteContext context) { var folders = context.GetProperty>("Folders") ?? throw Missing(context, "Folders"); return new( Inbox: FullPath(Value(context, folders, "Inbox")), Outbox: FullPath(Value(context, folders, "Outbox")), Archive: FullPath(Value(context, folders, "Archive")), Error: FullPath(Value(context, folders, "Error"))); } /// Creates the folders that do not exist yet. public void EnsureFolders() { foreach (var folder in new[] { Inbox, Outbox, Archive, Error }) Directory.CreateDirectory(folder); } // Relative paths resolve against the current directory of the process. private static string FullPath(string path) => Path.GetFullPath(path).Replace('\\', '/'); private static string Value(IRouteContext context, IDictionary section, string key) => section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text ? text : throw Missing(context, $"Folders:{key}"); private static InvalidOperationException Missing(IRouteContext context, string key) => new( $"{key} is not configured for context '{context.ContextId}': set it in RedbWorker.Module.config.json " + $"or in Tsak:Contexts:{context.ContextId}:Override."); } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/RedbWorker.Module.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/RedbWorker.Module.config.json ---- { "ContextName": "redbworker", "AutoStart": true, "Folders": { "Inbox": "data/inbox", "Outbox": "data/outbox", "Archive": "data/archive", "Error": "data/error" } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/RedbWorker.Module.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/RedbWorker.Module.csproj ---- Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Routes/ExceptionRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Routes/ExceptionRouteBuilder.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.Validation; using RedbWorker.Module.Xml; namespace RedbWorker.Module.Routes; /// /// 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 file and answer it". A handled exception is a /// success for the file consumer, so the file moves to the archive. A catch-all /// OnException<Exception>().Handled(true) would be wrong here: it would archive a file the /// database never saw. /// /// public sealed class ExceptionRouteBuilder : RouteBuilder { protected override void Configure() { OnException() .Handled(true) .Process(e => e.In.Body = new OrderReceiptXml { Status = ReceiptStatuses.Rejected, Reason = e.Exception?.Message ?? "The file does not match the order schema.", }) .Log("${header.worker.fileName}: rejected, the file does not match the order schema", LogLevel.Warning) .To(RouteUris.WriteReceipt); } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Routes/OrderInboxRouteBuilder.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Routes/OrderInboxRouteBuilder.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.File; using redb.Route.RedbCore.Extensions; using RedbWorker.Module.Services; using RedbWorker.Module.Xml; namespace RedbWorker.Module.Routes; /// /// inbox -> schema check -> one transaction in redb -> receipt in the outbox. /// /// A processed file moves to the archive, a file that failed moves to the error folder. /// A schema violation is the sender's mistake, not a failure: /// answers it with a Rejected receipt and the file goes to the archive like any other. /// Anything else (the file is not XML at all, the database is down) fails the exchange: the /// transaction rolls back and the file goes to the error folder. /// /// public sealed class OrderInboxRouteBuilder : RouteBuilder { protected override void Configure() { var settings = ModuleSettings.FromContext(Context!); From(FileDsl.Read(settings.Inbox) .Include("*.xml") .Delay(1000) .MoveTo(settings.Archive) // Without MoveFailed a failed file stays in the inbox and is picked up again on the next // poll: the better choice when failures are temporary, such as a database restart. .MoveFailed(settings.Error)) .RouteId("order-inbox") .SetHeader(WorkerHeaders.FileName, e => e.In.GetHeader(FileHeaders.FileNameOnly)) .ConvertBody() .Log("${header.worker.fileName}: received") .ValidateXsd(XmlSchemas.Order) .Unmarshal("application/xml") // Everything the order writes to redb commits together or not at all. .Transacted() .ProcessWithRedb(OrderService.RegisterAsync) .EndTransaction() .Log("${header.worker.fileName}: order ${header.worker.orderId} ${header.worker.status}") .To(RouteUris.WriteReceipt); // The receipt, shared by this route and by the exception handler. From(RouteUris.WriteReceipt) .RouteId("write-receipt") .Marshal("application/xml") .To(FileDsl.Write(settings.Outbox).FileName("${header.worker.fileName}.receipt.xml")); } } /// Internal endpoints of the module. public static class RouteUris { public const string WriteReceipt = "direct:write-receipt"; } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Services/OrderService.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Services/OrderService.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using RedbWorker.Module.Models; using RedbWorker.Module.Xml; namespace RedbWorker.Module.Services; /// The work done on an order. Each method is one ProcessWithRedb step of a route. public static class OrderService { /// /// Stores the order, or answers it as a duplicate when an order with the same id is already there. /// Sets the receipt as the new body. /// /// /// Runs inside .Transacted(). The order id is the object's unique key, so two files with the /// same id that arrive at the same time cannot both be stored: the second fails on the key, rolls /// back, stays in the inbox and is answered as a duplicate on the next poll. /// public static async Task RegisterAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var xml = (OrderXml)exchange.In.Body!; exchange.In.Headers[WorkerHeaders.OrderId] = xml.OrderId; var isDuplicate = await redb.Query().Where(o => o.OrderId == xml.OrderId).AnyAsync(); if (isDuplicate) { exchange.In.Headers[WorkerHeaders.Status] = ReceiptStatuses.Duplicate; exchange.In.Body = new OrderReceiptXml { OrderId = xml.OrderId, Status = ReceiptStatuses.Duplicate, Reason = "An order with this id was received before.", }; return; } await redb.SaveAsync(new RedbObject { Name = xml.OrderId, ValueUnique = xml.OrderId, Props = new Order { OrderId = xml.OrderId, Customer = xml.Customer, Amount = xml.Amount, Currency = xml.Currency, SourceFile = exchange.In.GetHeader(WorkerHeaders.FileName) ?? "", }, }, ct); exchange.In.Headers[WorkerHeaders.Status] = ReceiptStatuses.Accepted; exchange.In.Body = new OrderReceiptXml { OrderId = xml.OrderId, Status = ReceiptStatuses.Accepted }; } } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/Order.xsd Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/Order.xsd ---- Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/OrderXml.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/OrderXml.cs ---- using System.Xml.Serialization; namespace RedbWorker.Module.Xml; /// An inbound order, exactly as the file carries it. Checked against Order.xsd first. [XmlRoot("Order")] public sealed class OrderXml { [XmlElement("OrderId")] public string OrderId { get; set; } = ""; [XmlElement("Customer")] public string Customer { get; set; } = ""; [XmlElement("Amount")] public decimal Amount { get; set; } [XmlElement("Currency")] public string Currency { get; set; } = ""; } /// The answer written to the outbox for every file taken from the inbox. [XmlRoot("OrderReceipt")] public sealed class OrderReceiptXml { [XmlElement("OrderId")] public string? OrderId { get; set; } [XmlElement("Status")] public string Status { get; set; } = ""; [XmlElement("Reason")] public string? Reason { get; set; } } /// The values of . public static class ReceiptStatuses { public const string Accepted = "Accepted"; public const string Duplicate = "Duplicate"; public const string Rejected = "Rejected"; } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/XmlSchemas.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/Xml/XmlSchemas.cs ---- namespace RedbWorker.Module.Xml; /// The XSD schemas, compiled into the module as resources. public static class XmlSchemas { public static readonly string Order = Load("Order.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/redb.Templates/templates/redb-worker/RedbWorker.Module/manifest.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.Module/manifest.json ---- { "Name": "RedbWorker", "Version": "1.0.0", "EntryPoints": ["RedbWorker.Module.dll"], "Dependencies": [] } Path: redb/redb.Templates/templates/redb-worker/RedbWorker.slnx Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/RedbWorker.slnx ---- Path: redb/redb.Templates/templates/redb-worker/deploy/docker-compose.mssql.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/deploy/docker-compose.mssql.yml ---- # The worker in its own host with SQL Server instead of SQLite. # Before the first run, switch the provider in code (see the comment in RedbWorker.Host/Program.cs): # RedbWorker.Host.csproj: redb.SQLite.Pro -> redb.MSSql.Pro # Program.cs: .UseSqlite(...) -> .UseMsSql(connectionString) # RedBase creates its tables but not the database: create redb_app once, for example # docker compose -f deploy/docker-compose.mssql.yml up -d db # docker compose -f deploy/docker-compose.mssql.yml exec db /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P "Change_me_123" -Q "CREATE DATABASE redb_app" # Then: docker compose -f deploy/docker-compose.mssql.yml up --build # Put order files into runtime/inbox; receipts arrive in runtime/outbox. services: db: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Change_me_123" volumes: - mssqldata:/var/opt/mssql worker: build: .. environment: ConnectionStrings__Redb: "Server=db,1433;Database=redb_app;User Id=sa;Password=Change_me_123;TrustServerCertificate=true" volumes: # On Linux the folder must be writable by the container's user. - ../runtime:/data depends_on: - db volumes: mssqldata: Path: redb/redb.Templates/templates/redb-worker/deploy/docker-compose.postgres.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/deploy/docker-compose.postgres.yml ---- # The worker in its own host with PostgreSQL instead of SQLite. # Before the first run, switch the provider in code (see the comment in RedbWorker.Host/Program.cs): # RedbWorker.Host.csproj: redb.SQLite.Pro -> redb.Postgres.Pro # Program.cs: .UseSqlite(...) -> .UsePostgres(connectionString) # Then from the project folder: docker compose -f deploy/docker-compose.postgres.yml up --build # Put order files into runtime/inbox; receipts arrive in runtime/outbox. services: db: image: postgres:17 environment: POSTGRES_USER: redb POSTGRES_PASSWORD: change_me POSTGRES_DB: redb_app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U redb -d redb_app"] interval: 5s retries: 10 worker: build: .. environment: ConnectionStrings__Redb: "Host=db;Port=5432;Username=redb;Password=change_me;Database=redb_app;Pooling=true" volumes: # On Linux the folder must be writable by the container's user. - ../runtime:/data depends_on: db: condition: service_healthy volumes: pgdata: Path: redb/redb.Templates/templates/redb-worker/deploy/docker-compose.tsak.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/deploy/docker-compose.tsak.yml ---- # The module on a Tsak worker: the Tsak stack image (worker and dashboard in one container) loads # RedbWorker.tpkg from deploy/output. The worker's default redb is SQLite, so nothing else is needed. # # From the project folder: # cp deploy/.env.example deploy/.env # then fill in the four Tsak values # pwsh deploy/pack-tpkg.ps1 # -> deploy/output/RedbWorker.tpkg # docker compose -f deploy/docker-compose.tsak.yml up -d # # Then put a file from samples/ into runtime/inbox; the receipt arrives in runtime/outbox. # Dashboard: http://localhost:8085 (admin and TSAK_WEB_ADMIN_PASSWORD). services: tsak: image: ghcr.io/redbase-app/redb-tsak-stack:${TSAK_VERSION:-4.8.0-net10} restart: unless-stopped ports: - "127.0.0.1:9090:9090" # worker API - "127.0.0.1:8085:8085" # dashboard environment: # The worker's default (unnamed) redb, the one the module works in. The same settings as the own # host: Pro, change tracking, the PVT prefilter. The props cache stays off; to turn it on add # Tsak__Redb__EnablePropsCache=true. - Tsak__Redb__UsePro=true - Tsak__Redb__PropsSaveStrategy=ChangeTracking - Tsak__Redb__EnablePvtPrefilter=true - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://tsak:9090 # No Tsak__Cluster__NodeId: a node is named after its container's host name, so each replica of # `docker compose up --scale` is a node of its own. A fixed id suits one instance or a StatefulSet only. # 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 folders: the Override layer of its context, the same keys the own host reads. - Tsak__Contexts__redbworker__Override__Folders__Inbox=/data/inbox - Tsak__Contexts__redbworker__Override__Folders__Outbox=/data/outbox - Tsak__Contexts__redbworker__Override__Folders__Archive=/data/archive - Tsak__Contexts__redbworker__Override__Folders__Error=/data/error volumes: - ./output:/app/modules # On Linux the folder must be writable by the container's user. - ../runtime:/data Path: redb/redb.Templates/templates/redb-worker/deploy/pack-tpkg.ps1 Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds RedbWorker.Module and packs it into RedbWorker.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, RedbWorker.Module.dll and every dependency the worker does not ship itself. deploy/shipped-module-deps.txt lists what the worker ships (its header says how to regenerate the list), so a dependency missing from that list travels inside the package. The package contents are also written next to it as RedbWorker.tpkg.contents.txt. .EXAMPLE ./deploy/pack-tpkg.ps1 ./deploy/pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $module = Join-Path $root "RedbWorker.Module" $entryDll = "RedbWorker.Module.dll" $publish = Join-Path ([IO.Path]::GetTempPath()) "redbworker-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "redbworker-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "RedbWorker.tpkg" $shippedList = Join-Path $PSScriptRoot "shipped-module-deps.txt" # 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 $module "RedbWorker.Module.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of RedbWorker.Module failed." } # The worker resolves only the assemblies it ships (shipped-module-deps.txt). Every other dependency # has to travel inside the package, otherwise the module fails to load with FileNotFoundException: # redb.Route.File and redb.Route.GenericFile, for example, are not part of the worker's own set. $shipped = @(Get-Content $shippedList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) $extra = @(Get-ChildItem $publish -Filter *.dll | Where-Object { $_.Name -ne $entryDll -and $shipped -notcontains $_.Name }) 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 $module "manifest.json") $staging Copy-Item (Join-Path $module "RedbWorker.Module.config.json") $staging Copy-Item (Join-Path $publish $entryDll) $staging foreach ($dependency in $extra) { Copy-Item $dependency.FullName $staging } # Native assets of a dependency (runtimes//native/...), if the module brought any. $runtimes = Join-Path $publish "runtimes" if (Test-Path $runtimes) { Copy-Item $runtimes $staging -Recurse } if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) # What the package holds, next to it: handy when a Tsak node refuses to load the module. $contents = Get-ChildItem $staging -Recurse -File | ForEach-Object { $_.FullName.Substring($staging.Length + 1).Replace('\', '/') } Set-Content -Path ($package + ".contents.txt") -Value $contents -Encoding utf8 Write-Host "Packed $package" Write-Host " module: $entryDll" Write-Host (" packed dependencies: {0}" -f $extra.Count) foreach ($dependency in $extra) { Write-Host (" " + $dependency.Name) } Write-Host (" not packed: {0} assemblies shipped by the worker" -f $shipped.Count) Path: redb/redb.Templates/templates/redb-worker/deploy/shipped-module-deps.txt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/deploy/shipped-module-deps.txt ---- # Assemblies the redb.Tsak worker already provides: /app/*.dll and /app/Libs/shared/*.dll of # redb-tsak-worker:4.8.0, and the assemblies of the ASP.NET Core shared framework of its base image that this # list carries (Microsoft.Extensions.*, System.Diagnostics.EventLog, System.Security.Cryptography.Pkcs). The # worker binds those from /usr/share/dotnet/shared: since 4.8 the SDK publishes no copy of them into /app, and a # copy inside a module would give ILogger, IConfiguration or IOptions a second type identity. A module # dependency present here is NOT packed into the .tpkg; every other dependency travels inside the package. # # The worker resolves these from its own folder and from Libs/shared next to the application # (Libs/shared under the app directory, not the current one). A Tsak host built locally from the # tsak-worker template ships a smaller set: put the assemblies a module needs (redb.Route.File, # redb.Route.GenericFile, ...) into that host project Libs/shared - the template copies Libs/** to # the output - or pack them by removing them from this list. # # Regenerate when the worker image changes: the command gives the /app part; merge it in and keep the # shared-framework entries the list already has. # docker run --rm --entrypoint sh redb-tsak-worker: -c "ls /app/*.dll /app/Libs/shared/*.dll" | sed "s|.*/||" | sort -u # AWSSDK.Core.dll AWSSDK.S3.dll AWSSDK.SQS.dll AWSSDK.SimpleNotificationService.dll Amqp.Net.dll Azure.Core.Amqp.dll Azure.Core.dll Azure.Messaging.ServiceBus.dll BCrypt-Net-Next.dll BouncyCastle.Cryptography.dll Chr.Avro.Binary.dll Chr.Avro.Json.dll Chr.Avro.dll Confluent.Kafka.dll CsvHelper.dll Elastic.Clients.Elasticsearch.dll Elastic.Esql.dll Elastic.Transport.dll FirebaseAdmin.dll FluentFTP.dll FluentValidation.dll Google.Api.CommonProtos.dll Google.Api.Gax.Grpc.dll Google.Api.Gax.Rest.dll Google.Api.Gax.dll Google.Apis.Auth.dll Google.Apis.Core.dll Google.Apis.Storage.v1.dll Google.Apis.dll Google.Cloud.Firestore.V1.dll Google.Cloud.Firestore.dll Google.Cloud.Location.dll Google.Cloud.Storage.V1.dll Google.LongRunning.dll Google.Protobuf.dll Grpc.Auth.dll Grpc.Core.Api.dll Grpc.Net.Client.dll Grpc.Net.Common.dll Humanizer.dll Json.More.dll JsonPath.Net.dll JsonPointer.Net.dll JsonSchema.Net.dll Jsonata.Net.Native.SystemTextJson.dll Jsonata.Net.Native.dll MQTTnet.dll MailKit.dll MessagePack.Annotations.dll MessagePack.dll Microsoft.AspNetCore.Http.Connections.Client.dll Microsoft.AspNetCore.SignalR.Client.Core.dll Microsoft.AspNetCore.SignalR.Client.dll Microsoft.AspNetCore.SignalR.Protocols.MessagePack.dll Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll Microsoft.Azure.Amqp.dll Microsoft.Bcl.AsyncInterfaces.dll Microsoft.Bcl.Cryptography.dll Microsoft.Data.SqlClient.Extensions.Abstractions.dll Microsoft.Data.SqlClient.Internal.Logging.dll Microsoft.Data.SqlClient.dll Microsoft.Data.Sqlite.dll Microsoft.Extensions.Caching.Abstractions.dll Microsoft.Extensions.Caching.Memory.dll Microsoft.Extensions.Configuration.Abstractions.dll Microsoft.Extensions.Configuration.Binder.dll Microsoft.Extensions.Configuration.CommandLine.dll Microsoft.Extensions.Configuration.EnvironmentVariables.dll Microsoft.Extensions.Configuration.FileExtensions.dll Microsoft.Extensions.Configuration.Json.dll Microsoft.Extensions.Configuration.UserSecrets.dll Microsoft.Extensions.Configuration.dll Microsoft.Extensions.DependencyInjection.Abstractions.dll Microsoft.Extensions.DependencyInjection.dll Microsoft.Extensions.DependencyModel.dll Microsoft.Extensions.Diagnostics.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.dll Microsoft.Extensions.Diagnostics.HealthChecks.dll Microsoft.Extensions.Diagnostics.dll Microsoft.Extensions.FileProviders.Abstractions.dll Microsoft.Extensions.FileProviders.Physical.dll Microsoft.Extensions.FileSystemGlobbing.dll Microsoft.Extensions.Hosting.Abstractions.dll Microsoft.Extensions.Hosting.dll Microsoft.Extensions.Logging.Abstractions.dll Microsoft.Extensions.Logging.Configuration.dll Microsoft.Extensions.Logging.Console.dll Microsoft.Extensions.Logging.Debug.dll Microsoft.Extensions.Logging.EventLog.dll Microsoft.Extensions.Logging.EventSource.dll Microsoft.Extensions.Logging.dll Microsoft.Extensions.Options.ConfigurationExtensions.dll Microsoft.Extensions.Options.dll Microsoft.Extensions.Primitives.dll Microsoft.Identity.Client.Extensions.Msal.dll Microsoft.Identity.Client.dll Microsoft.IdentityModel.Abstractions.dll Microsoft.IdentityModel.JsonWebTokens.dll Microsoft.IdentityModel.Logging.dll Microsoft.IdentityModel.Protocols.OpenIdConnect.dll Microsoft.IdentityModel.Protocols.dll Microsoft.IdentityModel.Tokens.dll Microsoft.NET.StringTools.dll Microsoft.SqlServer.Server.dll MimeKit.dll Newtonsoft.Json.dll Novell.Directory.Ldap.NETStandard.dll Npgsql.dll OpenTelemetry.Api.ProviderBuilderExtensions.dll OpenTelemetry.Api.dll OpenTelemetry.Exporter.OpenTelemetryProtocol.dll OpenTelemetry.Exporter.Prometheus.HttpListener.dll OpenTelemetry.Extensions.Hosting.dll OpenTelemetry.Instrumentation.Process.dll OpenTelemetry.Instrumentation.Runtime.dll OpenTelemetry.dll Pipelines.Sockets.Unofficial.dll Quartz.Extensions.DependencyInjection.dll Quartz.Extensions.Hosting.dll Quartz.Serialization.Json.dll Quartz.dll RabbitMQ.Client.OAuth2.dll RabbitMQ.Client.dll Renci.SshNet.dll SQLitePCLRaw.batteries_v2.dll SQLitePCLRaw.core.dll SQLitePCLRaw.provider.e_sqlite3.dll Scriban.dll Serilog.AspNetCore.dll Serilog.Enrichers.Environment.dll Serilog.Enrichers.Process.dll Serilog.Enrichers.Thread.dll Serilog.Extensions.Hosting.dll Serilog.Extensions.Logging.dll Serilog.Formatting.Compact.dll Serilog.Settings.Configuration.dll Serilog.Sinks.Console.dll Serilog.Sinks.Debug.dll Serilog.Sinks.File.dll Serilog.dll StackExchange.Redis.dll System.ClientModel.dll System.CodeDom.dll System.Configuration.ConfigurationManager.dll System.Diagnostics.EventLog.dll System.IO.Hashing.dll System.IdentityModel.Tokens.Jwt.dll System.Management.dll System.Memory.Data.dll System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.ProtectedData.dll Telegram.Bot.dll XPath2.dll YamlDotNet.dll amqmdnetstd.dll amqmxmsstd.dll redb.Core.Pro.dll redb.Core.dll redb.Licensing.dll redb.MSSql.Pro.dll redb.MSSql.dll redb.Postgres.Pro.dll redb.Postgres.dll redb.Route.Amqp.dll redb.Route.As2.dll redb.Route.As4.dll redb.Route.AzureServiceBus.dll redb.Route.Cache.dll redb.Route.Controllers.dll redb.Route.Core.dll redb.Route.DataFormats.Avro.dll redb.Route.DataFormats.Csv.dll redb.Route.DataFormats.Mime.dll redb.Route.DataFormats.Protobuf.dll redb.Route.DataFormats.XmlJson.dll redb.Route.DataFormats.Yaml.dll redb.Route.Elasticsearch.dll redb.Route.Exec.dll redb.Route.File.dll redb.Route.Firebase.dll redb.Route.Ftp.dll redb.Route.GenericFile.dll redb.Route.Grpc.dll redb.Route.Http.Hosting.dll redb.Route.Http.dll redb.Route.IbmMq.dll redb.Route.JsonTransform.dll redb.Route.Kafka.dll redb.Route.Ldap.dll redb.Route.Llm.Abstractions.dll redb.Route.Llm.Mcp.dll redb.Route.Llm.Tools.dll redb.Route.Llm.dll redb.Route.Mail.dll redb.Route.MqttNet.dll redb.Route.Quartz.dll redb.Route.RabbitMQ.dll redb.Route.Redis.dll redb.Route.S3.dll redb.Route.Sftp.dll redb.Route.SignalR.StackExchangeRedis.dll redb.Route.SignalR.dll redb.Route.Soap.dll redb.Route.Sql.dll redb.Route.Sqs.dll redb.Route.Tcp.dll redb.Route.Telegram.dll redb.Route.Templates.dll redb.Route.Validation.Adapters.dll redb.Route.WebSocket.dll redb.Route.XPath2.dll redb.Route.Xml.dll redb.Route.dll redb.SQLite.Pro.dll redb.SQLite.dll redb.Tsak.Contracts.dll redb.Tsak.Core.Pro.dll redb.Tsak.Core.dll redb.Tsak.Worker.dll Path: redb/redb.Templates/templates/redb-worker/samples/order-1001.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/samples/order-1001.xml ---- 1001 Contoso Ltd 249.90 EUR Path: redb/redb.Templates/templates/redb-worker/samples/order-invalid.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-worker/samples/order-invalid.xml ---- 1002 Contoso Ltd -5 euro Path: redb/redb.Templates/templates/route-xml/_agents/AGENTS.common.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/_agents/AGENTS.common.md ---- # AGENTS.md Instructions for AI coding agents (GitHub Copilot, Cursor, Codex, Claude Code and others) working in this project. Read this file before changing anything. ## What this project is `RouteModule` is a Tsak module whose routes are written in redb.Route XML markup. It is not an application: the build produces a package, `pkg/routemodule-.tpkg`, that a Tsak worker loads from its `modules/` folder into the route context `modulectx`. The `.csproj` exists to restore the connector packages, so that the build-time check knows their elements and endpoint options, and to compile the C# part: the same scenario also has a route written in C#, a `RouteBuilder` in `routes/*.cs`, as a real project mixes both. ## Files | Path | Holds | |---|---| | `routes/*.route.xml` | the routes; root `` | | `context.xml` | root ``: beans (``), ``, the dead letter channel, context-level blocks | | `resources/` | XSLT, XSD and JSON schema files the routes name by a path under `resources/` | | `config/routemodule.config.json` | identity inside the package: `ContextName`, `AutoStart`; nothing else | | `config/context.sample.json` | the deployment configuration of the context: `Contexts.default`, then `Contexts.modulectx` | ## Rules - Elements, attributes and endpoint options come from the schema, never from memory. The VS Code extension `redb.redb-route-xml` binds it by the namespace and completes options. Without it, run `dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema` and read `schema/redb-route-1.0.xsd`; `dotnet redb-route-xml catalog bin/Debug/net10.0 --out schema` lists the options of every connector. - Connector packages: the worker ships every `redb.Route.*` connector in its shared folder and the module does not bundle its own copies. The `PackageReference` items of the `.csproj` are there for the build-time check. A new connector is one more `PackageReference` of that `redb.Route.*` package with `Version="$(RedbVersion)"`. - A value that differs between deployments is a key: `{{key}}` or `{{key:default}}`. Keys are flat names with dots (`rabbit.host`). Every key goes into `config/context.sample.json` under `Contexts.modulectx` as `"rabbit.host": "..."`; a nested JSON object (`"rabbit": { "host": ... }`) is not found by `{{rabbit.host}}`. - Secrets (passwords, tokens, keys) are keys without a default: never a literal in the XML, never a real value in `context.sample.json`. The build lists the keys without a default in `manifest.json` (`RequiredConfigKeys`), and the module stops at init when one has no value. - A connection or any other object several endpoints share is a `` in `context.xml`; the endpoints refer to it (`connectionFactory=rabbit`, `dataSource=#main-db`, `repository="#name"`). - What XML cannot express (a lambda, custom logic) is a C# class in this project, declared as `` and called as ``. - A C# route is a public `RouteBuilder` with no constructor parameters, added by `` in `context.xml`; `RoutePackageIncludeAssembly` puts the assembly into the package. Its route ids start with `cs-`, and it has its own timers, queues and `direct:` names, so the two forms never consume the same thing twice. It reads the same `{{key}}` configuration and refers to the beans of `context.xml` by name. - In XML attributes `&` is written `&` and `<` is written `<`. - Leave `.config/dotnet-tools.json`, `Directory.Build.props` and `Directory.Build.targets` as they are: the version of the `redb-route-xml` tool must equal `RedbVersion`. ## Expressions An attribute typed as an expression (`expr=` of `when`, `filter`, `validate`, `setHeader`, `setBody`; `correlation=`, `while=`) holds the engine's own expression language. `value=`, `uri`, `id` and the like are literals and are never parsed. The same text reads in three ways: a condition, read as yes or no a template: each ${...} is evaluated a function over the JSON body; xpath(...) for XML An expression reads the exchange through `header.x`, `property.x`, `body` and `exception.message`, and calls a bean method as `bean:pricing.IsBulk(header.qty)`. Text inside an expression is quoted: `'application/json'`; unquoted, `application/json` is a division of two words and an error. - Functions, operators and methods come from the expression reference, never from memory: https://github.com/redbase-app/redb-route/blob/main/EXPRESSIONS.md. What the language lacks is a C# bean method, called through `bean:`. - A broken expression fails when the route file loads, not on the first message: an unclosed `${` or quote, text after a complete expression (`${exception.type|message}`), a bare word inside arithmetic. `check` and the build report it as an error at its attribute, in the engine's words. A bare expression that turns into plain text (`header.b 3`) is a warning: its value is the text, and as a condition it is always true. ## Check every change dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=0.0.1 dotnet redb-route-xml check . --bin bin/Debug/net10.0 The build fails on a markup error, an unknown endpoint option, a bean type or method that does not exist, or a resource outside `resources/`. Then read `pkg/routemodule-0.0.1/manifest.json`: `Context` must be `modulectx`, and `RequiredConfigKeys` must hold exactly the keys a deployment has to supply. A change is done when the build is clean and the manifest says what you meant. ## Run Copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`, and drop the `.tpkg` into the worker's `modules/` folder. Secrets come from the environment of the worker, in the `Override` section, which wins over every file: environment: Tsak__Contexts__modulectx__Override__rabbit.password: ${RABBIT_PASSWORD} The key keeps its dots; only the section separators are `__`. `Tsak__Contexts__modulectx__Override__rabbit__password` would be a nested object and is not found by `{{rabbit.password}}`. Module deployment: https://github.com/redbase-app/redb-tsak/blob/main/MODULE_DEPLOYMENT.md ## Reference - XML markup: https://github.com/redbase-app/redb-route/blob/main/redb.Route.Xml/README.md - Expressions: https://github.com/redbase-app/redb-route/blob/main/EXPRESSIONS.md - A connector: `https://github.com/redbase-app/redb-route/blob/main/redb.Route./README.md` - `README.md` of this project - Documentation: https://redbase.app ## This template Path: redb/redb.Templates/templates/route-xml/_shared/.config/dotnet-tools.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/_shared/.config/dotnet-tools.json ---- { "version": 1, "isRoot": true, "tools": { "redb.route.xml.codegen": { "version": "4.8.0", "commands": [ "redb-route-xml" ], "rollForward": false } } } Path: redb/redb.Templates/templates/route-xml/_shared/Directory.Build.props Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/_shared/Directory.Build.props ---- net10.0 enable enable 4.8.0 false true Path: redb/redb.Templates/templates/route-xml/_shared/Directory.Build.targets Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/_shared/Directory.Build.targets ---- <_RoutePackageEntry Condition="'$(RoutePackageIncludeAssembly)' == 'true'"> --entry "$(TargetPath)" Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/.template.config/agents-scenario.md ---- AMQP 1.0 (`redb.Route.Amqp`, AMQPNetLite; ActiveMQ Artemis, ActiveMQ Classic, Qpid, Azure Service Bus, Amazon MQ), `routes/orders.route.xml`: a producer to the queue `orders`, a consumer of `orders` and a consumer of `orders.failed`. The connection is the bean `amqp` (`AmqpConnectionFactory`: Host, Port, User, Password, Ssl) in `context.xml`; every URI says `connectionFactory=amqp`. `onException` retries a failed message twice and then sends the original to `orders.failed`. Facts to keep: `routingType` `ANYCAST` (a queue, one consumer per message, the default) or `MULTICAST` (a topic, every subscriber); `credit` is the number of unsettled messages a consumer takes at a time; a message body may arrive as bytes, keep `` before JSON expressions; `amqp.password` is a required key from the environment. `deploy/docker-compose.amqp.yml` runs Artemis. Usually changed: the addresses, `routingType` for a topic, `filterSelector` for a selective consumer, the retry count, TLS on the bean. `routes/QuoteRpcRoute.cs` adds request-reply in C# on its own queue `cs.quotes` and timer: the client sends with `replyTo=true&timeout={{rpc.timeout:5}}` and reads the reply as the body of the next step; the server route ends with the reply as its body. Keep the server free of retries and of a handled `OnException`: a handled error would send an empty or stale reply, an unhandled one shows as the client's timeout. Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Amqp", "name": "redb.Route XML module: AMQP 1.0", "description": "AMQP 1.0 in XML markup: a producer, a consumer with retries, a queue for failed messages; request-reply in C#.", "shortName": "redb-route-amqp", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/README.md ---- # RouteModule A Tsak module that works with an AMQP 1.0 broker (ActiveMQ Artemis, ActiveMQ Classic, Qpid, Azure Service Bus, Amazon MQ and others), written in XML markup (`urn:redb:route:1.0`): | Route | What it does | |---|---| | `modulectx-orders-out` | sends a test order to the queue `orders` every 5 seconds; every fifth one has amount 0 | | `modulectx-orders-in` | reads `orders` and logs each order; an order with amount 0 fails | | `modulectx-orders-failed` | logs what ended up in the queue `orders.failed` | | `cs-modulectx-quote-client` | C#: asks for a price quote on the queue `cs.quotes` every 7 seconds and waits for the reply | | `cs-modulectx-quote-server` | C#: answers the quote requests of `cs.quotes` | A failed message is tried again twice, one second apart (`onException` in `routes/orders.route.xml`). If it still fails, the original message goes to `orders.failed` and the delivery is accepted, so one bad message does not block the queue. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `amqp` connection: host, port, user, password; the C# route builder | | `routes/orders.route.xml` | the three routes and the error handling | | `routes/QuoteRpcRoute.cs` | the request-reply routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.amqp.yml` | a local ActiveMQ Artemis, and the module on a Tsak worker | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `amqp://` option against the connector, the `amqp` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No broker is needed for the build. ## Try it with Artemis dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set AMQP_PASSWORD docker compose -f deploy/docker-compose.amqp.yml up -d The module log shows `order processed` every 5 seconds and, for every fifth order, two retries and `failed order`. The Artemis console is on http://localhost:8161. The module needs the broker up when it starts: a consumer that cannot reach it fails its route and the context. The compose file therefore starts the module only when Artemis answers on 5672 (`healthcheck` and `condition: service_healthy`); do the same in a deployment. ## Configuration | Key | Default | What | |---|---|---| | `amqp.host`, `amqp.port` | `localhost`, `5672` | the broker | | `amqp.user` | none, required | the user | | `amqp.password` | none, required | its password; from the environment | | `orders.period` | `5000` | the producer's interval, ms | | `rpc.period` | `7000` | quote request interval, ms | | `rpc.timeout` | `5` | how long the client waits for a reply, s | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__amqp.password: ${AMQP_PASSWORD} ## Request-reply in C# `routes/QuoteRpcRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. It uses the same `amqp` connection and its own timer and queue, so it never reads what the XML routes read. The log shows `quote requested: {"id":"quote-1","amount":1}` from the server and `quote received: {"id":"quote-1","gross":1.20}` from the client. The difference to notice: the client sends with `replyTo=true&timeout={{rpc.timeout:5}}`, so the send waits for the reply (the producer link gets a temporary reply address of its own, and the request a correlation id; no reply queue to declare) and the step after it reads the reply as the body. The server needs no option: a request carries its reply address, and the body the route ends with goes back. The server has no retries and no handled error on purpose; a request that fails is not delivered again, the client sees its timeout. ## Change it - **A topic.** `routingType=MULTICAST` on the producer and the consumers: every subscriber gets each message. - **Selective consumers.** `filterSelector=` with a JMS-style selector over the message properties. - **Parallelism.** `credit` (unsettled messages per consumer) and `concurrentConsumers`. - **TLS.** `Ssl` on the `amqp` bean (port 5671); `SslCertPath` for a client certificate. - **Several sends at once.** `transacted=true` sends all messages of an exchange in one broker transaction. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "amqp.user and amqp.password are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "amqp.host": "localhost", "amqp.port": "5672", "amqp.user": "modulectx", "orders.period": "5000", "rpc.period": "7000", "rpc.timeout": "5" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/deploy/docker-compose.amqp.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/deploy/docker-compose.amqp.yml ---- # A local AMQP 1.0 broker for the module: Apache ActiveMQ Artemis, and the module on a Tsak worker. A test stand, not # a deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set AMQP_PASSWORD # docker compose -f deploy/docker-compose.amqp.yml up -d # # Artemis creates the queues orders and orders.failed on first use. Its console: http://localhost:8161 (modulectx). name: modulectx-amqp services: artemis: image: apache/activemq-artemis:2.44.0 environment: ARTEMIS_USER: modulectx ARTEMIS_PASSWORD: ${AMQP_PASSWORD:?AMQP_PASSWORD required, see deploy/.env.example} ports: - "127.0.0.1:5672:5672" - "127.0.0.1:8161:8161" # Ready when the AMQP port answers; the module starts only then, so its consumers find the broker. healthcheck: test: ["CMD-SHELL", "bash -c 'echo > /dev/tcp/localhost/5672'"] interval: 5s timeout: 3s retries: 30 module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: artemis: condition: service_healthy environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__amqp.host=artemis - Tsak__Contexts__modulectx__Override__amqp.user=modulectx - Tsak__Contexts__modulectx__Override__amqp.password=${AMQP_PASSWORD:?AMQP_PASSWORD required, see deploy/.env.example} volumes: - ../pkg:/app/modules Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/routes/QuoteRpcRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/routes/QuoteRpcRoute.cs ---- using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace RouteModule.Routes; /// /// The request-reply half of the scenario in C#, next to the send, consume and retry routes of /// routes/orders.route.xml: a client asks for a price quote on the queue cs.quotes and waits for the reply, a server /// answers it. Its own timer and its own queue, the same amqp connection bean. /// public sealed class QuoteRpcRoute : RouteBuilder { protected override void Configure() { // Client: every {{rpc.period:7000}} ms a quote request. replyTo=true makes the send a request-reply: the // connector sends with a temporary reply address of its own and a correlation id, waits up to // {{rpc.timeout:5}} seconds and puts the reply into the exchange, so the next step reads the reply as the body. From("timer://cs-modulectx-quotes?period={{rpc.period:7000}}") .RouteId("cs-modulectx-quote-client") .Description("Asks for a price quote and waits for the reply") // No reply in time: the server failed or is not running. Logged, the next tick asks again. .OnException() .Handled() .Log("no quote within the timeout: ${exception.message}", LogLevel.Warning) .EndOnException() .SetBody(Expr("""{"id":"quote-${header.CamelTimerCounter}","amount":${header.CamelTimerCounter}}""")) .To("amqp://cs.quotes?connectionFactory=amqp&contentType=application/json&replyTo=true&timeout={{rpc.timeout:5}}") .ConvertBody(typeof(string)) .Log("quote received: ${body}"); // Server: a request on cs.quotes carries a reply address, so the connector sends the body this route ends // with back to the client. No retries and no handled error here: a failed request is not delivered again, // the client sees its timeout instead. From("amqp://cs.quotes?connectionFactory=amqp") .RouteId("cs-modulectx-quote-server") .Description("Answers a price quote request") .ConvertBody(typeof(string)) .Log("quote requested: ${body}") // The reply is the last body of the route. .Process(exchange => exchange.In.Body = Quote((string)exchange.In.Body!)); } // The quote of a request {"id":..,"amount":..}: the amount with 20 % VAT. private static string Quote(string request) { using var json = JsonDocument.Parse(request); var id = json.RootElement.GetProperty("id").GetString(); var amount = json.RootElement.GetProperty("amount").GetDecimal(); var gross = Math.Round(amount * 1.20m, 2).ToString(CultureInfo.InvariantCulture); return $$"""{"id":"{{id}}","gross":{{gross}}}"""; } } Path: redb/redb.Templates/templates/route-xml/redb-route-amqp/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-amqp/routes/orders.route.xml ---- moved to orders.failed: ${exception.message} order processed: ${body} failed order: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-as2/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/.template.config/agents-scenario.md ---- AS2 (`redb.Route.As2`, RFC 4130), `routes/send.route.xml` and `routes/receive.route.xml`: `context.xml` holds our key pair (`as2-key`, PKCS#12), the partner's certificate (`partner-cert`), the agreement `partner` (`As2ConnectionFactory`: `As2From` us, `As2To` the partner, `PartnerUrl`, sign, encrypt, signed MDN, `RequireValidMdn`) and the duplicate memory `as2-received`. The sender posts with `as2:/send?connectionFactory=partner` and reads `redbAs2.mdnDisposition` and `redbAs2.mdnMicStatus`; the receiver listens on `as2:/as2/inbound?port={{as2.port:4080}}&connectionFactory=partner&idempotentRepository=as2-received`. Facts to keep: with a connection factory every agreement option lives on the factory, the URI carries none; the partner certificate is pinned; `as2.keyFile`, `as2.keyPassword` and `as2.partnerCertificateFile` are required keys and the password comes from the environment; `deploy/docker-compose.openas2.yml` makes test keys and runs OpenAS2 4.9.0 as the partner (`deploy/openas2/partnerships.xml`). Usually changed: the identifiers, the partner URL, the algorithms, the source of the documents (a file or SFTP consumer instead of the timer), what the receiver does with a document. `routes/InvoiceSendRoute.cs` is a second sender in C# on its own timer (`as2.invoicePeriod`) under the same agreement: an XML invoice from LINQ to XML, `exchange.In.ContentType = "application/xml"`, its own `OnException` with two retries, and a branch on `As2Headers.MdnConfirmed`. One `as2:` receiver per path: keep it in XML. Path: redb/redb.Templates/templates/route-xml/redb-route-as2/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.As2", "name": "redb.Route XML module: AS2", "description": "AS2 in XML markup: a signed, encrypted send with a verified MDN, a receiver with duplicate detection; invoices in C#.", "shortName": "redb-route-as2", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env", "deploy/keys/**", "deploy/openas2/config/**", "deploy/openas2/data/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-as2/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/README.md ---- # RouteModule A Tsak module that exchanges documents over AS2 (RFC 4130), written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-as2-send` | every minute signs and encrypts a test document and posts it to the partner; the call returns when the partner's signed MDN has been verified and its MIC matched; no confirmation is retried twice, then logged | | `modulectx-as2-receive` | listens on port 4080 at `/as2/inbound`, decrypts, verifies the partner's signature, answers with the MDN the partner asked for; a resend with the same `Message-ID` gets its MDN again and is not delivered twice | | `cs-modulectx-as2-invoice` | C#: every 90 seconds an XML invoice under the same agreement, with the same retries; logs whether the MDN confirmed it | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | our key pair, the partner's certificate, the agreement `partner` (`As2ConnectionFactory`) and the duplicate memory; the C# route builder | | `routes/send.route.xml`, `routes/receive.route.xml` | the two directions | | `routes/InvoiceSendRoute.cs` | the invoice sender in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.openas2.yml` | a local exchange: test keys, OpenAS2 4.9.0 as the partner, the module on a Tsak worker | | `deploy/openas2/partnerships.xml` | the OpenAS2 side of the agreement | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the `as2:` options, the beans and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No partner is needed for the build. ## Try it with OpenAS2 dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set AS2_KEY_PASSWORD docker compose -f deploy/docker-compose.openas2.yml up -d The `certs` service makes the test key pairs once (`deploy/keys`, `deploy/openas2/config`). The module log shows `sent <...>: automatic-action/MDN-sent-automatically; processed, MIC matched` every minute. For the other direction put a file into `deploy/openas2/data/outbox/modulectx`: OpenAS2 signs, encrypts and posts it, the module logs `received <...> from openas2, signature valid True` and answers with a signed MDN. ## Configuration | Key | Default | What | |---|---|---| | `as2.keyFile` | none, required | our PKCS#12 key pair | | `as2.keyPassword` | none, required | its password; from the environment | | `as2.partnerCertificateFile` | none, required | the partner's certificate (PEM or DER) | | `as2.ourId` | `modulectx` | our AS2 identifier | | `as2.partnerId` | `openas2` | the partner's AS2 identifier | | `as2.partnerUrl` | `http://openas2:10080` | where we post | | `as2.port` | `4080` | where we listen | | `as2.sendPeriod` | `60000` | the test sender's interval, ms | | `as2.invoicePeriod` | `90000` | the C# invoice sender's interval, ms | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__as2.keyPassword: ${AS2_KEY_PASSWORD} ## Invoices in C# `routes/InvoiceSendRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own it sends an XML invoice through the same agreement `partner`, signed and encrypted like the X12 document, with the same two retries. The log shows `invoice <...@redb.route>: delivered and confirmed` next to the XML sender's lines. The difference to notice: C# builds the invoice with LINQ to XML, sets the MIME type of the document on the message (`exchange.In.ContentType = "application/xml"`) and branches on the typed outcome of the MDN, `As2Headers.MdnConfirmed`, instead of logging the disposition text. ## Change it - **A real partner.** Its identifier, URL and certificate; the algorithms (`SignAlg`, `EncryptAlg`) and `Compress` as agreed. `sha-1` and `3des` need `AllowLegacyAlgorithms`. - **Asynchronous MDN.** `MdnMode` `Async` with `AsyncMdnUrl` on send and an `as2:` endpoint with `mode=mdn`; `AsyncMdnAllowedHosts` on receive. - **TLS.** `as2s://` to send over HTTPS; `useTls` with `sslCertPath` on the receiver, a certificate of its own, not the S/MIME key. - **Documents.** Replace the timer with `file://`, `sftp://` or a queue, and the receiver's log with the real work. - **Duplicates across restarts.** `as2-received` keeps the ids in memory; a durable repository keeps them. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-as2/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-as2/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "as2.keyFile, as2.keyPassword and as2.partnerCertificateFile are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "as2.keyFile": "/app/keys/module.p12", "as2.partnerCertificateFile": "/app/keys/openas2.crt", "as2.ourId": "modulectx", "as2.partnerId": "openas2", "as2.partnerUrl": "http://openas2:10080", "as2.port": "4080", "as2.sendPeriod": "60000", "as2.invoicePeriod": "90000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-as2/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-as2/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-as2/deploy/docker-compose.openas2.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/deploy/docker-compose.openas2.yml ---- # A local AS2 exchange: the module on a Tsak worker, OpenAS2 as its trading partner. A test stand with test keys made # on the spot, not a deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set AS2_KEY_PASSWORD # docker compose -f deploy/docker-compose.openas2.yml up -d # # certs runs first and once: keytool writes the module's key pair to deploy/keys, and OpenAS2's configuration to # deploy/openas2/config (the image's own template, partnerships.xml of this folder, a keystore with OpenAS2's key pair # and the module's certificate); it leaves them alone when they are there. The module sends to http://openas2:10080, # OpenAS2 sends to http://module:4080/as2/inbound; both stay inside the compose network. # OpenAS2 -> module: put a file into deploy/openas2/data/outbox/modulectx. name: modulectx-as2 services: certs: image: greicodex/openas2:4.9.0 environment: - AS2_KEY_PASSWORD=${AS2_KEY_PASSWORD:?AS2_KEY_PASSWORD required, see deploy/.env.example} volumes: - ./keys:/keys - ./openas2/config:/openas2-config - ./openas2/partnerships.xml:/partnerships.xml:ro # Test key pairs, RSA 2048, two years. The module: PKCS#12 with AS2_KEY_PASSWORD. OpenAS2: as2_certs.p12 with the # password its config.xml expects (testas2), holding its key pair and the module's certificate. entrypoint: ["sh", "-ec"] command: - | if [ -f /keys/module.p12 ] && [ -f /openas2-config/as2_certs.p12 ]; then echo "keys present"; exit 0; fi rm -rf /keys/module.p12 /keys/module.crt /keys/openas2.crt /openas2-config/* cp -r /opt/openas2/config_template/. /openas2-config/ cp /partnerships.xml /openas2-config/partnerships.xml rm -f /openas2-config/as2_certs.p12 keytool -genkeypair -alias module -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -validity 730 \ -dname "CN=module.example, O=Test only" \ -keystore /keys/module.p12 -storetype PKCS12 -storepass "$$AS2_KEY_PASSWORD" keytool -exportcert -rfc -alias module -keystore /keys/module.p12 -storetype PKCS12 \ -storepass "$$AS2_KEY_PASSWORD" -file /keys/module.crt keytool -genkeypair -alias openas2 -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -validity 730 \ -dname "CN=openas2.example, O=Test only" \ -keystore /openas2-config/as2_certs.p12 -storetype PKCS12 -storepass testas2 keytool -exportcert -rfc -alias openas2 -keystore /openas2-config/as2_certs.p12 -storetype PKCS12 \ -storepass testas2 -file /keys/openas2.crt keytool -importcert -noprompt -alias module -file /keys/module.crt \ -keystore /openas2-config/as2_certs.p12 -storetype PKCS12 -storepass testas2 chmod -R a+rwX /keys /openas2-config echo "keys written" openas2: image: greicodex/openas2:4.9.0 depends_on: certs: condition: service_completed_successfully volumes: - ./openas2/config:/opt/openas2/config - ./openas2/data:/opt/openas2/data module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: certs: condition: service_completed_successfully ports: - "127.0.0.1:4080:4080" # the AS2 receiver, for a partner on this machine environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__as2.keyFile=/app/keys/module.p12 - Tsak__Contexts__modulectx__Override__as2.keyPassword=${AS2_KEY_PASSWORD:?AS2_KEY_PASSWORD required, see deploy/.env.example} - Tsak__Contexts__modulectx__Override__as2.partnerCertificateFile=/app/keys/openas2.crt - Tsak__Contexts__modulectx__Override__as2.partnerUrl=http://openas2:10080 volumes: - ../pkg:/app/modules - ./keys:/app/keys:ro Path: redb/redb.Templates/templates/route-xml/redb-route-as2/deploy/openas2/partnerships.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/deploy/openas2/partnerships.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-as2/routes/InvoiceSendRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/routes/InvoiceSendRoute.cs ---- using System.Xml.Linq; using Microsoft.Extensions.Logging; using redb.Route.As2; using redb.Route.Core; namespace RouteModule.Routes; /// /// A sibling of routes/send.route.xml in C#: an XML invoice instead of the X12 test document, sent on a timer of its /// own under the same partner agreement. The route reads the outcome of the MDN as a typed value. /// public sealed class InvoiceSendRoute : RouteBuilder { protected override void Configure() { // The partner did not answer, or its MDN did not confirm the transfer: sent again twice, half a minute apart. OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromSeconds(30)) .Handled() .Log("the partner did not confirm the invoice: ${exception.message}", LogLevel.Error); // Every {{as2.invoicePeriod:90000}} ms an invoice, signed and encrypted for the partner like the XML document. From("timer://cs-modulectx-as2-invoice?period={{as2.invoicePeriod:90000}}") .RouteId("cs-modulectx-as2-invoice") .Description("Sends a test XML invoice to the AS2 partner") .Process(exchange => { var number = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); exchange.In.Headers[As2Headers.Subject] = $"invoice {number}"; // The MIME type of the document inside the signed and encrypted message. exchange.In.ContentType = "application/xml"; exchange.In.Body = new XElement("invoice", new XAttribute("number", $"INV-{number}"), new XElement("line", new XAttribute("sku", "A-1"), new XAttribute("qty", 2), new XAttribute("price", "9.50")), new XElement("total", "19.00")).ToString(SaveOptions.DisableFormatting); }) .To("as2:/send?connectionFactory=partner") .Process(exchange => { // MdnConfirmed: positive disposition, matching MIC and a valid signature where the agreement asks for one. var confirmed = exchange.In.Headers[As2Headers.MdnConfirmed] is true; exchange.In.Body = confirmed ? "delivered and confirmed" : "MDN did not confirm"; }) .Log("invoice ${header.Message-ID}: ${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-as2/routes/receive.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/routes/receive.route.xml ---- received ${header.Message-ID} from ${header.AS2-From}, signature valid ${header.redbAs2.signatureValid}: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-as2/routes/send.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as2/routes/send.route.xml ---- the partner did not confirm the document: ${exception.message} sent ${header.Message-ID}: ${header.redbAs2.mdnDisposition}, MIC ${header.redbAs2.mdnMicStatus} Path: redb/redb.Templates/templates/route-xml/redb-route-as4/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/.template.config/agents-scenario.md ---- AS4, eDelivery AS4 1.16 common profile (`redb.Route.As4`). `routes/send.route.xml`: a timer sends a test document with `as4:?connectionFactory=as4-node&partner=partner` to the `Address` of the agreement; `routes/receive.route.xml`: `as4:/as4/in` on port 4090. Beans in `context.xml`: `as4-key` (our PKCS#12 key pair), `partner-cert`, `partner` (`As4Partner`, the agreement), `as4-node` (`As4ConnectionFactory`), `as4-received` (ids of received messages). Facts to keep: the answer is a signed receipt in the HTTP response, there is no MDN (that is AS2); signing, encryption and compression are mandated by the profile; keys and certificates come from files named by configuration keys, never from the markup; the partner's ebMS error (`As4ErrorSignalException`) is not retried. Keys: `as4.keyFile`, `as4.keyPassword`, `as4.partnerCertificateFile` required, the rest have defaults. `deploy/docker-compose.holodeck.yml` is a test stand with Holodeck B2B as the partner, not a deployment. Usually changed: the source of the documents, the receiving route's work, more `As4Partner` beans, `PartnerTrustAnchors` (trust in a certification authority) instead of a pinned certificate. `routes/CreditNoteSendRoute.cs` is a second sender in C# on its own timer (`as4.creditNotePeriod`) to the same partner: `exchange.In.ContentType = "application/xml"` gives the payload its MimeType, and its own two `OnException` blocks repeat the reception awareness of `send.route.xml` (that file's handlers cover XML routes only). One `as4:` receiver per path: keep it in XML. Path: redb/redb.Templates/templates/route-xml/redb-route-as4/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.As4", "name": "redb.Route XML module: AS4", "description": "AS4 (eDelivery) in XML markup: a signed, encrypted send with its receipt, a receiver; credit notes sent from C#.", "shortName": "redb-route-as4", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env", "deploy/keys/**", "deploy/holodeck/certs/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-as4/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/README.md ---- # RouteModule A Tsak module that exchanges documents over AS4 (eDelivery AS4 1.16 common profile), written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-as4-send` | sends a test invoice to the partner every minute and logs the partner's receipt | | `modulectx-as4-receive` | receives the partner's messages on `POST /as4/in`, port 4090, and logs them | | `cs-modulectx-as4-credit-note` | C#: sends a test credit note to the same partner every 90 seconds, as `application/xml`, with the same reception awareness | Every message is signed, its payload compressed and encrypted for the partner. The answer is a signed non-repudiation receipt in the same HTTP response: AS4 has no MDN (that is AS2), and the send step returns only when the receipt has been verified. A send without a receipt is tried again twice, half a minute apart, with the same message id; the receiver gives a repeated message its receipt again and does not deliver it twice. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | our node (`as4-node`): party id and key pair; the agreement with the partner (`partner`); the received-ids store; the C# route builder | | `routes/send.route.xml` | the sending route and its error handling | | `routes/receive.route.xml` | the receiving route | | `routes/CreditNoteSendRoute.cs` | the credit note sender in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.holodeck.yml` | a local exchange: test keys, the module on a Tsak worker, Holodeck B2B as the partner | | `deploy/holodeck/` | Holodeck's image, certificate manager, P-Modes and a message to submit | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `as4:` option against the connector, the beans and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No partner and no keys are needed for the build. ## Run a local exchange The partner is [Holodeck B2B](https://github.com/holodeck-b2b/Holodeck-B2B) 8.1.1, an open source AS4 message service handler. `deploy/` is a test stand: keys made on the spot, fixed test passwords in Holodeck's configuration, no TLS. It is not a deployment, and the Holodeck image it builds is not one for production. 1. `cp deploy/.env.example deploy/.env` and set `AS4_KEY_PASSWORD`. 2. `docker compose -f deploy/docker-compose.holodeck.yml up -d --build` The `certs` service writes the module's key pair to `deploy/keys` and Holodeck's keystores to `deploy/holodeck/certs`, once. The Holodeck image is built from the release archive, checked against its SHA-256 (`deploy/holodeck/Dockerfile`). 3. Module to Holodeck: the worker log shows `sent , receipt ` every minute, and Holodeck stores each message it took: docker compose -f deploy/docker-compose.holodeck.yml logs -f module docker compose -f deploy/docker-compose.holodeck.yml exec holodeck ls data/msg_in Holodeck starts in about half a minute; a send before that fails and is retried. 4. Holodeck to the module: submit the sample message. docker compose -f deploy/docker-compose.holodeck.yml exec holodeck sh -c "cp samples/invoice-1.xml data/msg_out/ && cp samples/invoice-1.mmd data/msg_out/" The worker log shows `received ... from partner`; Holodeck writes the module's receipt to `data/msg_in` once it has verified it. `docker compose -f deploy/docker-compose.holodeck.yml down` stops it; delete `deploy/keys` and `deploy/holodeck/certs` for new keys. ## Deploy 1. Our key pair: a PKCS#12 file with the certificate the partner knows. The partner's certificate: a file (`.cer`, `.crt`, PEM or DER). 2. Give the context its configuration: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. The key password goes through the environment, `Tsak__Contexts__modulectx__Override__as4.keyPassword`. 3. Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). 4. Publish the receiver to partners over HTTPS: a reverse proxy that terminates TLS in front of port 4090. ## Configuration | Key | Default | What | |---|---|---| | `as4.keyFile` | none, required | our key pair, PKCS#12 | | `as4.keyPassword` | none, required | its password; from an environment variable | | `as4.partnerCertificateFile` | none, required | the partner's certificate: verifies its signatures, we encrypt for it | | `as4.ourPartyId` | `urn:redb:example:module` | our `eb:PartyId` | | `as4.hostName` | `module.example` | the host part of the message ids we make: the public name of the access point | | `as4.partnerPartyId` | `urn:redb:example:holodeck` | the partner's `eb:PartyId` | | `as4.partnerAddress` | `http://holodeck:8080/holodeckb2b/as4` | the partner's address, `http://` or `https://`, with a query where it has one (a Domibus domain, `?domain=name`): the `Address` of the agreement | | `as4.agreement` | `urn:redb:example:agreement` | `eb:AgreementRef`; the partner selects its P-Mode by it | | `as4.service` | `urn:redb:example:as4` | `eb:Service` | | `as4.action` | `StoreMessage` | `eb:Action` | | `as4.port` | `4090` | the receiver's port | | `as4.sendPeriod` | `60000` | the test sender's interval, ms | | `as4.creditNotePeriod` | `90000` | the C# credit note sender's interval, ms | ## Credit notes in C# `routes/CreditNoteSendRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own it sends a credit note through the same node `as4-node` to the same partner, with the same two redeliveries when no receipt comes and none after an ebMS error. The log shows `sent credit note , receipt ` next to the XML sender's lines. The difference to notice: C# sets the content type on the message (`exchange.In.ContentType = "application/xml"`), so the payload travels with `MimeType` `application/xml` where the XML sender's goes as `application/octet-stream`; the document comes from LINQ to XML, and the error handlers name the exception types as types (`As4ReceiptException`, `As4ErrorSignalException`). ## Change it - **The document.** Replace the timer and `setBody` in `routes/send.route.xml` with the real source (a file consumer, a queue, an HTTP call). The content type the source gives the body travels as the `MimeType` part property; a body set in the route goes as `application/octet-stream`. - **The receiving side.** Replace the log in `routes/receive.route.xml` with the real work. The receipt goes when the route has finished; a failure answers the partner with an ebMS error, and the partner resends. - **More partners.** One `As4Partner` bean per partner in the node's `Partners`; `partner=` on a sending endpoint picks one, the receiver finds it by the party id and the agreement. - **Trust in a certification authority** instead of a pinned certificate: `PartnerTrustAnchors` on the partner, with revocation checks on the node. See the `redb.Route.As4` README. - **Four corner topology.** `RequireFourCornerProperties` is off for a point-to-point exchange; turn it on where `originalSender` and `finalRecipient` are required. - **Received ids that survive a restart.** Replace the `as4-received` bean with the redb-stored repository shown in `context.xml`. A complete access point that passes the eDelivery conformance scenarios is in the redb.Route repository, `demos/As4ConformanceDemo`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-as4/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-as4/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "as4.keyFile, as4.keyPassword and as4.partnerCertificateFile are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "as4.keyFile": "/app/keys/module.p12", "as4.partnerCertificateFile": "/app/keys/holodeck.crt", "as4.ourPartyId": "urn:redb:example:module", "as4.hostName": "module.example", "as4.partnerPartyId": "urn:redb:example:holodeck", "as4.partnerAddress": "http://holodeck:8080/holodeckb2b/as4", "as4.agreement": "urn:redb:example:agreement", "as4.service": "urn:redb:example:as4", "as4.action": "StoreMessage", "as4.port": "4090", "as4.sendPeriod": "60000", "as4.creditNotePeriod": "90000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-as4/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-as4/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/docker-compose.holodeck.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/docker-compose.holodeck.yml ---- # A local AS4 exchange: the module on a Tsak worker, Holodeck B2B as its trading partner. A test stand with test # keys made on the spot, not a deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set AS4_KEY_PASSWORD # docker compose -f deploy/docker-compose.holodeck.yml up -d --build # # certs runs first and once: keytool writes the module's key pair to deploy/keys and Holodeck's keystores to # deploy/holodeck/certs, and leaves them alone when they are there. The module sends to http://holodeck:8080, Holodeck # sends to http://module:4090/as4/in; both stay inside the compose network. name: modulectx-as4 services: certs: image: eclipse-temurin:17-jre environment: - AS4_KEY_PASSWORD=${AS4_KEY_PASSWORD:?AS4_KEY_PASSWORD required, see deploy/.env.example} volumes: - ./keys:/keys - ./holodeck/certs:/holodeck-certs # Test key pairs, RSA 2048, two years. The module: PKCS#12 with AS4_KEY_PASSWORD. Holodeck: the three JKS stores # of its certificate manager, passwords as in holodeck/conf/certmanager_config.xml and the P-Modes. entrypoint: ["sh", "-ec"] command: - | if [ -f /keys/module.p12 ] && [ -f /holodeck-certs/privatekeys.jks ]; then echo "keys present"; exit 0; fi rm -f /keys/module.p12 /keys/module.crt /keys/holodeck.crt /holodeck-certs/*.jks keytool -genkeypair -alias module -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -validity 730 \ -dname "CN=module.example, O=Test only" \ -keystore /keys/module.p12 -storetype PKCS12 -storepass "$$AS4_KEY_PASSWORD" keytool -exportcert -rfc -alias module -keystore /keys/module.p12 -storetype PKCS12 \ -storepass "$$AS4_KEY_PASSWORD" -file /keys/module.crt keytool -genkeypair -alias holodeck -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -validity 730 \ -dname "CN=holodeck.example, O=Test only" \ -keystore /holodeck-certs/privatekeys.jks -storetype JKS -storepass test-only-private -keypass test-only-key keytool -exportcert -rfc -alias holodeck -keystore /holodeck-certs/privatekeys.jks -storetype JKS \ -storepass test-only-private -file /keys/holodeck.crt keytool -importcert -noprompt -alias module -file /keys/module.crt \ -keystore /holodeck-certs/partnerkeys.jks -storetype JKS -storepass test-only-partners keytool -importcert -noprompt -alias module -file /keys/module.crt \ -keystore /holodeck-certs/trustedcerts.jks -storetype JKS -storepass test-only-trusted chmod 644 /keys/* /holodeck-certs/* echo "keys written" holodeck: build: ./holodeck image: modulectx-holodeck:8.1.1 depends_on: certs: condition: service_completed_successfully volumes: - ./holodeck/conf/certmanager_config.xml:/opt/holodeckb2b/conf/certmanager_config.xml:ro - ./holodeck/pmodes:/opt/holodeckb2b/repository/pmodes:ro - ./holodeck/certs:/opt/holodeckb2b/repository/certs:ro - ./holodeck/samples:/opt/holodeckb2b/samples:ro module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: certs: condition: service_completed_successfully ports: - "127.0.0.1:4090:4090" # the AS4 receiver, for a partner on this machine environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__as4.keyFile=/app/keys/module.p12 - Tsak__Contexts__modulectx__Override__as4.keyPassword=${AS4_KEY_PASSWORD:?AS4_KEY_PASSWORD required, see deploy/.env.example} - Tsak__Contexts__modulectx__Override__as4.partnerCertificateFile=/app/keys/holodeck.crt - Tsak__Contexts__modulectx__Override__as4.partnerAddress=http://holodeck:8080/holodeckb2b/as4 volumes: - ../pkg:/app/modules - ./keys:/app/keys:ro Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/Dockerfile Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/Dockerfile ---- # syntax=docker/dockerfile:1.7 # Holodeck B2B, an open source AS4 message service handler, as the partner of a local test exchange. # A test stand, not an image for production. Holodeck publishes no image of its own; this one is built from the # release distribution, pinned by version and by the SHA-256 of the archive (the digest GitHub lists for the asset). # Holodeck B2B is GPLv3: the module only talks to it over HTTP, nothing of it is linked. FROM alpine:3.20 AS dist ARG HB2B_VERSION=8.1.1 ADD --checksum=sha256:a63355fc02dab653102f47769ecf877d6619779f9dfca6bff3539b42b3fabc02 \ https://github.com/holodeck-b2b/Holodeck-B2B/releases/download/v${HB2B_VERSION}/holodeckb2b-distribution-${HB2B_VERSION}.zip \ /tmp/holodeckb2b.zip RUN unzip -q /tmp/holodeckb2b.zip -d /tmp \ && mv /tmp/holodeckb2b-${HB2B_VERSION} /opt/holodeckb2b \ && chmod +x /opt/holodeckb2b/bin/*.sh FROM eclipse-temurin:17-jre COPY --from=dist /opt/holodeckb2b /opt/holodeckb2b ENV HB2B_HOME=/opt/holodeckb2b WORKDIR /opt/holodeckb2b EXPOSE 8080 CMD ["/opt/holodeckb2b/bin/startServer.sh"] Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/conf/certmanager_config.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/conf/certmanager_config.xml ---- true repository/certs/privatekeys.jks test-only-private repository/certs/partnerkeys.jks test-only-partners repository/certs/trustedcerts.jks test-only-trusted Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/pmodes/holodeck-to-module.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/pmodes/holodeck-to-module.xml ---- holodeck-to-module http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push urn:redb:example:holodeck http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/initiator holodeck BSTReference http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 http://www.w3.org/2001/04/xmlenc#sha256 urn:redb:example:module http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/responder module module http://www.w3.org/2009/xmlenc11#aes128-gcm http://www.w3.org/2009/xmlenc11#rsa-oaep http://www.w3.org/2009/xmlenc11#mgf1sha256 http://www.w3.org/2001/04/xmlenc#sha256 BSTReference urn:redb:example:agreement
http://module:4090/as4/in
RESPONSE true 2 30 org.holodeckb2b.backend.file.NotifyAndDeliverOperation format ebms deliveryDirectory data/msg_in StoreMessage urn:redb:example:as4 true
Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/pmodes/module-to-holodeck.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/pmodes/module-to-holodeck.xml ---- module-to-holodeck http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push urn:redb:example:module http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/initiator module urn:redb:example:holodeck http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/responder holodeck BSTReference http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 http://www.w3.org/2001/04/xmlenc#sha256 holodeck urn:redb:example:agreement RESPONSE false org.holodeckb2b.backend.file.NotifyAndDeliverOperation format ebms deliveryDirectory data/msg_in StoreMessage urn:redb:example:as4 Path: redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/samples/invoice-1.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/deploy/holodeck/samples/invoice-1.xml ---- H-1 Path: redb/redb.Templates/templates/route-xml/redb-route-as4/routes/CreditNoteSendRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/routes/CreditNoteSendRoute.cs ---- using System.Xml.Linq; using Microsoft.Extensions.Logging; using redb.Route.As4; using redb.Route.Core; namespace RouteModule.Routes; /// /// A sibling of routes/send.route.xml in C#: credit notes, sent on a timer of their own to the same partner under the /// same agreement, with the same reception awareness. The payload carries its MIME type, so the partner gets /// application/xml instead of application/octet-stream. /// public sealed class CreditNoteSendRoute : RouteBuilder { private static readonly XNamespace Ns = "urn:example:credit-note"; protected override void Configure() { // No signed receipt came back: the same message is sent again twice, half a minute apart, then logged. OnException(typeof(As4ReceiptException), typeof(HttpRequestException)) .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromSeconds(30)) .Handled() .Log("no receipt from the partner for ${header.redbAs4.messageId}: ${exception.message}", LogLevel.Error); // The partner refused the message with an ebMS error: its answer, not redelivered. OnException() .Handled() .Log("the partner refused ${header.redbAs4.messageId}: ${exception.message}", LogLevel.Error); // Every {{as4.creditNotePeriod:90000}} ms a credit note, signed, compressed and encrypted like the invoice. From("timer://cs-modulectx-as4-credit-note?period={{as4.creditNotePeriod:90000}}") .RouteId("cs-modulectx-as4-credit-note") .Description("Sends a test credit note to the AS4 partner") .Process(exchange => { var number = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); // The content type travels as the MimeType part property of the payload. exchange.In.ContentType = "application/xml"; exchange.In.Body = new XElement(Ns + "creditNote", new XElement(Ns + "number", $"CN-{number}"), new XElement(Ns + "amount", "12.50")).ToString(SaveOptions.DisableFormatting); }) .To("as4:?connectionFactory=as4-node&partner=partner") .Log("sent credit note ${header.redbAs4.messageId}, receipt ${header.redbAs4.receiptMessageId}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-as4/routes/receive.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/routes/receive.route.xml ---- received ${header.redbAs4.messageId} from ${header.redbAs4.partner} (${header.redbAs4.service} / ${header.redbAs4.action}): ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-as4/routes/send.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-as4/routes/send.route.xml ---- no receipt from the partner for ${header.redbAs4.messageId}: ${exception.message} the partner refused ${header.redbAs4.messageId}: ${exception.message} sent ${header.redbAs4.messageId}, receipt ${header.redbAs4.receiptMessageId} Path: redb/redb.Templates/templates/route-xml/redb-route-beans/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/.template.config/agents-scenario.md ---- C# beans, `Beans/PriceCalculator.cs` and `routes/orders.route.xml`: `context.xml` declares `` with a `` and a ``. The route calls `` (arguments are expressions, the return value becomes the body; the same endpoint as `bean:#pricing?method=Gross(...)`), `` (a method that takes `IExchange`) and, in a condition, `` (the expression function: no `#`, bare arguments, and the method must be synchronous; a `Task` method is refused there and belongs in a step). Facts to keep: `RoutePackageIncludeAssembly` in the `.csproj` puts this project's assembly into the package; a constructor argument needs `type=` when the parameter is not a string; a bean with a dependency the XML cannot build stays out of XML and is registered by code. An exception the bean throws is an ordinary route failure (`onException` here). `routes/QuotesRoute.cs` is a second route in C# (`cs-modulectx-quotes`, its own timer `{{quotes.period:10000}}`) that takes the same bean from the registry, `exchange.Context.GetFromRegistry("pricing")`, and calls `Gross` and `Stamp` as typed methods. Usually changed: the class itself, more methods, more beans in `context.xml`. Path: redb/redb.Templates/templates/route-xml/redb-route-beans/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Beans", "name": "redb.Route XML module: C# beans", "description": "XML routes that call a C# class of the project: a bean from configuration, method calls; a second route in C#.", "shortName": "redb-route-beans", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-beans/Beans/PriceCalculator.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/Beans/PriceCalculator.cs ---- using System.Globalization; using redb.Route.Abstractions; namespace RouteModule.Beans; /// /// A bean of the module: logic that does not belong in markup. context.xml builds one instance /// from configuration (constructor argument and property); the routes call its methods through the /// <bean ref="#pricing" method="..."/> step, the bean:#pricing?method=... URI and the /// bean:pricing.Method(...) expression function. /// public sealed class PriceCalculator { /// Creates the calculator with the VAT rate, for example 0.20. public PriceCalculator(decimal vatRate) { if (vatRate < 0) throw new ArgumentOutOfRangeException(nameof(vatRate), "The VAT rate cannot be negative."); VatRate = vatRate; } /// The VAT rate the gross prices include. public decimal VatRate { get; } /// The currency written on every order; set from configuration. public string Currency { get; set; } = "EUR"; /// /// The gross amount of an order line. Called with method="Gross(${header.qty}, ${header.price})": /// each argument is an expression, converted to the parameter type; the result becomes the body. /// public decimal Gross(int qty, decimal price) { if (qty <= 0) throw new ArgumentOutOfRangeException(nameof(qty), "The quantity must be positive."); return Math.Round(qty * price * (1 + VatRate), 2, MidpointRounding.AwayFromZero); } /// The quantity from which an order line counts as bulk. public int BulkQuantity { get; set; } = 3; /// /// Whether an order line is a bulk line. Called in a condition as bean:pricing.IsBulk(header.qty): /// a method the expression language calls must be synchronous, a Task is refused there. /// public bool IsBulk(int qty) => qty >= BulkQuantity; /// /// Writes the currency and the VAT rate into the headers. Called as method=Stamp: a method /// that takes the exchange reads and changes it directly; a void method leaves the body alone. /// public void Stamp(IExchange exchange) { exchange.In.Headers["currency"] = Currency; exchange.In.Headers["vat"] = VatRate.ToString(CultureInfo.InvariantCulture); } } Path: redb/redb.Templates/templates/route-xml/redb-route-beans/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/README.md ---- # RouteModule A Tsak module whose XML routes (`urn:redb:route:1.0`) call a C# class of the project. Logic that does not belong in markup lives in `Beans/`; `context.xml` builds the object from configuration and the routes call its methods. It needs no broker. | Part | What it shows | |---|---| | `Beans/PriceCalculator.cs` | a plain class: a constructor with the VAT rate, a `Currency` property, three methods | | `context.xml` | `` with `` and ``, values from configuration | | `routes/orders.route.xml` | the step ``: arguments are expressions, the result becomes the body; the URI `bean:#pricing?method=Stamp`: the method takes the exchange and sets headers; ``: a bean method in a condition | The log shows `order order-1: 2 x 12.50 + VAT 0.20 = 30.00 EUR`, `order order-2 is a bulk line: 3 pieces` for a line of three and, for every fifth order, `order order-4 refused: The quantity must be positive.`, an exception of the bean handled by `onException`. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `Beans/PriceCalculator.cs` | the bean | | `context.xml` | the `pricing` bean and the C# route builder | | `routes/orders.route.xml` | the route and the error handling | | `routes/QuotesRoute.cs` | a second route in C#, with the same bean | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration: `pricing.vat`, `pricing.currency`, `orders.period`, `quotes.period` | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## The same bean from C# `routes/QuotesRoute.cs` is a `RouteBuilder` next to the XML route: price quotes on a timer of its own (`{{quotes.period:10000}}`), with the same `pricing` bean of `context.xml` and the same kind of error handling. `context.xml` adds it with ``. The log shows `quote quote-1: 2 x 8.00 + VAT 0.20 = 19.20 EUR` and, for every fourth quote, `quote quote-3 refused: ...`. The difference to notice: XML calls the bean by name and method text (`method="Gross(...)"`), checked at build; C# takes the same bean from the registry by its name as a `PriceCalculator` and calls `Gross` and `Stamp` directly, checked by the compiler. ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 `RoutePackageIncludeAssembly` in `RouteModule.csproj` puts `RouteModule.dll` into the package. The build checks that the bean type, its properties and the called methods exist in it, then writes `pkg/routemodule-1.0.0.tpkg`. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). ## Change it - **Constructor arguments.** One `` per parameter, in order; `type=` names the parameter type when it is not a string (`System.Decimal`, `System.Int32`, `System.TimeSpan`). An argument can be a nested ``, a `ref=` to another bean or a ``. - **Properties.** ``, converted to the property type. - **Methods.** `method=Name` calls a method that takes `IExchange` (or `IExchange` and a `CancellationToken`); `method=Name(expr, ...)` binds each argument from an expression. A method that returns a value sets the body; a `Task` is awaited. `` and `` are the same endpoint. - **Methods in expressions.** `bean:pricing.Method(args)` calls a method in any condition, value or template (`${bean:pricing.Gross(header.qty, 2)}`); the name has no `#`, the arguments are written bare. Such a method must be synchronous: a `Task` is refused there, call it as a step instead. - **Dependencies.** A class that needs services from the container (a database, an HTTP client) is better registered by code in a module with `InitRoute`; XML refers to it by `#name`. - **NuGet packages.** A package the bean uses and the worker does not ship goes into the package too: pass its assembly to `redb-route-xml pack` with `--entry`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-beans/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-beans/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "pricing.vat": "0.20", "pricing.currency": "EUR", "orders.period": "3000", "quotes.period": "10000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-beans/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-beans/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-beans/routes/QuotesRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/routes/QuotesRoute.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using RouteModule.Beans; namespace RouteModule.Routes; /// /// A sibling of routes/orders.route.xml in C#: price quotes on a timer of their own, with the same /// pricing bean of context.xml. Where the XML calls the bean by name and method text, C# calls it as a /// typed object. /// public sealed class QuotesRoute : RouteBuilder { protected override void Configure() { // A quote the bean refuses (quantity 0 throws in Gross): logged, the exchange ends. OnException() .Handled() .Log("quote ${header.quoteId} refused: ${exception.message}", LogLevel.Warning); // Every {{quotes.period:10000}} ms a quote; every fourth one has quantity 0. From("timer://cs-modulectx-quotes?period={{quotes.period:10000}}") .RouteId("cs-modulectx-quotes") .Description("Prices a quote with the C# bean, called as a typed object") .SetHeader("quoteId", Expr("quote-${header.CamelTimerCounter}")) .Process(exchange => { var pricing = Pricing(exchange); var counter = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); var qty = counter % 4 == 3 ? 0 : counter % 4 + 1; const decimal price = 8.00m; // The same two methods as the XML route: Gross for the amount, Stamp for currency and vat. exchange.In.Headers["qty"] = qty; exchange.In.Headers["price"] = price; exchange.In.Headers["gross"] = pricing.Gross(qty, price); pricing.Stamp(exchange); }) .Log("quote ${header.quoteId}: ${header.qty} x ${header.price} + VAT ${header.vat} = ${header.gross} ${header.currency}"); } // The bean context.xml registered as "pricing"; the route context is stamped on every exchange. private static PriceCalculator Pricing(IExchange exchange) => exchange.Context?.GetFromRegistry("pricing") ?? throw new InvalidOperationException("The bean 'pricing' of context.xml is not in the route context."); } Path: redb/redb.Templates/templates/route-xml/redb-route-beans/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-beans/routes/orders.route.xml ---- order ${header.orderId} refused: ${exception.message} order ${header.orderId}: ${header.qty} x ${header.price} + VAT ${header.vat} = ${header.gross} ${header.currency} order ${header.orderId} is a bulk line: ${header.qty} pieces Path: redb/redb.Templates/templates/route-xml/redb-route-cron/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/.template.config/agents-scenario.md ---- Schedules (`redb.Route.Quartz`), `routes/schedules.route.xml`: `cron://modulectx-report?schedule=...&timeZone=...` runs a job on a Quartz cron expression (six or seven fields: seconds minutes hours day-of-month month day-of-week [year], one of the two day fields `?`); `qtimer://modulectx-heartbeat?period=...` is an interval on the same scheduler. Both have `stateful=true` (no overlapping runs). Facts to keep: the job key is the group and the URI path (`redb.modulectx-report`), so it is stable across restarts and nodes, and one path has one consumer; `misfireInstruction` decides what happens to runs missed while the worker was down (`CronDoNothing`, `CronFireOnceNow`); the scheduler and its store (in memory, or a shared database for a cluster) belong to the worker, not to the module; `timer://` is not Quartz and fires on every node. Usually changed: the schedule, the time zone, the work of the job. `routes/CleanupJobRoute.cs` is a C# job on its own cron name and schedule (`cleanup.schedule`), same time zone key and misfire rule; the work is C# code in a `Process` step. Every job needs its own name after `cron://`. Path: redb/redb.Templates/templates/route-xml/redb-route-cron/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Cron", "name": "redb.Route XML module: schedules", "description": "Schedules in XML markup: a cron job with a time zone and a misfire rule, a Quartz interval; a cleanup job in C#.", "shortName": "redb-route-cron", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-cron/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/README.md ---- # RouteModule A Tsak module with scheduled jobs, written in XML markup (`urn:redb:route:1.0`) on Quartz.NET: | Route | What it does | |---|---| | `modulectx-report` | a job on a cron expression, every 30 seconds here, in the configured time zone; a run is never started beside one still running, runs missed while the worker was down are skipped | | `modulectx-heartbeat` | an interval on the same scheduler, every minute | | `cs-modulectx-cleanup` | C#: a cleanup job on a cron expression of its own, at second 15 of every minute here, in the same time zone | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `routes/schedules.route.xml` | the two jobs | | `routes/CleanupJobRoute.cs` | the cleanup job in C# | | `context.xml` | the C# route builder; room for beans and the one-time init pipeline | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the schedule options against the connector and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log shows `report job started` and `report job finished` every 30 seconds and `heartbeat` every minute. ## Cron expressions Quartz syntax, six or seven fields: seconds, minutes, hours, day of month, month, day of week, optional year. One of the two day fields is `?`. | Expression | When | |---|---| | `0/30 * * * * ?` | every 30 seconds | | `0 0 6 ? * MON-FRI` | at 06:00 on working days | | `0 */15 8-18 * * ?` | every 15 minutes from 08:00 to 18:59 | | `0 0 2 1 * ?` | at 02:00 on the first of every month | ## Configuration | Key | Default | What | |---|---|---| | `report.schedule` | `0/30 * * * * ?` | the cron expression of the report job | | `report.timeZone` | `UTC` | the time zone the expression is read in (`Europe/Moscow`) | | `heartbeat.period` | `60000` | the interval, ms | | `cleanup.schedule` | `15 * * * * ?` | the cron expression of the C# cleanup job | ## A job in C# `routes/CleanupJobRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. Its job has a name and a schedule of its own (`cleanup.schedule`) on the same Quartz scheduler, with the same time zone, `stateful` and misfire rule as the report job. The log shows `cleanup job: removing what is older than ` at second 15 of every minute, between the report runs. The difference to notice: the endpoint URI is the same text in both forms; what changes is the work of the job, which in C# is code (`DateOnly` arithmetic here, a query or a file cleanup in a real module) instead of steps. ## Change it - **Missed runs.** `misfireInstruction=CronFireOnceNow` runs one missed occurrence at start instead of skipping it. - **Overlap.** Without `stateful=true` a long run and the next one may run together. - **A cluster.** With a shared Quartz store on the workers a job runs on one node; `timer://` fires on every node. - **A start and an end.** `startAt` and `endAt` bound the schedule; `customCalendar` excludes holidays. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-cron/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-cron/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "report.timeZone takes an IANA or Windows time zone id (Europe/Moscow, UTC)." ], "Contexts": { "default": {}, "modulectx": { "report.schedule": "0/30 * * * * ?", "report.timeZone": "UTC", "heartbeat.period": "60000", "cleanup.schedule": "15 * * * * ?" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-cron/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-cron/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-cron/routes/CleanupJobRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/routes/CleanupJobRoute.cs ---- using redb.Route.Core; namespace RouteModule.Routes; /// /// A sibling of routes/schedules.route.xml in C#: a cleanup job on a cron schedule of its own, on the same Quartz /// scheduler and in the same time zone. The job works out in C# which day it cleans up. /// public sealed class CleanupJobRoute : RouteBuilder { protected override void Configure() { // At second 15 of every minute by default; a real cleanup would be "0 30 2 * * ?", at half past two at night. // The time zone, stateful and misfireInstruction as in the XML report job. From("cron://cs-modulectx-cleanup?schedule={{cleanup.schedule:15 * * * * ?}}&timeZone={{report.timeZone:UTC}}&stateful=true&misfireInstruction=CronDoNothing") .RouteId("cs-modulectx-cleanup") .Description("Runs the cleanup job on a cron schedule") .Process(exchange => { // The day whose leftovers the job removes: everything older than yesterday, in UTC. var cutoff = DateOnly.FromDateTime(DateTime.UtcNow).AddDays(-1); exchange.In.Body = cutoff.ToString("yyyy-MM-dd"); }) .Log("cleanup job: removing what is older than ${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-cron/routes/schedules.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-cron/routes/schedules.route.xml ---- report job started report job finished heartbeat Path: redb/redb.Templates/templates/route-xml/redb-route-eip/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/.template.config/agents-scenario.md ---- Integration patterns without a broker, `routes/orders.route.xml`: a timer feeds `seda://modulectx-orders`; the intake route applies `` (bean `seen-orders` in `context.xml`, in memory), ``, `` into an `` per order type, and `` by order type; the book route splits the order lines with ``. A type no branch handles throws and ends in the context's `` (`direct://modulectx-dead`). Usually changed: the timer becomes a real input; `seen-orders` becomes a shared repository on a cluster; the aggregation strategy and completion. `routes/OrdersRoute.cs` is the same chain in C# on its own timer, seda queue and `direct:` names (`cs-modulectx-...`), with C# lambdas for the router and the generated headers. It shares the `seen-orders` repository (keys prefixed `cs-`) and the dead letter channel of `context.xml` with the XML routes. Path: redb/redb.Templates/templates/route-xml/redb-route-eip/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Eip", "name": "redb.Route XML module: integration patterns", "description": "Integration patterns in XML markup, no broker: seda, idempotent consumer, aggregate, split; the same chain in C#.", "shortName": "redb-route-eip", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-eip/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/README.md ---- # RouteModule A Tsak module that shows the common integration patterns in XML markup (`urn:redb:route:1.0`). It needs no broker and no database: test orders come from a timer. | Pattern | Where | What you see in the log | |---|---|---| | In-memory queue (`seda://`) | `modulectx-source` to `modulectx-intake` | the producer goes on at once, two consumers read the queue | | Idempotent consumer | `modulectx-intake` | an order id that came before is dropped (every fourth tick repeats one) | | Throttle | `modulectx-intake` | at most 5 orders a second pass | | Wire tap | `modulectx-intake` to `modulectx-audit` | a copy of every order goes to the audit, the main flow does not wait for it | | Aggregator | `modulectx-audit` | `audit book: orders 0, 2, 4`: three ids per order type in one line | | Content-based router (`choice`) | `modulectx-intake` | books and music go to their own routes | | Splitter | `modulectx-books` | one line per order line: `book order 0: 2 x B-2` | | Dead letter channel | `context.xml`, `modulectx-dead` | an order of type `toy` has no route and ends here with the reason | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the repository of seen order ids and the dead letter channel of the context; the C# route builder | | `routes/orders.route.xml` | the routes | | `routes/OrdersRoute.cs` | the same routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the endpoint options, bean references and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log shows the lines of the table above. ## The same route in C# `routes/OrdersRoute.cs` is `routes/orders.route.xml` written as a `RouteBuilder`: the same patterns in the same order, on its own timer, seda queue and `direct:` names (`cs-modulectx-...`). `context.xml` adds it with ``. Both chains run with the module: every line of the table above also comes from the `cs-` routes, with order ids `cs-order-`. The difference to notice: the router branches and the generated headers are C# lambdas (`.When(exchange => ...)`, `.SetHeader("orderType", exchange => ...)`) instead of expression text. What the two forms share is declared once in `context.xml`: the `seen-orders` repository (the C# keys get the prefix `cs-` so they never count as duplicates of the XML ones) and the dead letter channel, which catches a failure of either form. ## Change it - **Real input.** Replace the timer route with a connector, for example `rabbitmq://`, `kafka://`, `file://` or an HTTP endpoint; the intake stays as it is. - **Idempotency across restarts and nodes.** `seen-orders` keeps the ids in the memory of one worker. On a cluster use a shared repository: `SqlIdempotentRepository` of `redb.Route.Sql`, or the redb-backed one of `redb.Route.Core`. - **Aggregation.** `strategy` takes `concat:`, `groupedBody`, `useLatest`, `sum:`, `max:`, `min:`, `intoHeader:`; `completionSize`, `completionTimeout` and `completion` (an expression) end a group. - **Throttle per key.** `key="${header.customer}"` on `` gives every key its own limit. - **Order period.** `orders.period` in the context configuration, 2000 ms by default. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-eip/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-eip/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "orders.period": "2000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-eip/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-eip/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-eip/routes/OrdersRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/routes/OrdersRoute.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.Core; namespace RouteModule.Routes; /// /// The patterns of routes/orders.route.xml written in C#: the same chain of seda queue, idempotent consumer, /// throttle, wire tap, content-based router, splitter and aggregator, on a timer, a queue and direct: names of its /// own. Both chains run with the module; a failure of either one ends in the dead letter channel of context.xml. /// public sealed class OrdersRoute : RouteBuilder { protected override void Configure() { // Test traffic: an order every {{orders.period:2000}} ms. Every fourth tick repeats the previous order id, // every seventh order has a type no branch handles. From("timer://cs-modulectx-source?period={{orders.period:2000}}") .RouteId("cs-modulectx-source") .Description("Generates test orders, the C# form") .SetHeader("orderId", exchange => { var tick = Tick(exchange); return tick % 4 == 3 ? tick - 1 : tick; }) .SetHeader("orderType", exchange => Tick(exchange) switch { var t when t % 7 == 6 => "toy", var t when t % 2 == 0 => "book", _ => "music", }) .SetBody(Expr("""{"id":"cs-order-${header.orderId}","type":"${header.orderType}","lines":[{"sku":"A-1","qty":1},{"sku":"B-2","qty":2}]}""")) .To("seda://cs-modulectx-orders"); // Intake: drop repeated order ids, at most 5 orders a second, a copy to the audit, a branch by order type. // The ids get the prefix cs- in the shared seen-orders repository, so they never clash with the XML ones. From("seda://cs-modulectx-orders?concurrentConsumers=2") .RouteId("cs-modulectx-intake") .Description("Deduplicates, throttles, audits and routes the orders, the C# form") .IdempotentConsumer("cs-${header.orderId}", "seen-orders", true) .Throttle(5).Period(TimeSpan.FromSeconds(1)) .WireTap("direct://cs-modulectx-audit") .Choice() .When(exchange => OrderType(exchange) == "book") .To("direct://cs-modulectx-books") .When(exchange => OrderType(exchange) == "music") .To("direct://cs-modulectx-music") .Otherwise() .ThrowException(typeof(InvalidOperationException), "no route for this order type") .EndChoice() .EndThrottle() .EndIdempotentConsumer(); // Splitter: one exchange per order line. From("direct://cs-modulectx-books") .RouteId("cs-modulectx-books") .Description("Handles a book order line by line, the C# form") .Split(Expr("${jpath('$.lines')}")) .Log("book order ${header.orderId}: ${jpath('$.qty')} x ${jpath('$.sku')}") .EndSplit(); From("direct://cs-modulectx-music") .RouteId("cs-modulectx-music") .Description("Handles a music order, the C# form") .Log("music order ${header.orderId}: ${body}"); // Aggregator: the audit copies per order type, three at a time or whatever arrived within 10 seconds. From("direct://cs-modulectx-audit") .RouteId("cs-modulectx-audit") .Description("Collects the audit copies per order type, the C# form") .SetBody(Expr("${header.orderId}")) .Aggregate("${header.orderType}", AggregationStrategies.ByName("concat:, "), null, 3, TimeSpan.FromSeconds(10)) .ForceCompletionOnStop() .Log("audit ${header.orderType}: orders ${body}", LogLevel.Information) .EndAggregate(); } private static int Tick(IExchange exchange) => Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); private static string? OrderType(IExchange exchange) => exchange.In.Headers["orderType"] as string; } Path: redb/redb.Templates/templates/route-xml/redb-route-eip/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-eip/routes/orders.route.xml ---- book order ${header.orderId}: ${jpath('$.qty')} x ${jpath('$.sku')} music order ${header.orderId}: ${body} audit ${header.orderType}: orders ${body} dead letter: ${exception.message}, body ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-email/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/.template.config/agents-scenario.md ---- E-mail (`redb.Route.Mail`), `routes/send.route.xml` and `routes/read.route.xml`: two beans in `context.xml`, `smtp` and `imap` (`MailConnectionFactory`: Host, Port, Security `None`, `StartTls` or `Ssl`, Username, Password). The sender posts with `smtp://...?connectionFactory=smtp&from={{mail.from}}&to={{mail.to}}`, the subject from the header `redbMail.Subject`; the reader polls `imap://...?connectionFactory=imap&fetchFilter=Unseen&postProcess=MarkRead` (the text body is the body; `redbMail.From`, `redbMail.Subject`, `redbMail.HasAttachments` and the rest are headers). Facts to keep: `disconnect=true` on the sender opens a connection per message (a server closes an idle one, a pooled connection would then fail the next send); the sender's `onException` lives in its own file, an `onException` with `handled="true"` next to the reader would mark a failed message read; `{{key}}` is resolved in URIs and bean values, not in a log `` or `setHeader value=`; the recipients set on the URI can be overridden per message by the headers `redbMail.To`, `redbMail.Cc`, `redbMail.Bcc`; a message the route failed stays unseen and is read again; `mail.password` comes from the environment. `deploy/docker-compose.mail.yml` runs GreenMail with one mailbox. Usually changed: the servers and security, the recipients, the folder and the filter (`subjectFilter`, `fromFilter`, `minAge`, `maxAge`), `postProcess` (`MarkRead`, `Delete`, `Move` with `moveTo`), what the reader does with a message. `routes/HtmlReportRoute.cs` is a second sender in C# on its own timer (`mail.htmlPeriod`): HTML built in code, `contentType=text/html`, subject in `MailHeaders.Subject`, its own `OnException` with two retries (the one of `send.route.xml` does not cover a C# builder). Keep one IMAP reader per mailbox folder: the XML one. Path: redb/redb.Templates/templates/route-xml/redb-route-email/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Email", "name": "redb.Route XML module: e-mail", "description": "E-mail in XML markup: SMTP sending with retries, an IMAP inbox read and marked; an HTML report sent from C#.", "shortName": "redb-route-email", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-email/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/README.md ---- # RouteModule A Tsak module that sends and reads e-mail, written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-mail-send` | every minute sends a short report over SMTP to `mail.to` | | `modulectx-mail-read` | every 30 seconds reads the unseen messages of the IMAP inbox, one exchange each, and marks each read once the route finished it | | `cs-modulectx-mail-html` | C#: every two minutes sends an HTML report with a table to `mail.to`, with the same retries | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `smtp` and `imap` connections: host, port, security, user, password; the C# route builder | | `routes/send.route.xml` | the sender and its retries | | `routes/read.route.xml` | the reader; a separate file so that the sender's error handling does not mark a failed message read | | `routes/HtmlReportRoute.cs` | the HTML sender in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.mail.yml` | GreenMail with one test mailbox, and the module on a Tsak worker | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `smtp://` and `imap://` option against the connector, the beans and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No mail server is needed for the build. ## Try it with GreenMail dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set MAIL_PASSWORD docker compose -f deploy/docker-compose.mail.yml up -d The module sends to its own mailbox, so the log shows both directions: `sent Report 1`, then `received from modulectx@example.org: Report 1 / Report number 1 ...`. ## Configuration | Key | Default | What | |---|---|---| | `mail.smtpHost`, `mail.smtpPort`, `mail.smtpSecurity` | `localhost`, `587`, `StartTls` | the outgoing server | | `mail.imapHost`, `mail.imapPort`, `mail.imapSecurity` | `localhost`, `993`, `Ssl` | the mailbox server | | `mail.username` | none, required | the login of both servers | | `mail.password` | none, required | its password; from the environment | | `mail.from`, `mail.to` | none, required | the sender and the recipient of the reports | | `mail.sendPeriod`, `mail.pollPeriod` | `60000`, `30000` | the intervals, ms | | `mail.htmlPeriod` | `120000` | the interval of the C# HTML report, ms | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__mail.password: ${MAIL_PASSWORD} ## An HTML report in C# `routes/HtmlReportRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own it sends through the same `smtp` bean to the same recipient, with the same two retries; the XML reader then receives it from the mailbox like the plain reports. The log shows `sent HTML report 1`. The difference to notice: XML sets the subject and the text with expressions; C# builds the HTML in code, encodes the values with `WebUtility.HtmlEncode`, sets the subject in the header `MailHeaders.Subject` and sends with `contentType=text/html`. Its retries are its own `OnException`: the one of `send.route.xml` covers the XML routes only. ## Change it - **Recipients per message.** Set the headers `redbMail.To`, `redbMail.Cc`, `redbMail.Bcc` before the `smtp://` step; they win over the URI. - **HTML.** `contentType=text/html` on the sender, `alternativeBody=true` for a plain text part too. - **Attachments.** `attachments=` on the sender; on the reader `fetchAttachments` and `maxAttachmentSize`. - **Which messages.** `subjectFilter`, `fromFilter`, `searchQuery`, another `folder`; `idle=true` for IMAP push instead of polling. - **After reading.** `postProcess=Delete`, or `Move` with `moveTo=Processed`. - **OAuth.** `AccessToken` and `AuthMechanism` on the bean instead of a password. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-email/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-email/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "mail.username, mail.password, mail.from and mail.to are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "mail.smtpHost": "smtp.example.org", "mail.smtpPort": "587", "mail.smtpSecurity": "StartTls", "mail.imapHost": "imap.example.org", "mail.imapPort": "993", "mail.imapSecurity": "Ssl", "mail.username": "modulectx@example.org", "mail.from": "modulectx@example.org", "mail.to": "modulectx@example.org", "mail.sendPeriod": "60000", "mail.htmlPeriod": "120000", "mail.pollPeriod": "30000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-email/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-email/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-email/deploy/docker-compose.mail.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/deploy/docker-compose.mail.yml ---- # A local mail server for the module: GreenMail (SMTP and IMAP for tests, one mailbox), and the module on a Tsak # worker. A test stand, not a deployment: GreenMail keeps the mail in memory and speaks no TLS on these ports. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set MAIL_PASSWORD # docker compose -f deploy/docker-compose.mail.yml up -d # # The mailbox modulectx@example.org (password MAIL_PASSWORD) receives what the module sends and is what the module # reads, so one module shows both directions. A mail client can use it too: SMTP localhost:3025, IMAP localhost:3143. name: modulectx-mail services: mail: image: greenmail/standalone:2.1.14 environment: GREENMAIL_OPTS: >- -Dgreenmail.setup.test.smtp -Dgreenmail.setup.test.imap -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.users=modulectx:${MAIL_PASSWORD:?MAIL_PASSWORD required, see deploy/.env.example}@example.org -Dgreenmail.users.login=email ports: - "127.0.0.1:3025:3025" - "127.0.0.1:3143:3143" module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: - mail environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__mail.smtpHost=mail - Tsak__Contexts__modulectx__Override__mail.smtpPort=3025 - Tsak__Contexts__modulectx__Override__mail.smtpSecurity=None - Tsak__Contexts__modulectx__Override__mail.imapHost=mail - Tsak__Contexts__modulectx__Override__mail.imapPort=3143 - Tsak__Contexts__modulectx__Override__mail.imapSecurity=None - Tsak__Contexts__modulectx__Override__mail.username=modulectx@example.org - Tsak__Contexts__modulectx__Override__mail.password=${MAIL_PASSWORD:?MAIL_PASSWORD required, see deploy/.env.example} - Tsak__Contexts__modulectx__Override__mail.from=modulectx@example.org - Tsak__Contexts__modulectx__Override__mail.to=modulectx@example.org - Tsak__Contexts__modulectx__Override__mail.sendPeriod=30000 - Tsak__Contexts__modulectx__Override__mail.pollPeriod=10000 volumes: - ../pkg:/app/modules Path: redb/redb.Templates/templates/route-xml/redb-route-email/routes/HtmlReportRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/routes/HtmlReportRoute.cs ---- using System.Net; using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.Mail; namespace RouteModule.Routes; /// /// A sibling of routes/send.route.xml in C#: an HTML report on a timer of its own, through the same smtp bean, to the /// same recipient. The mailbox reader of routes/read.route.xml receives it like any other message. /// public sealed class HtmlReportRoute : RouteBuilder { protected override void Configure() { // A send that failed is tried again twice, ten seconds apart, as in the XML sender. OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromSeconds(10)) .Handled() .Log("could not send ${header.redbMail.Subject}: ${exception.message}", LogLevel.Error); // Every {{mail.htmlPeriod:120000}} ms an HTML message with a small table built in C#. From("timer://cs-modulectx-mail-html?period={{mail.htmlPeriod:120000}}") .RouteId("cs-modulectx-mail-html") .Description("Sends an HTML report over SMTP") .Process(exchange => { var tick = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); var rows = new[] { ("orders", tick * 3), ("refunds", tick % 2), ("customers", 2) } .Select(r => $"{WebUtility.HtmlEncode(r.Item1)}{r.Item2}"); exchange.In.Headers[MailHeaders.Subject] = $"HTML report {tick}"; exchange.In.Body = $"

Report {tick}

{string.Join("", rows)}
"; }) .To("smtp://{{mail.smtpHost:localhost}}?connectionFactory=smtp&from={{mail.from}}&to={{mail.to}}&contentType=text/html&disconnect=true") .Log("sent ${header.redbMail.Subject}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-email/routes/read.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/routes/read.route.xml ---- received from ${header.redbMail.From}: ${header.redbMail.Subject} / ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-email/routes/send.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-email/routes/send.route.xml ---- could not send ${header.redbMail.Subject}: ${exception.message} sent ${header.redbMail.Subject} Path: redb/redb.Templates/templates/route-xml/redb-route-file/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/.template.config/agents-scenario.md ---- Files (`redb.Route.File`, `redb.Route.Ftp` or `redb.Route.Sftp`, chosen at `dotnet new` by `--transport`), `routes/files.route.xml`: a feed route writes test files into `{{files.inbox:inbox}}` (delete it in a real module); the inbox route polls `*.xml` (`antInclude`), checks each against `resources/order.xsd`, moves a finished file to `done/` and a failed one to `error/` (`moveTo`, `moveFailed`), and writes a receipt into `{{files.outbox:outbox}}`. For FTP and SFTP the bean `remote` in `context.xml` holds the server and the credentials; every URI says `connectionFactory=remote`. Facts to keep: `moveTo`, `moveFailed`, `preMove` and `doneFileName` take only file variables (`${file:name}`, `${file:name.noext}`); the producer's `fileName` takes the full expression language; the header prefix is the transport's (`redbFile`, `redbFtp` or `redbSftp`, then `.Name`, `.NameOnly`, `.Length`); the producer refuses paths outside its folder; `files.password` is a required key from the environment. Usually changed: the folders, the include pattern, a read lock for files still being written (`readLock`), a done marker (`doneFileName`), what the route does with a file. `routes/CsvFilesRoute.cs` runs CSV files in C# through its own inbox `files.csInbox` (`inbox-cs`) with the same `done/`, `error/` and outbox; the connection option is the constant `Connection` (empty for local files). Never point a C# consumer at `files.inbox`: the XML reader owns it. Path: redb/redb.Templates/templates/route-xml/redb-route-file/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.File", "name": "redb.Route XML module: files", "description": "Files in XML markup: an inbox, done and error folders, a receipt per file; CSV files in C#; local disk, FTP or SFTP.", "shortName": "redb-route-file", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" }, "transport": { "type": "parameter", "datatype": "choice", "choices": [ { "choice": "file", "description": "A folder of the worker's file system (a local disk or a mounted share)" }, { "choice": "ftp", "description": "An FTP server (FTPS with UseFtps)" }, { "choice": "sftp", "description": "An SFTP server (SSH)" } ], "defaultValue": "file", "displayName": "Transport", "description": "Where the inbox and outbox folders are: the connector, its URI scheme and, for FTP and SFTP, the connection bean." }, "scheme": { "type": "generated", "generator": "switch", "replaces": "file://", "parameters": { "evaluator": "C++", "datatype": "string", "cases": [ { "condition": "(transport == \"ftp\")", "value": "ftp://" }, { "condition": "(transport == \"sftp\")", "value": "sftp://" }, { "condition": "(true)", "value": "file://" } ] } }, "headerPrefix": { "type": "generated", "generator": "switch", "replaces": "redbFile.", "parameters": { "evaluator": "C++", "datatype": "string", "cases": [ { "condition": "(transport == \"ftp\")", "value": "redbFtp." }, { "condition": "(transport == \"sftp\")", "value": "redbSftp." }, { "condition": "(true)", "value": "redbFile." } ] } }, "connection": { "type": "generated", "generator": "switch", "replaces": "?connectionFactory=remote&", "parameters": { "evaluator": "C++", "datatype": "string", "cases": [ { "condition": "(transport == \"file\")", "value": "?" }, { "condition": "(true)", "value": "?connectionFactory=remote&" } ] } } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env", "deploy/data/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-file/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/README.md ---- # RouteModule A Tsak module that processes files from an inbox folder, written in XML markup (`urn:redb:route:1.0`). The folders are on the worker's disk, on an FTP or on an SFTP server: the project was created with `--transport` (`file`, `ftp` or `sftp`), which picks the connector, the URI scheme and the connection. | Route | What it does | |---|---| | `modulectx-files-feed` | test input: every 20 seconds an order file into the inbox, every fifth one not XML; delete it in a real module | | `modulectx-files-in` | every 5 seconds the new `*.xml` files of the inbox, one exchange each: checked against `resources/order.xsd`, a receipt written to the outbox; a finished file moves to `done/`, a failed one to `error/` | | `cs-modulectx-files-feed`, `cs-modulectx-files-in` | C#: every 30 seconds a CSV order file into an inbox of its own (`inbox-cs`); the reader sums the amounts, writes a receipt to the same outbox, and a file with a line without an amount moves to `error/` | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | for FTP and SFTP the `remote` connection: host, port, user, password; the C# route builder | | `routes/files.route.xml` | the two routes | | `routes/CsvFilesRoute.cs` | the CSV routes in C# | | `resources/order.xsd` | the schema of an order file | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.files.yml` | the module on a Tsak worker, with a local FTP or SFTP server for those transports | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every endpoint option against the connector, the beans, the resources and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No server is needed for the build. ## Try it locally dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # FTP and SFTP: set FILES_PASSWORD docker compose -f deploy/docker-compose.files.yml up -d The module log shows `processed order-N.xml: `; every fifth file fails the schema check and moves to `error/`. With `file` the folders are under `deploy/data`. ## Configuration | Key | Default | What | |---|---|---| | `files.inbox`, `files.outbox` | `inbox`, `outbox` | the folders; relative to the worker's working folder (file) or to the login folder (FTP, SFTP) | | `files.host`, `files.port` | `localhost`, 21 or 22 | FTP and SFTP: the server | | `files.username`, `files.password` | none, required | FTP and SFTP: the login; the password from the environment | | `files.period` | `20000` | the test feed's interval, ms | | `files.csInbox`, `files.csPeriod` | `inbox-cs`, `30000` | the inbox of the C# routes and their feed's interval, ms | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__files.password: ${FILES_PASSWORD} ## CSV files in C# `routes/CsvFilesRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. It runs the same inbox pattern for CSV files on a folder of its own, `inbox-cs`, with the same `done/` and `error/` folders and receipts into the same outbox, so the two forms never read the same file. The log shows `processed orders-1: total 9` and, for every third file, `refused orders-2: ...`. The difference to notice: XML checks a file with a schema; C# reads the lines and sums the amounts with LINQ, and a line that does not parse fails the file. The transport is chosen once for both forms: `--transport` switches the scheme and the `connectionFactory=remote` option in the C# file as well. ## Change it - **Files still being written.** `readLock=Changed` (waits until the size stops changing), or `doneFileName=${file:name}.done` when the sender writes a marker after the file. - **Delete instead of move.** `delete=true` and no `moveTo`. - **Order and volume.** `sortBy`, `maxMessagesPerPoll`, `recursive=true` with `maxDepth`. - **Twice the same file.** `idempotent=true` remembers what was read. - **FTPS, keys, host pinning.** `useFtps=true` (FTP); `PrivateKeyPath`, `ServerFingerprint` or `KnownHostsFile` with `StrictHostKeyChecking` on the `remote` bean (SFTP). ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-file/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-file/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { //#if (transport != "file") "files.host": "files.example.org", "files.username": "modulectx", //#endif "files.inbox": "inbox", "files.outbox": "outbox", "files.period": "20000", "files.csInbox": "inbox-cs", "files.csPeriod": "30000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-file/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-file/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-file/deploy/docker-compose.files.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/deploy/docker-compose.files.yml ---- #if (transport == "file") # The module on a Tsak worker with the folders on a volume: deploy/data/inbox, done, error and deploy/data/outbox. # A test stand, not a deployment. #else # A local file server for the module and the module on a Tsak worker. A test stand, not a deployment. #endif # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg #if (transport != "file") # cp deploy/.env.example deploy/.env # then set FILES_PASSWORD #endif # docker compose -f deploy/docker-compose.files.yml up -d name: modulectx-files services: #if (transport == "ftp") files: image: stilliard/pure-ftpd:bookworm-1.0.50 environment: PUBLICHOST: files FTP_USER_NAME: modulectx FTP_USER_PASS: ${FILES_PASSWORD:?FILES_PASSWORD required, see deploy/.env.example} FTP_USER_HOME: /home/ftpusers/modulectx #endif #if (transport == "sftp") files: # The image has no version tags; the digest pins it. The user is chrooted to /home/modulectx and may write only # below files/, where the module's folders are. image: atmoz/sftp@sha256:43dd1c023cf1bae487127d4b54660b0aee6e94c188a6599be36fb89ba115f961 command: "modulectx:${FILES_PASSWORD:?FILES_PASSWORD required, see deploy/.env.example}:1001::files" #endif module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} #if (transport != "file") depends_on: - files #endif environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. #if (transport == "file") - Tsak__Contexts__modulectx__Override__files.inbox=/data/inbox - Tsak__Contexts__modulectx__Override__files.outbox=/data/outbox - Tsak__Contexts__modulectx__Override__files.csInbox=/data/inbox-cs #elseif (transport == "ftp") - Tsak__Contexts__modulectx__Override__files.host=files - Tsak__Contexts__modulectx__Override__files.username=modulectx - Tsak__Contexts__modulectx__Override__files.password=${FILES_PASSWORD:?FILES_PASSWORD required, see deploy/.env.example} #else - Tsak__Contexts__modulectx__Override__files.host=files - Tsak__Contexts__modulectx__Override__files.username=modulectx - Tsak__Contexts__modulectx__Override__files.password=${FILES_PASSWORD:?FILES_PASSWORD required, see deploy/.env.example} - Tsak__Contexts__modulectx__Override__files.inbox=files/inbox - Tsak__Contexts__modulectx__Override__files.outbox=files/outbox - Tsak__Contexts__modulectx__Override__files.csInbox=files/inbox-cs #endif volumes: - ../pkg:/app/modules #if (transport == "file") - ./data:/data #endif Path: redb/redb.Templates/templates/route-xml/redb-route-file/resources/order.xsd Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/resources/order.xsd ---- Path: redb/redb.Templates/templates/route-xml/redb-route-file/routes/CsvFilesRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/routes/CsvFilesRoute.cs ---- using System.Globalization; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace RouteModule.Routes; /// /// A sibling of routes/files.route.xml in C#: CSV order files through an inbox folder of its own, /// {{files.csInbox:inbox-cs}}, with the same done/ and error/ folders and receipts into the same outbox. The /// XML inbox and this one are different folders, so no file is read twice. /// public sealed class CsvFilesRoute : RouteBuilder { //#if (transport == "file") // The folders are on the worker's file system: no connection bean. private const string Connection = ""; //#else // The same remote connection bean as the XML routes. private const string Connection = "connectionFactory=remote&"; //#endif protected override void Configure() { // Test input: every {{files.csPeriod:30000}} ms a CSV file of three order lines; every third file has a line // without an amount. From("timer://cs-modulectx-files-feed?period={{files.csPeriod:30000}}") .RouteId("cs-modulectx-files-feed") .Description("Puts a test CSV order file into the C# inbox") .SetBody(exchange => { var tick = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); var third = tick % 3 == 2 ? "C-3;" : $"C-3;{tick + 3}"; return $"sku;amount\nA-1;{tick + 1}\nB-2;{tick + 2}\n{third}\n"; }) .To("file://{{files.csInbox:inbox-cs}}?" + Connection + "fileName=orders-${header.CamelTimerCounter}.csv"); // The C# inbox: every 5 seconds the *.csv files; a finished file moves to done/, a failed one to error/. From("file://{{files.csInbox:inbox-cs}}?" + Connection + "antInclude=*.csv&delay=5000&moveTo=done&moveFailed=error") .RouteId("cs-modulectx-files-in") .Description("Processes the CSV files of the C# inbox") .OnException() .Log("refused ${header.redbFile.NameOnly}: ${exception.message}", LogLevel.Warning) .EndOnException() .ConvertBody(typeof(string)) .Process(exchange => { // A line without an amount fails the file: it moves to error/. var total = ((string)exchange.In.Body!) .Split('\n', StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Sum(line => decimal.Parse(line.Split(';')[1], CultureInfo.InvariantCulture)); exchange.In.Headers["total"] = total; }) .Log("processed ${header.redbFile.NameOnly}: total ${header.total}") .SetBody(Expr("received ${header.redbFile.NameOnly}, total ${header.total}")) .To("file://{{files.outbox:outbox}}?" + Connection + "fileName=${header.redbFile.NameOnly}.receipt"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-file/routes/files.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-file/routes/files.route.xml ---- processed ${header.redbFile.NameOnly}: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/.template.config/agents-scenario.md ---- Kafka (`redb.Route.Kafka`), `routes/orders.route.xml`: a producer to the topic `orders` keyed by the header `CamelKafkaKey`, a consumer of `orders` in the group `{{kafka.group:modulectx}}` and a consumer of `orders-failed`. The connection is the bean `kafka` (`KafkaConnectionFactory`) in `context.xml`; every URI says `connectionFactory=kafka`. `onException` retries a failed record twice and then sends the original to `orders-failed`; the offset is committed after the route. Keys: `kafka.brokers` required, `kafka.group` with a default. A record arrives as bytes: keep `` before JSON expressions. Headers of a consumed record: `CamelKafkaTopic`, `CamelKafkaPartition`, `CamelKafkaOffset`, `CamelKafkaKey`. `deploy/docker-compose.kafka.yml` starts a local single-node Kafka. Usually changed: topic names, the group, security properties of the `kafka` bean, the retry count. `routes/PaymentsRoute.cs` adds payments in C# on their own topic `cs-payments` (key = customer) and consumer group `cs-modulectx`: the consumer keeps a running total per customer in the builder's dictionary. Never point a C# consumer at the XML topics. Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Kafka", "name": "redb.Route XML module: Kafka", "description": "Kafka in XML markup: a keyed producer, a consumer group with retries, a topic for failed records; payments in C#.", "shortName": "redb-route-kafka", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/README.md ---- # RouteModule A Tsak module that works with Kafka, written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-orders-out` | publishes a test order to the topic `orders` every 5 seconds, keyed by the order id; every fifth one has amount 0 | | `modulectx-orders-in` | reads `orders` in the consumer group `modulectx` and logs each order with its partition and offset; an order with amount 0 fails | | `modulectx-orders-failed` | logs what ended up in the topic `orders-failed` | | `cs-modulectx-payments-out` | C#: publishes a test payment to the topic `cs-payments` every 4 seconds, keyed by customer | | `cs-modulectx-payments-in` | C#: reads `cs-payments` in the consumer group `cs-modulectx` and logs a running total per customer | A failed record is tried again twice, one second apart (`onException` in `routes/orders.route.xml`). If it still fails, the original record goes to `orders-failed` and its offset is committed, so one bad record does not stop the partition. The offset of every record is committed after the route finished with it: a record is not lost when the worker stops in the middle. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `kafka` connection: brokers and consumer group from configuration; the C# route builder | | `routes/orders.route.xml` | the three routes and the error handling | | `routes/PaymentsRoute.cs` | the payment routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.kafka.yml` | a local single-node Kafka (KRaft) | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `kafka://` option against the connector, the `kafka` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No broker is needed for the build. ## Run 1. Start a broker: `docker compose -f deploy/docker-compose.kafka.yml up -d` (brokers `localhost:9092`). 2. Give the context its configuration: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. `kafka.brokers` has no default: without it the module stops at init and names the key. 3. Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log then shows `order processed` every 5 seconds and, for every fifth order, two retries and `failed order`. ## Configuration | Key | Default | What | |---|---|---| | `kafka.brokers` | none, required | bootstrap servers, `host:port[,host:port]` | | `kafka.group` | `modulectx` | consumer group of the module | | `orders.period` | `5000` | producer interval, ms | | `payments.period` | `4000` | payment producer interval, ms | ## Payments in C# `routes/PaymentsRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. It uses the same `kafka` connection and its own timer, topic and consumer group, so it never reads what the XML routes read. The log shows lines like `payment of customer-1: total 5 (partition 0, offset 1)`. The difference to notice: the running total is C# state of the route builder (a dictionary per customer), which markup has no place for, and the record key header is the constant `KafkaHeaders.Key` instead of the text `CamelKafkaKey`. The totals are those of the partitions this worker reads; with several workers each one sums its own customers. ## Change it - **Topics.** `kafka://?connectionFactory=kafka`. The broker of the compose file creates a topic on first use; a production cluster usually wants them created up front. - **Where a new group starts.** `AutoOffsetReset` on the `kafka` bean, `Earliest` here. - **Exactly once.** Kafka transactions (`transactionalIdPrefix`) move the output and the consumed offset together; the `redb.Route.Kafka` package README shows the setup. - **Security.** `SecurityProtocol`, `SaslMechanism`, `SaslUsername`, `SaslPassword`, `Ssl*` on the `kafka` bean; take the password from a `{{key}}` without a default. - **Retries.** `maximumRedeliveries` and `redeliveryDelay` on `onException`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "kafka.brokers is such a key." ], "Contexts": { "default": {}, "modulectx": { "kafka.brokers": "localhost:9092", "kafka.group": "modulectx", "orders.period": "5000", "payments.period": "4000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/deploy/docker-compose.kafka.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/deploy/docker-compose.kafka.yml ---- # A local single-node Kafka (KRaft, no ZooKeeper) for the module: # docker compose -f deploy/docker-compose.kafka.yml up -d # Brokers: localhost:9092. Topics are created on first use. name: modulectx-kafka services: kafka: image: apache/kafka:4.1.0 ports: - "9092:9092" environment: KAFKA_NODE_ID: 1 KAFKA_PROCESS_ROLES: broker,controller KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 KAFKA_NUM_PARTITIONS: 3 volumes: - kafka-data:/var/lib/kafka/data volumes: kafka-data: Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/routes/PaymentsRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/routes/PaymentsRoute.cs ---- using System.Collections.Concurrent; using System.Text.Json; using redb.Route.Core; using redb.Route.Kafka; namespace RouteModule.Routes; /// /// A sibling of routes/orders.route.xml in C#: payments on a topic of their own, cs-payments, keyed by customer, /// and a consumer that keeps a running total per customer. The same kafka connection bean; its own timer, topic /// and consumer group, so it never reads what the XML routes read. /// public sealed class PaymentsRoute : RouteBuilder { // Running totals of the customers whose partitions this worker reads. private readonly ConcurrentDictionary _totals = new(); protected override void Configure() { // Producer: a payment every {{payments.period:4000}} ms for one of three customers. The record key is the // customer, so the payments of one customer land in one partition, in order. From("timer://cs-modulectx-payments?period={{payments.period:4000}}") .RouteId("cs-modulectx-payments-out") .Description("Publishes a test payment to the topic cs-payments") .SetHeader(KafkaHeaders.Key, Expr("customer-${header.CamelTimerCounter % 3}")) .SetBody(Expr("""{"customer":"customer-${header.CamelTimerCounter % 3}","amount":${header.CamelTimerCounter}}""")) .To("kafka://cs-payments?connectionFactory=kafka"); // Consumer in a group of its own: the offset is committed after the route finished with a record. From("kafka://cs-payments?connectionFactory=kafka&groupId=cs-modulectx") .RouteId("cs-modulectx-payments-in") .Description("Keeps a running total per customer") .ConvertBody(typeof(string)) .Process(exchange => { using var json = JsonDocument.Parse((string)exchange.In.Body!); var customer = json.RootElement.GetProperty("customer").GetString()!; var amount = json.RootElement.GetProperty("amount").GetDecimal(); exchange.In.Headers["total"] = _totals.AddOrUpdate(customer, amount, (_, sum) => sum + amount); exchange.In.Headers["customer"] = customer; }) .Log("payment of ${header.customer}: total ${header.total} (partition ${header.CamelKafkaPartition}, offset ${header.CamelKafkaOffset})"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-kafka/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-kafka/routes/orders.route.xml ---- moved to orders-failed: ${exception.message} order processed: ${body} (partition ${header.CamelKafkaPartition}, offset ${header.CamelKafkaOffset}) failed order: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/.template.config/agents-scenario.md ---- LDAP (`redb.Route.Ldap`), `routes/directory.route.xml`: the bean `ldap` (`LdapConnectionFactory`: Server, Port, BindDn, BindPassword) in `context.xml`; every URI says `connectionFactory=ldap`. Three routes: `ldap:WATCH:{{ldap.usersDn}}?...&initialLoad=true` (every entry once, then the changed ones; the body is an `LdapEntry` with `Dn`, `Attributes`, `ChangeType`), `ldap:SEARCH:...` on a timer (the count is `redbLdap.ResultCount`), and `direct://modulectx-check-password`, a `ldap:BIND` with the credentials in the headers `redbLdap.AuthDn` and `redbLdap.AuthPassword` (`redbLdap.BindResult` 0 = accepted, 49 = invalid credentials). Facts to keep: the URI form is `ldap:OPERATION:baseDn?options`; a filter with parentheses goes into `filter=` as is; `{{key}}` is resolved in URIs and bean values, not in `setHeader value=`, so credentials for BIND come from the caller's headers; `ldap.bindPassword` is a required key from the environment. `deploy/docker-compose.ldap.yml` starts OpenLDAP with `deploy/ldap/users.ldif`. Usually changed: the base DNs and the filter, the attributes, what the watch does with an entry, the caller of the password check (an HTTP route of `redb.Route.Http`). `routes/DirectoryListRoute.cs` is a C# `SEARCH` on its own timer (`ldap.listPeriod`) that reads the body as `IEnumerable` and logs the users with their mail addresses. Only one `ldap:WATCH` per directory and filter: keep the watch in XML. Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Ldap", "name": "redb.Route XML module: LDAP", "description": "LDAP in XML markup: a directory watch, a search on a timer, a password check by bind; a user list in C#.", "shortName": "redb-route-ldap", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/README.md ---- # RouteModule A Tsak module that works with an LDAP directory, written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-ldap-watch` | every user entry once at start, then every entry whose `modifyTimestamp` changed, polled every 10 seconds; one exchange per entry | | `modulectx-ldap-count` | a search every minute: how many users the directory holds | | `modulectx-ldap-check-password` | `direct://modulectx-check-password`: a bind with the credentials of the headers `redbLdap.AuthDn` and `redbLdap.AuthPassword`; `redbLdap.BindResult` is 0 when they are right | | `cs-modulectx-ldap-list` | C#: a search every minute that lists the users with their mail addresses | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `ldap` connection: server, port, service account; the C# route builder | | `routes/directory.route.xml` | the three routes | | `routes/DirectoryListRoute.cs` | the user list in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.ldap.yml` | OpenLDAP with the test entries of `deploy/ldap/users.ldif`, and the module on a Tsak worker | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `ldap:` option against the connector, the `ldap` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No directory is needed for the build. ## Try it with OpenLDAP dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set LDAP_ADMIN_PASSWORD docker compose -f deploy/docker-compose.ldap.yml up -d The module log shows `directory entry added: uid=alice,ou=users,dc=example,dc=org` and the same for bob, then `users in the directory: 2` every minute. Add an entry with `ldapadd` in the `openldap` container and the watch logs it within 10 seconds. ## Configuration | Key | Default | What | |---|---|---| | `ldap.server` | `localhost` | directory host | | `ldap.port` | `389` | 389, or 636 with `Ssl` on the bean | | `ldap.bindDn` | none, required | the service account | | `ldap.bindPassword` | none, required | its password; from the environment | | `ldap.baseDn` | none, required | the base of the password check | | `ldap.usersDn` | none, required | where the users are | | `ldap.countPeriod` | `60000` | the search interval, ms | | `ldap.listPeriod` | `60000` | the interval of the C# user list, ms | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__ldap.bindPassword: ${LDAP_PASSWORD} ## The user list in C# `routes/DirectoryListRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own it sends the same kind of `SEARCH` through the same `ldap` bean and logs `users: alice , bob `. The difference to notice: XML reads the result through headers and expressions (`redbLdap.ResultCount`); C# takes the body as the list of `LdapEntry` objects it is and reads each attribute with `entry.GetString("mail")`. ## Change it - **Active Directory.** `changeTrackingMode=usn` on the watch, `ldap.port` 636 with `Ssl`, the AD names in the filter (`(objectClass=user)`, `sAMAccountName`). - **Deletions.** `detectDeletions=true` on the watch reports entries that disappeared. - **Calling the password check.** From an HTTP route of `redb.Route.Http`: set `redbLdap.AuthDn` and `redbLdap.AuthPassword` from the request, ``, answer by `redbLdap.BindResult`. - **Writing.** `ldap:ADD:` with a dictionary body, `ldap:MODIFY:`, `ldap:DELETE:`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "ldap.bindDn, ldap.bindPassword, ldap.usersDn and ldap.baseDn are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "ldap.server": "localhost", "ldap.port": "389", "ldap.bindDn": "cn=admin,dc=example,dc=org", "ldap.baseDn": "dc=example,dc=org", "ldap.usersDn": "ou=users,dc=example,dc=org", "ldap.countPeriod": "60000", "ldap.listPeriod": "60000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/deploy/docker-compose.ldap.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/deploy/docker-compose.ldap.yml ---- # A local directory for the module: OpenLDAP with the test entries of ldap/users.ldif, and the module on a Tsak # worker. A test stand, not a deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set LDAP_ADMIN_PASSWORD # docker compose -f deploy/docker-compose.ldap.yml up -d # # The module reads the directory as cn=admin,dc=example,dc=org. # Add a user with ldapadd in the openldap container and the watch route logs it within 10 seconds. name: modulectx-ldap services: openldap: image: osixia/openldap:1.5.0 # --copy-service: the bootstrap LDIF is copied, the mounted file stays read-only. command: ["--copy-service"] environment: LDAP_ORGANISATION: "Example" LDAP_DOMAIN: "example.org" LDAP_ADMIN_PASSWORD: ${LDAP_ADMIN_PASSWORD:?LDAP_ADMIN_PASSWORD required, see deploy/.env.example} ports: - "127.0.0.1:389:389" volumes: - ./ldap/users.ldif:/container/service/slapd/assets/config/bootstrap/ldif/custom/50-users.ldif:ro module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: - openldap environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__ldap.server=openldap - Tsak__Contexts__modulectx__Override__ldap.bindDn=cn=admin,dc=example,dc=org - Tsak__Contexts__modulectx__Override__ldap.bindPassword=${LDAP_ADMIN_PASSWORD:?LDAP_ADMIN_PASSWORD required, see deploy/.env.example} - Tsak__Contexts__modulectx__Override__ldap.baseDn=dc=example,dc=org - Tsak__Contexts__modulectx__Override__ldap.usersDn=ou=users,dc=example,dc=org volumes: - ../pkg:/app/modules Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/routes/DirectoryListRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/routes/DirectoryListRoute.cs ---- using redb.Route.Core; using redb.Route.Ldap; namespace RouteModule.Routes; /// /// A sibling of routes/directory.route.xml in C#: the user list with their mail addresses, on a timer of its own, /// through the same ldap connection bean. A search only reads, so it never competes with the XML watch. /// public sealed class DirectoryListRoute : RouteBuilder { protected override void Configure() { // Every {{ldap.listPeriod:60000}} ms, the first time 10 seconds after start: a SEARCH whose body is the list of // entries, read as typed LdapEntry objects. From("timer://cs-modulectx-ldap-list?period={{ldap.listPeriod:60000}}&delay=10000") .RouteId("cs-modulectx-ldap-list") .Description("Lists the users and their mail addresses") .To("ldap:SEARCH:{{ldap.usersDn}}?connectionFactory=ldap&filter=(objectClass=inetOrgPerson)&attributes=uid,mail") .Process(exchange => { var users = ((IEnumerable)exchange.In.Body!) .Select(entry => $"{entry.GetString("uid")} <{entry.GetString("mail")}>") .Order(StringComparer.Ordinal); exchange.In.Body = "users: " + string.Join(", ", users); }) .Log("${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-ldap/routes/directory.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-ldap/routes/directory.route.xml ---- directory entry ${body.ChangeType}: ${body.Dn} users in the directory: ${header.redbLdap.ResultCount} password accepted for ${header.redbLdap.AuthDn} password refused for ${header.redbLdap.AuthDn}: result ${header.redbLdap.BindResult} Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/.template.config/agents-scenario.md ---- MQTT (`redb.Route.MqttNet`, MQTTnet, MQTT 3.1.1 and 5), `routes/sensors.route.xml`: test sensors publish to `sensors//temperature` (QoS 1), a retained status goes to `modules/modulectx/status`, a subscriber of `sensors/+/temperature` logs each reading and publishes the ones over 30 degrees to `alerts/temperature`, which a fourth route logs. The connection is the bean `mqtt` (`MqttConnectionFactory`: Server, Port, Username, Password, UseTls) in `context.xml`; every URI says `connectionFactory=mqtt`. Facts to keep: the topic is the URI path; a producer says `mode=Publish` (the default mode is Subscribe); `+` matches one level, `#` the rest; no `ClientId` on the shared bean (two connections with one id push each other off); the received topic is the header `redbMqtt.topic`; a message arrives as bytes, keep `` before JSON expressions; `mqtt.password` is a required key from the environment. `deploy/docker-compose.mqtt.yml` runs Mosquitto. Usually changed: the topics, QoS, `retain`, `sharedSubscription` to share one subscription between workers, TLS. `routes/HumidityRoute.cs` adds humidity sensors in C# on their own topics `sensors//humidity` (timer `humidity.period`) and a subscriber of `sensors/+/humidity` that keeps a moving average per room in the builder. A C# subscription must not overlap the XML one (`sensors/+/temperature`). Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Mqtt", "name": "redb.Route XML module: MQTT", "description": "MQTT in XML markup: sensors publishing with QoS 1, a wildcard subscriber, a retained status; humidity in C#.", "shortName": "redb-route-mqtt", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/README.md ---- # RouteModule A Tsak module that works with an MQTT broker, written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-sensors-out` | test sensors: every 5 seconds a temperature reading of two rooms on `sensors//temperature`, QoS 1 | | `modulectx-status` | the module's status every minute on `modules/modulectx/status`, retained | | `modulectx-sensors-in` | subscribes to `sensors/+/temperature`, logs each reading, publishes the ones over 30 degrees to `alerts/temperature` | | `modulectx-alerts` | logs the alerts | | `cs-modulectx-humidity-out` | C#: every 7 seconds a humidity reading of two rooms on `sensors//humidity`, QoS 1 | | `cs-modulectx-humidity-in` | C#: subscribes to `sensors/+/humidity` and logs the moving average of each room | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `mqtt` connection: host, port, user, password; the C# route builder | | `routes/sensors.route.xml` | the four routes | | `routes/HumidityRoute.cs` | the humidity routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.mqtt.yml` | a local Mosquitto, and the module on a Tsak worker | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `mqtt://` option against the connector, the `mqtt` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No broker is needed for the build. ## Try it with Mosquitto dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set MQTT_PASSWORD docker compose -f deploy/docker-compose.mqtt.yml up -d The module log shows `sensors/room-1/temperature: 24 C` and the like every 5 seconds, and `alert: ...` for the readings over 30. The module needs the broker up when it starts: a subscription that cannot reach it fails its route and the context. The compose file therefore starts the module only when Mosquitto takes a login (`healthcheck` and `condition: service_healthy`); do the same in a deployment. ## Configuration | Key | Default | What | |---|---|---| | `mqtt.host`, `mqtt.port` | `localhost`, `1883` | the broker; 8883 with `UseTls` on the bean | | `mqtt.username` | none, required | the user | | `mqtt.password` | none, required | its password; from the environment | | `sensors.period` | `5000` | the test sensors' interval, ms | | `humidity.period` | `7000` | the C# humidity sensors' interval, ms | In a deployment the password goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__mqtt.password: ${MQTT_PASSWORD} ## Humidity in C# `routes/HumidityRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. It publishes and subscribes on topics of its own, `sensors//humidity`, through the same `mqtt` bean; the XML subscriber takes `sensors/+/temperature` only. The log shows `sensors/room-1/humidity: average 40.5 % over the last readings`. The difference to notice: the moving average is C# state of the route builder (the last five readings per room), which markup has no place for; the received topic is read with the constant `MqttHeaders.Topic`. ## Change it - **Topics.** The topic is the URI path; `+` matches one level, `#` everything below. - **Delivery.** `qos=0` (at most once), `1` (at least once), `2` (exactly once). - **Several workers.** `sharedSubscription=` shares one subscription, each message goes to one worker. - **MQTT 5.** `messageExpiryInterval`, `responseTopic` and `contentType` on the publisher. - **TLS.** `UseTls` on the `mqtt` bean. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "mqtt.username and mqtt.password are such keys; the password goes through the environment." ], "Contexts": { "default": {}, "modulectx": { "mqtt.host": "localhost", "mqtt.port": "1883", "mqtt.username": "modulectx", "sensors.period": "5000", "humidity.period": "7000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/deploy/docker-compose.mqtt.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/deploy/docker-compose.mqtt.yml ---- # A local MQTT broker for the module: Eclipse Mosquitto, and the module on a Tsak worker. A test stand, not a # deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set MQTT_PASSWORD # docker compose -f deploy/docker-compose.mqtt.yml up -d # # The broker listens on localhost:1883 for the user modulectx; subscribe to alerts/# with any MQTT client to watch # the alerts. name: modulectx-mqtt services: mosquitto: image: eclipse-mosquitto:2.1.2-alpine environment: MQTT_PASSWORD: ${MQTT_PASSWORD:?MQTT_PASSWORD required, see deploy/.env.example} # The password file is written at start from MQTT_PASSWORD, then the broker starts with mosquitto.conf. entrypoint: ["sh", "-ec"] command: - | cp /config-ro/mosquitto.conf /mosquitto/config/mosquitto.conf mosquitto_passwd -c -b /mosquitto/config/passwd modulectx "$$MQTT_PASSWORD" chown mosquitto:mosquitto /mosquitto/config/passwd chmod 0700 /mosquitto/config/passwd exec mosquitto -c /mosquitto/config/mosquitto.conf ports: - "127.0.0.1:1883:1883" volumes: - ./mosquitto/mosquitto.conf:/config-ro/mosquitto.conf:ro # Ready when the broker takes a login; the module starts only then, so its subscriptions find the broker. healthcheck: test: ["CMD-SHELL", "mosquitto_sub -h localhost -u modulectx -P \"$$MQTT_PASSWORD\" -t '$$SYS/broker/version' -C 1 -W 3"] interval: 5s timeout: 5s retries: 30 module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: mosquitto: condition: service_healthy environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__mqtt.host=mosquitto - Tsak__Contexts__modulectx__Override__mqtt.username=modulectx - Tsak__Contexts__modulectx__Override__mqtt.password=${MQTT_PASSWORD:?MQTT_PASSWORD required, see deploy/.env.example} volumes: - ../pkg:/app/modules Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/deploy/mosquitto/mosquitto.conf Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/deploy/mosquitto/mosquitto.conf ---- # Mosquitto for the local stand: one plain listener, users from the password file the compose command writes. listener 1883 allow_anonymous false password_file /mosquitto/config/passwd Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/routes/HumidityRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/routes/HumidityRoute.cs ---- using System.Collections.Concurrent; using System.Text.Json; using redb.Route.Core; using redb.Route.MqttNet; namespace RouteModule.Routes; /// /// A sibling of routes/sensors.route.xml in C#: humidity sensors on topics of their own, /// sensors/<room>/humidity, and a subscriber that keeps a moving average per room. The same mqtt connection /// bean; the XML subscriber reads sensors/+/temperature only, so no message is read by both forms. /// public sealed class HumidityRoute : RouteBuilder { // The last five readings of every room. private readonly ConcurrentDictionary> _readings = new(); protected override void Configure() { // Test sensors: every {{humidity.period:7000}} ms a humidity reading of room-1 and room-2, QoS 1. From("timer://cs-modulectx-humidity?period={{humidity.period:7000}}") .RouteId("cs-modulectx-humidity-out") .Description("Publishes test humidity readings") .SetBody(Expr("""{"room":"room-1","percent":${header.CamelTimerCounter % 20 + 40}}""")) .To("mqtt://sensors/room-1/humidity?connectionFactory=mqtt&mode=Publish&qos=1&contentType=application/json") .SetBody(Expr("""{"room":"room-2","percent":${header.CamelTimerCounter % 9 + 55}}""")) .To("mqtt://sensors/room-2/humidity?connectionFactory=mqtt&mode=Publish&qos=1&contentType=application/json"); // Every room's humidity: the average of its last five readings. From("mqtt://sensors/+/humidity?connectionFactory=mqtt&qos=1") .RouteId("cs-modulectx-humidity-in") .Description("Keeps a moving average of the humidity per room") .ConvertBody(typeof(string)) .Process(exchange => { using var json = JsonDocument.Parse((string)exchange.In.Body!); var room = json.RootElement.GetProperty("room").GetString()!; var last = _readings.GetOrAdd(room, _ => new Queue()); lock (last) { last.Enqueue(json.RootElement.GetProperty("percent").GetInt32()); if (last.Count > 5) last.Dequeue(); exchange.In.Headers["average"] = Math.Round(last.Average(), 1); } exchange.In.Headers["topic"] = exchange.In.Headers[MqttHeaders.Topic]; }) .Log("${header.topic}: average ${header.average} % over the last readings"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-mqtt/routes/sensors.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-mqtt/routes/sensors.route.xml ---- ${header.redbMqtt.topic}: ${jpath('$.celsius')} C alert: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/.template.config/agents-scenario.md ---- RabbitMQ (`redb.Route.RabbitMQ`), `routes/orders.route.xml`: a producer to the queue `orders`, a consumer of `orders` and a consumer of `orders-failed`. The connection is the bean `rabbit` (`RabbitMQConnectionFactory`) in `context.xml`; every URI says `connectionFactory=rabbit&declare=true`. `onException` retries a failed message twice and then sends the original to `orders-failed`. Keys: `rabbit.host`, `rabbit.port`, `rabbit.vhost`, `rabbit.username` with defaults, `rabbit.password` required. A message body arrives as bytes: keep `` before JSON expressions. `deploy/docker-compose.rabbitmq.yml` starts a local broker. Usually changed: queue names, an exchange (`rabbitmq:?exchange=...&exchangeType=topic&routingKey=...`), `prefetchCount`, the retry count. `routes/QuoteRpcRoute.cs` adds request-reply in C# on its own queue `cs-quotes` and timer: the client sends with `replyTo=true&timeout={{rpc.timeout:5}}` and reads the reply as the body of the next step; the server route ends with the reply as its body. Keep the server free of retries and of a handled `OnException`: a handled error would send an empty or stale reply, an unhandled one shows as the client's timeout. Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.RabbitMQ", "name": "redb.Route XML module: RabbitMQ", "description": "RabbitMQ in XML markup: a producer, a consumer with retries, a queue for failed messages; request-reply in C#.", "shortName": "redb-route-rabbitmq", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/README.md ---- # RouteModule A Tsak module that works with RabbitMQ, written in XML markup (`urn:redb:route:1.0`) and in C#: | Route | What it does | |---|---| | `modulectx-orders-out` | publishes a test order to the queue `orders` every 5 seconds; every fifth one has amount 0 | | `modulectx-orders-in` | reads `orders` and logs each order; an order with amount 0 fails | | `modulectx-orders-failed` | logs what ended up in the queue `orders-failed` | | `cs-modulectx-quote-client` | C#: asks for a price quote on the queue `cs-quotes` every 7 seconds and waits for the reply | | `cs-modulectx-quote-server` | C#: answers the quote requests of `cs-quotes` | A failed message is tried again twice, one second apart (`onException` in `routes/orders.route.xml`). If it still fails, the original message goes to `orders-failed` and the delivery is acknowledged, so one bad message does not block the queue. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `rabbit` connection: host, port, virtual host, user, password from configuration; the C# route builder | | `routes/orders.route.xml` | the three routes and the error handling | | `routes/QuoteRpcRoute.cs` | the request-reply routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.rabbitmq.yml` | a local RabbitMQ with the management UI | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `rabbitmq://` option against the connector, the `rabbit` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No broker is needed for the build. ## Run 1. Start a broker: `docker compose -f deploy/docker-compose.rabbitmq.yml up -d` (management UI on http://localhost:15672, guest / guest). 2. Give the context its configuration: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. `rabbit.password` has no default: without it the module stops at init and names the key. 3. Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log then shows `order processed` every 5 seconds and, for every fifth order, two retries and `failed order`. ## Configuration | Key | Default | What | |---|---|---| | `rabbit.host` | `localhost` | broker host | | `rabbit.port` | `5672` | AMQP port | | `rabbit.vhost` | `/` | virtual host | | `rabbit.username` | `guest` | user | | `rabbit.password` | none, required | password; in production from an environment variable | | `orders.period` | `5000` | producer interval, ms | | `rpc.period` | `7000` | quote request interval, ms | | `rpc.timeout` | `5` | how long the client waits for a reply, s | The guest user of RabbitMQ works only from localhost; a broker on another machine needs its own user. ## Request-reply in C# `routes/QuoteRpcRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. It uses the same `rabbit` connection and its own timer and queue, so it never reads what the XML routes read. The log shows `quote requested: {"id":"quote-1","amount":1}` from the server and `quote received: {"id":"quote-1","gross":1.20}` from the client. The difference to notice: the client sends with `replyTo=true&timeout={{rpc.timeout:5}}`, so the send waits for the reply (a reply queue of its own and a correlation id) and the step after it reads the reply as the body. The server needs no option: a request carries its reply address, and the body the route ends with goes back. The server has no error handler on purpose: a request that fails is tried again by the consumer (`maximumRetryAttempts`, 5 by default, 1 s apart) and then rejected; with no dead letter exchange it is dropped, and the client sees its timeout. ## Change it - **Queues.** `rabbitmq://?connectionFactory=rabbit&declare=true` declares the queue at start. Leave `declare` out when the queues are created by the broker's administrators. - **Exchanges.** `rabbitmq:?exchange=events&exchangeType=topic&routingKey=order.*&connectionFactory=rabbit&declare=true` reads a queue of its own bound to the exchange. - **Parallelism.** `prefetchCount` limits the unacknowledged messages per consumer; `concurrentConsumers` runs several consumers on one queue. - **TLS.** `Ssl`, `SslServerName`, `SslCaCertPath` on the `rabbit` bean. - **Retries.** `maximumRedeliveries` and `redeliveryDelay` on `onException`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "rabbit.password is such a key: set it here only for a local broker, in production through the environment." ], "Contexts": { "default": {}, "modulectx": { "rabbit.host": "localhost", "rabbit.port": "5672", "rabbit.vhost": "/", "rabbit.username": "guest", "rabbit.password": "guest", "orders.period": "5000", "rpc.period": "7000", "rpc.timeout": "5" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/deploy/docker-compose.rabbitmq.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/deploy/docker-compose.rabbitmq.yml ---- # A local RabbitMQ for the module: docker compose -f deploy/docker-compose.rabbitmq.yml up -d # Management UI: http://localhost:15672 (guest / guest). The guest user works from localhost only. name: modulectx-rabbitmq services: rabbitmq: image: rabbitmq:4-management ports: - "5672:5672" - "15672:15672" healthcheck: test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] interval: 10s timeout: 5s retries: 10 volumes: - rabbitmq-data:/var/lib/rabbitmq volumes: rabbitmq-data: Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/routes/QuoteRpcRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/routes/QuoteRpcRoute.cs ---- using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace RouteModule.Routes; /// /// The request-reply half of the scenario in C#, next to the publish, consume and retry routes of /// routes/orders.route.xml: a client asks for a price quote on the queue cs-quotes and waits for the reply, a /// server answers it. Its own timer and its own queue, the same rabbit connection bean. /// public sealed class QuoteRpcRoute : RouteBuilder { protected override void Configure() { // Client: every {{rpc.period:7000}} ms a quote request. replyTo=true makes the send a request-reply: the // connector publishes with a reply queue of its own and a correlation id, waits up to {{rpc.timeout:5}} // seconds and puts the reply into the exchange, so the next step reads the reply as the body. From("timer://cs-modulectx-quotes?period={{rpc.period:7000}}") .RouteId("cs-modulectx-quote-client") .Description("Asks for a price quote and waits for the reply") // No reply in time: the server failed or is not running. Logged, the next tick asks again. .OnException() .Handled() .Log("no quote within the timeout: ${exception.message}", LogLevel.Warning) .EndOnException() .SetBody(Expr("""{"id":"quote-${header.CamelTimerCounter}","amount":${header.CamelTimerCounter}}""")) .To("rabbitmq://cs-quotes?connectionFactory=rabbit&declare=true&replyTo=true&timeout={{rpc.timeout:5}}") .ConvertBody(typeof(string)) .Log("quote received: ${body}"); // Server: a request on cs-quotes carries a reply address, so the connector sends the body this route ends // with back to the client. No handled error here: a failed request is tried again by the consumer (5 attempts, // 1 s apart) and then rejected, and the client sees its timeout instead. From("rabbitmq://cs-quotes?connectionFactory=rabbit&declare=true") .RouteId("cs-modulectx-quote-server") .Description("Answers a price quote request") .ConvertBody(typeof(string)) .Log("quote requested: ${body}") // The reply is the last body of the route. .Process(exchange => exchange.In.Body = Quote((string)exchange.In.Body!)); } // The quote of a request {"id":..,"amount":..}: the amount with 20 % VAT. private static string Quote(string request) { using var json = JsonDocument.Parse(request); var id = json.RootElement.GetProperty("id").GetString(); var amount = json.RootElement.GetProperty("amount").GetDecimal(); var gross = Math.Round(amount * 1.20m, 2).ToString(CultureInfo.InvariantCulture); return $$"""{"id":"{{id}}","gross":{{gross}}}"""; } } Path: redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rabbitmq/routes/orders.route.xml ---- moved to orders-failed: ${exception.message} order processed: ${body} failed order: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-redb/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/.template.config/agents-scenario.md ---- redb objects (`redb.Route.Core`), `Props/OrderProps.cs` and `routes/orders.route.xml`: `OrderProps` with `[RedbScheme]` is the scheme; `` in `context.xml` brings it up to date at context start. The writer saves one of five orders with `` (the body is `{"name":..., "value_unique":..., "properties":{...}}`, the same `value_unique` updates the same object); the reader runs ``. Facts to keep: `storage="local"` names the redb instance of the context, configured in `config/context.sample.json` under `Contexts.modulectx.Redb.local` (Provider, ConnectionString, UsePro, PropsSaveStrategy, EnsureCreated, cache keys), with `RedbInstanceName` naming the one whose `EnsureCreated` runs; `PropsSaveStrategy` `ChangeTracking` needs `UsePro` true; the worker ships redb and its providers, the module references `redb.Core` only for `[RedbScheme]`; `RoutePackageIncludeAssembly` puts the props classes into the package; `where` and `orderBy` run in the database, an unknown property refuses the route; `` inside `` is not used in this version. Usually changed: the props classes, the query, the provider and connection string, the props cache. `routes/OrdersReportRoute.cs` is a read-only C# report on its own timer (`report.period`): `ProcessWithRedb("local", ...)` gives the `IRedbService` of the same named instance, and the route runs a typed `redb.Query()` LINQ query. Use it for what the `where=` text of `redbQuery` cannot say. Path: redb/redb.Templates/templates/route-xml/redb-route-redb/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Redb", "name": "redb.Route XML module: redb objects", "description": "redb objects from XML routes: a props class saved by a unique key and queried, on Pro; a typed LINQ report in C#.", "shortName": "redb-route-redb", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" }, "db": { "type": "parameter", "datatype": "choice", "choices": [ { "choice": "sqlite", "description": "SQLite: a file next to the worker, no server needed" }, { "choice": "postgres", "description": "PostgreSQL" }, { "choice": "mssql", "description": "SQL Server" } ], "defaultValue": "sqlite", "displayName": "Database", "description": "The database of the redb instance of the context: the provider and the connection string in config/context.sample.json." } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-redb/Props/OrderProps.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/Props/OrderProps.cs ---- using redb.Core.Attributes; namespace RouteModule.Props; /// /// The props of an order object. The class is the scheme: <syncScheme> in context.xml creates /// or updates it at context start, the routes save and query objects of it. A new property is a new /// field of the scheme on the next start; no DDL anywhere. /// [RedbScheme("modulectx order")] public class OrderProps { /// Who ordered. public string Customer { get; set; } = string.Empty; /// The order amount; changes on every save of the demo. public decimal Amount { get; set; } /// The order status. public string Status { get; set; } = "new"; } Path: redb/redb.Templates/templates/route-xml/redb-route-redb/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/README.md ---- # RouteModule A Tsak module that stores objects in redb from XML routes (`urn:redb:route:1.0`). The scheme is a C# class of the project; the routes save and query its objects through a named redb instance of the context, on Pro with ChangeTracking. | Part | What it does | |---|---| | `Props/OrderProps.cs` | the props class with `[RedbScheme]`: customer, amount, status | | `context.xml` | ``: creates or updates the scheme once at context start; adds the C# route builder | | `modulectx-orders-save` | every 3 seconds saves one of five orders again with a new amount: `redbSave byUnique="true"` finds it by `value_unique` and updates it, the store keeps five objects | | `modulectx-orders-query` | every 10 seconds `redbQuery` for the orders over 100, largest first; the condition runs in the database | | `cs-modulectx-orders-report` | C#: every 15 seconds a typed LINQ query for the open orders of ACME, their number and total | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The worker ships redb, its providers and Pro: the module references `redb.Core` only for `[RedbScheme]`, and its own assembly (the props classes) travels in the package. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## The redb instance `storage="local"` names a redb instance of the context, set in `config/context.sample.json` under `Contexts.modulectx`: | Key | Here | What | |---|---|---| | `RedbInstanceName` | `local` | the instance whose `EnsureCreated` runs: it creates the redb tables in an empty database | | `Redb.local.Provider` | `sqlite` (by `--db`) | `sqlite`, `postgres` or `mssql` | | `Redb.local.ConnectionString` | a file next to the worker | the database of the instance | | `Redb.local.UsePro` | `true` | the Pro engine | | `Redb.local.PropsSaveStrategy` | `ChangeTracking` | a save writes only the values that changed instead of deleting and inserting the object's whole value set (`DeleteInsert`, the Free default); needs Pro | | `Redb.local.EnablePropsCache` | `false` | the props cache; size `PropsCacheMaxSize` to the objects the module works with before turning it on, a cache smaller than that evicts what it needs | | `Redb.local.EnableListCache` | `true` | the list cache | | `Redb.local.SkipHashValidationOnCacheCheck` | `false` | keep `false` on a cluster: a cache hit is checked against the object's hash in the database | Another database is two values, `Provider` and `ConnectionString`; the project is created with `--db sqlite` (the default), `--db postgres` or `--db mssql`, which only fills them in. The password of a server database goes into the environment of the worker: Tsak__Contexts__modulectx__Override__Redb__local__ConnectionString: ${ORDERS_DB} ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup and the redb elements against the props class, then writes `pkg/routemodule-1.0.0.tpkg` with `RouteModule.dll` inside. ## Run Copy `config/context.sample.json` as `context.json` next to the package (or put `Contexts.modulectx` into the worker's appsettings under `Tsak:`), and drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The worker log shows `Created named IRedbService 'local' (provider=sqlite, pro=True)`, then `saved order-N` and `orders over 100: N`. ## A typed query in C# `routes/OrdersReportRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own (`report.period`, 15 seconds) it reads the same objects through the same instance `local` and logs `open orders of ACME: 5, total 1500`. It only reads, so it never competes with the XML writer. The difference to notice: XML writes the condition as text (`where="Amount > 100"`), translated and checked when the route is built; C# gets the `IRedbService` of the instance (`ProcessWithRedb("local", ...)`) and writes `redb.Query().Where(o => o.Customer == "ACME" && o.Status == "new")`, checked by the compiler, with all of LINQ at hand. ## Change it - **Your own objects.** Add props classes to `Props/`, one `` each in `context.xml`. - **Reading.** `` loads one object; `` takes `where`, `whereRedb` (base fields: `Id`, `Name`, `DateCreate`, ...), `orderBy`, `take`, `skip` and `outputType` `List`, `First`, `Count` or `Any`. - **Deleting.** ``. - **The default instance.** Leave `storage` out to use the worker's own redb (`Tsak:Redb` in its appsettings). ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-redb/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-redb/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Redb.local is the redb instance the routes use with storage=\"local\". RedbInstanceName names the one", "instance whose EnsureCreated runs (it creates the redb tables in an empty database).", "Another database: change Provider and ConnectionString, nothing else.", " sqlite Data Source=modulectx-redb.db", " postgres Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=...", " mssql Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=...;TrustServerCertificate=true", "UsePro with PropsSaveStrategy ChangeTracking: a save writes only the values that changed instead of", "deleting and inserting the object's whole value set (DeleteInsert, the Free default). ChangeTracking needs Pro.", "Caches: the props cache is off; to turn it on set EnablePropsCache true and size PropsCacheMaxSize to the", "objects the module works with (a cache smaller than that evicts what it needs and gets slower than none).", "The list cache is on. SkipHashValidationOnCacheCheck stays false on a cluster: a cache hit is checked", "against the object's hash in the database, which catches changes made by other nodes." ], "Contexts": { "default": {}, "modulectx": { "orders.period": "3000", "report.period": "15000", "RedbInstanceName": "local", "Redb": { "local": { //#if (db == "sqlite") "Provider": "sqlite", "ConnectionString": "Data Source=modulectx-redb.db", //#elseif (db == "postgres") "Provider": "postgres", "ConnectionString": "Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=change-me", //#else "Provider": "mssql", "ConnectionString": "Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=change-me;TrustServerCertificate=true", //#endif "UsePro": true, "PropsSaveStrategy": "ChangeTracking", "EnsureCreated": true, "EnablePropsCache": false, "PropsCacheMaxSize": 10000, "PropsCacheTtlMinutes": 60, "SkipHashValidationOnCacheCheck": false, "EnableListCache": true, "ListCacheTtlMinutes": 5 } } } } } Path: redb/redb.Templates/templates/route-xml/redb-route-redb/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-redb/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-redb/routes/OrdersReportRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/routes/OrdersReportRoute.cs ---- using System.Globalization; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using RouteModule.Props; namespace RouteModule.Routes; /// /// A sibling of routes/orders.route.xml in C#: a report on the order objects, on a timer of its own, through the /// same named redb instance local. It only reads, with a typed LINQ query on the props class. /// public sealed class OrdersReportRoute : RouteBuilder { protected override void Configure() { // Every {{report.period:15000}} ms the new orders of ACME, their number and their total amount. From("timer://cs-modulectx-orders-report?period={{report.period:15000}}&delay=7000") .RouteId("cs-modulectx-orders-report") .Description("Reports the open orders with a typed query") .ProcessWithRedb("local", async (redb, exchange, ct) => { var open = await redb.Query() .Where(o => o.Customer == "ACME" && o.Status == "new") .ToListAsync(ct); // The scale of a decimal depends on the database; 0.## prints 30, not 30.000000000000000000. var total = open.Sum(o => o.Props.Amount).ToString("0.##", CultureInfo.InvariantCulture); exchange.In.Body = $"open orders of ACME: {open.Count}, total {total}"; }) .Log("${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-redb/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-redb/routes/orders.route.xml ---- saved ${header.orderKey}, amount ${header.CamelTimerCounter * 10} orders over 100: ${body.Count} Path: redb/redb.Templates/templates/route-xml/redb-route-rest/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/.template.config/agents-scenario.md ---- An HTTP JSON API (`redb.Route.Http`), `routes/api.route.xml`: `` with `GET /api/hello/{name}` and `POST /api/orders`. The POST goes to `direct://modulectx-order-in`, which converts the body to text (``, the HTTP body arrives as bytes), checks it against `resources/order.schema.json` and answers 202. `onException` turns a `redb.Route.Validation.ValidationException` into 400. Facts to keep: `port` on `` takes a number, not a `{{key}}`; the status code is the header `redbHttp.ResponseCode`; path parameters arrive as `header.`, query parameters as `header.query.`; the OpenAPI document is served at `/api/openapi.json`. Usually changed: more verbs under ``, the schema in `resources/`, sign-in with `inboundAuth`. `routes/ApiRoute.cs` is the same API in C# with the REST DSL (`this.Rest("/api/cs", ...)`, same port, ids `cs-...`): the schema is the same file compiled in as `EmbeddedResource` (`order.schema.json`) and passed to `ValidateJsonSchema` as text. Path: redb/redb.Templates/templates/route-xml/redb-route-rest/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Rest", "name": "redb.Route XML module: REST API", "description": "An HTTP JSON API in XML markup: a GET with a path parameter, a POST checked by a JSON schema; the same API in C#.", "shortName": "redb-route-rest", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-rest/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/README.md ---- # RouteModule A Tsak module with an HTTP JSON API written in XML markup (`urn:redb:route:1.0`): | Request | Answer | |---|---| | `GET /api/hello/{name}` | `200 {"greeting":"Hello, "}` | | `POST /api/orders` with a body that matches `resources/order.schema.json` | `202 {"accepted":true}` | | `POST /api/orders` with any other body | `400 {"error":"..."}`, the reason goes to the log | | `GET /api/openapi.json` | the OpenAPI document of the API | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `routes/api.route.xml` | the `` block, the POST handler and the error answer | | `routes/ApiRoute.cs` | the same API in C#, under `/api/cs` | | `resources/order.schema.json` | the JSON schema the POST body is checked against, by both forms | | `context.xml` | the C# route builder, and room for beans and the one-time init pipeline | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the endpoint options against the connectors in `bin/`, bean references, resources and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. A broken reference is a build error. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). Then: curl http://localhost:5180/api/hello/world curl -X POST http://localhost:5180/api/orders -H "Content-Type: application/json" -d "{\"id\":\"A-1\",\"amount\":10}" curl -X POST http://localhost:5180/api/orders -H "Content-Type: application/json" -d "{\"id\":\"A-2\"}" ## The same route in C# `routes/ApiRoute.cs` is `routes/api.route.xml` written as a `RouteBuilder` with the REST DSL (`this.Rest(...)`): the same `GET /hello/{name}` and `POST /orders`, the same schema check and 400 answer, under `/api/cs` on the same port 5180. `context.xml` adds it with ``. Both APIs run with the module and share the HTTP host: curl -X POST http://localhost:5180/api/cs/orders -H "Content-Type: application/json" -d "{\"id\":\"A-1\",\"amount\":10}" The difference to notice: XML names the schema file (`file="resources/order.schema.json"`) and the package carries it; C# compiles the same file into the assembly (`EmbeddedResource` in `RouteModule.csproj`) and passes its text to `ValidateJsonSchema`. The OpenAPI document of the C# half is at `/api/cs/openapi.json`. ## Change it - **Port.** `port` on ``, 5180 here. - **Status code.** Set the header `redbHttp.ResponseCode`; no body and no status answer 204. - **More endpoints.** Add ``, ``, ``, `` under ``. A verb takes either `to="direct://..."` or the steps inline. - **Sign-in.** `inboundAuth="basic"` or `inboundAuth="bearer"` with `tokenValidator="#name"` on ``. - **The schema.** Edit `resources/order.schema.json`; the build checks that the file is there. Settings come from the context configuration, not from the package: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. Secrets go into environment variables. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-rest/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-rest/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { } } } Path: redb/redb.Templates/templates/route-xml/redb-route-rest/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-rest/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-rest/resources/order.schema.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/resources/order.schema.json ---- { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Order", "type": "object", "required": [ "id", "amount" ], "properties": { "id": { "type": "string", "minLength": 1 }, "amount": { "type": "number", "exclusiveMinimum": 0 }, "comment": { "type": "string" } }, "additionalProperties": false } Path: redb/redb.Templates/templates/route-xml/redb-route-rest/routes/ApiRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/routes/ApiRoute.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.Http.Rest; using redb.Route.Validation; namespace RouteModule.Routes; /// /// The API of routes/api.route.xml written in C#, under /api/cs on the same port: the same two operations, the same /// schema check and the same 400 answer. Both APIs run with the module and share one HTTP host. /// public sealed class ApiRoute : RouteBuilder { protected override void Configure() { // A body that does not match the schema: answer 400 with a JSON error instead of 500. OnException() .Handled() .Log("request rejected: ${exception.message}", LogLevel.Warning) .SetHeader("redbHttp.ResponseCode", 400) .SetBody("""{"error":"the body does not match resources/order.schema.json"}"""); // The OpenAPI document of this half is served at /api/cs/openapi.json. var api = this.Rest("/api/cs", o => { o.Port = 5180; o.Produces = "application/json"; o.Title = "RouteModule API (C#)"; o.Version = "1.0.0"; }); api.Get("/hello/{name}") .Id("cs-modulectx-hello") .Param("name", RestParamType.Path, dataType: RestParamDataType.String, description: "Who to greet") .Route() .SetBody(Expr("""{"greeting":"Hello, ${header.name}"}""")); api.Post("/orders") .Id("cs-modulectx-orders") .Consumes("application/json") .To("direct://cs-modulectx-order-in"); // The POST handler: check the body, then answer 202. From("direct://cs-modulectx-order-in") .RouteId("cs-modulectx-order-in") .Description("Accepts an order checked against the JSON schema, the C# form") // The HTTP body arrives as bytes; the schema check and the log want the text. .ConvertBody(typeof(string)) .ValidateJsonSchema(OrderSchema) .Log("order accepted: ${body}") .SetHeader("redbHttp.ResponseCode", 202) .SetBody("""{"accepted":true}"""); } // resources/order.schema.json, compiled into this assembly (EmbeddedResource in RouteModule.csproj). private static string OrderSchema { get; } = ReadSchema(); private static string ReadSchema() { using var stream = typeof(ApiRoute).Assembly.GetManifestResourceStream("order.schema.json") ?? throw new InvalidOperationException("order.schema.json is not embedded in the module assembly."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } } Path: redb/redb.Templates/templates/route-xml/redb-route-rest/routes/api.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-rest/routes/api.route.xml ---- request rejected: ${exception.message} order accepted: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-s3/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/.template.config/agents-scenario.md ---- S3 (`redb.Route.S3`), `routes/objects.route.xml`: the bean `s3` (`S3ConnectionFactory`: ServiceUrl, Region, ForcePathStyle, AccessKey, SecretKey) in `context.xml`; every URI says `connectionFactory=s3`. A timer writes `orders/order-N.json` into the bucket `{{s3.inbox:incoming}}` (`keyName` takes expressions); a poll consumer reads the new `*.json` objects under `orders/` and, when the exchange succeeded, moves them to `{{s3.archive:archive}}`. Facts to keep: `moveAfterRead=true` needs `deleteAfterRead=false` written out (delete is the default and the two are refused together at start); an object arrives as bytes, keep `` before text work; headers `redbS3.BucketName`, `redbS3.Key`, `redbS3.ContentLength`, `redbS3.ETag`; `s3.accessKey` and `s3.secretKey` are required keys, the secret from the environment. For AWS: `s3.serviceUrl` empty, a region, `s3.forcePathStyle` false. `deploy/docker-compose.s3.yml` runs RustFS, an S3-compatible store. Usually changed: buckets and prefixes, the include pattern, delete instead of move, what happens to an object. `routes/PriceListRoute.cs` writes and reads CSV price lists in C# under `prices/` of the inbox bucket (own timer `prices.period`, `deleteAfterRead=true`); the key comes from the header `S3Headers.Key`. Keep a C# reader off `orders/`: the XML reader owns that prefix. Path: redb/redb.Templates/templates/route-xml/redb-route-s3/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.S3", "name": "redb.Route XML module: S3", "description": "S3 in XML markup: objects written to a bucket, new ones read and moved to an archive; CSV price lists in C#.", "shortName": "redb-route-s3", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**", "deploy/.env" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-s3/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/README.md ---- # RouteModule A Tsak module that works with S3 buckets (AWS S3, or an S3-compatible store), written in XML markup (`urn:redb:route:1.0`): | Route | What it does | |---|---| | `modulectx-s3-write` | every 20 seconds writes a JSON order as `orders/order-N.json` into the bucket `incoming` | | `modulectx-s3-read` | every 5 seconds reads the new `*.json` objects under `orders/` of `incoming`, one exchange each; when the exchange succeeded the object moves to the bucket `archive`, a failed one stays and is read again | | `cs-modulectx-s3-prices-write`, `cs-modulectx-s3-prices-read` | C#: every 30 seconds a CSV price list as `prices/prices-N.csv` into `incoming`; the reader logs its cheapest item and deletes it | The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `s3` connection: endpoint, region, path style, access key, secret key; the C# route builder | | `routes/objects.route.xml` | the two routes | | `routes/PriceListRoute.cs` | the price list routes in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `deploy/docker-compose.s3.yml` | RustFS, an S3-compatible store, and the module on a Tsak worker | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, every `s3://` option against the connector, the `s3` bean and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No store is needed for the build. ## Try it locally dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 cp deploy/.env.example deploy/.env # then set S3_SECRET_KEY docker compose -f deploy/docker-compose.s3.yml up -d The module log shows `written incoming/orders/order-N.json` and `read orders/order-N.json (... bytes): {...}`; the console of the store on http://localhost:9001 (access key `modulectx`) shows the objects in `archive`. ## Configuration | Key | Default | What | |---|---|---| | `s3.serviceUrl` | `http://localhost:9000` | the endpoint of an S3-compatible store; empty for AWS | | `s3.region` | `us-east-1` | the region | | `s3.forcePathStyle` | `true` | path-style URLs, needed by most S3-compatible stores; `false` for AWS | | `s3.accessKey` | none, required | the access key | | `s3.secretKey` | none, required | the secret key; from the environment | | `s3.inbox` | `incoming` | the bucket the reader polls | | `s3.archive` | `archive` | where processed objects go | | `orders.period` | `20000` | the writer's interval, ms | | `prices.period` | `30000` | the interval of the C# price lists, ms | In a deployment the secret goes into the environment of the worker, in the `Override` section: Tsak__Contexts__modulectx__Override__s3.secretKey: ${S3_SECRET_KEY} On AWS with an instance profile or a task role, set `UseDefaultCredentialsProvider` to `true` on the `s3` bean instead of keys. ## Price lists in C# `routes/PriceListRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. Through the same `s3` bean it writes CSV price lists under `prices/` of the inbox bucket on a timer of its own and reads them back, so it never takes an `orders/*.json` object from the XML reader. The log shows `price list prices/prices-1.csv: cheapest C-3 at 5.25`. The difference to notice: XML names the object in the URI (`keyName=orders/order-${header.CamelTimerCounter}.json`); C# builds the CSV with a `StringBuilder` and sets the key in the header `S3Headers.Key`, and the reader parses the lines with LINQ instead of handing the text on. ## Change it - **Delete instead of move.** Leave out `moveAfterRead`, `deleteAfterRead` and `destinationBucket`: the object is deleted after a successful exchange. - **Wait for a marker.** `doneFileName=${file:name}.done` reads an object only when its `.done` marker exists. - **Read in order.** `sortBy=LastModified` (it lists the whole prefix first). - **Large objects.** `streamBody=true` on the reader, `multiPartUpload=true` on the writer. - **Other operations.** `s3:ListObjects:`, `s3:CopyObject:`, `s3:CreateDownloadLink:` and the rest of the 22 operations of `redb.Route.S3`. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-s3/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-s3/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "s3.accessKey and s3.secretKey are such keys; the secret key goes through the environment.", "AWS S3: s3.serviceUrl empty, s3.region your region, s3.forcePathStyle false." ], "Contexts": { "default": {}, "modulectx": { "s3.serviceUrl": "http://localhost:9000", "s3.region": "us-east-1", "s3.forcePathStyle": "true", "s3.accessKey": "modulectx", "s3.inbox": "incoming", "s3.archive": "archive", "orders.period": "20000", "prices.period": "30000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-s3/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-s3/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-s3/deploy/docker-compose.s3.yml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/deploy/docker-compose.s3.yml ---- # A local S3-compatible store for the module: RustFS (MinIO-compatible, Apache 2.0), and the module on a Tsak worker. # A test stand, not a deployment. # # From the project folder (PowerShell or a POSIX shell alike): # dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/routemodule-1.0.0.tpkg # cp deploy/.env.example deploy/.env # then set S3_SECRET_KEY # docker compose -f deploy/docker-compose.s3.yml up -d # # The store listens on http://localhost:9000 (S3 API) and http://localhost:9001 (web console); the access key is # modulectx, the secret key S3_SECRET_KEY. The module creates the buckets incoming and archive on first use. name: modulectx-s3 services: s3: image: rustfs/rustfs:1.0.3 environment: RUSTFS_ACCESS_KEY: modulectx RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:?S3_SECRET_KEY required, see deploy/.env.example} RUSTFS_CONSOLE_ENABLE: "true" ports: - "127.0.0.1:9000:9000" - "127.0.0.1:9001:9001" volumes: - s3-data:/data module: image: ghcr.io/redbase-app/redb-tsak-worker:${TSAK_VERSION:-4.8.0-net10} depends_on: - s3 environment: - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://module:9090 # The module's context: the Override layer, which wins over every other layer of its configuration. - Tsak__Contexts__modulectx__Override__s3.serviceUrl=http://s3:9000 - Tsak__Contexts__modulectx__Override__s3.accessKey=modulectx - Tsak__Contexts__modulectx__Override__s3.secretKey=${S3_SECRET_KEY:?S3_SECRET_KEY required, see deploy/.env.example} volumes: - ../pkg:/app/modules volumes: s3-data: Path: redb/redb.Templates/templates/route-xml/redb-route-s3/routes/PriceListRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/routes/PriceListRoute.cs ---- using System.Globalization; using System.Text; using redb.Route.Core; using redb.Route.S3; namespace RouteModule.Routes; /// /// A sibling of routes/orders.route.xml in C#: price lists as CSV objects under the prefix prices/ of the same /// inbox bucket, written and read on a trigger of their own through the same s3 connection bean. The XML reader /// takes orders/*.json only, so the two never read the same object. /// public sealed class PriceListRoute : RouteBuilder { protected override void Configure() { // Writer: every {{prices.period:30000}} ms a price list of three items. The object key comes from the header // S3Headers.Key, set in C#, instead of a keyName option in the URI. From("timer://cs-modulectx-s3-prices?period={{prices.period:30000}}") .RouteId("cs-modulectx-s3-prices-write") .Description("Writes a CSV price list into the inbox bucket") .Process(exchange => { var tick = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); var csv = new StringBuilder("sku;price\n"); foreach (var (sku, price) in new[] { ("A-1", 9.50m), ("B-2", 20m), ("C-3", 4.25m) }) csv.Append(sku).Append(';').Append((price + tick).ToString(CultureInfo.InvariantCulture)).Append('\n'); exchange.In.Headers[S3Headers.Key] = $"prices/prices-{tick}.csv"; exchange.In.Body = csv.ToString(); }) .To("s3://{{s3.inbox:incoming}}?connectionFactory=s3&contentType=text/csv&autoCreateBucket=true") .Log("written price list ${header.redbS3.ProducedKey}"); // Reader: the new price lists, deleted once the route finished with them. From("s3://{{s3.inbox:incoming}}?connectionFactory=s3&prefix=prices/&include=*.csv&delay=5000&deleteAfterRead=true&autoCreateBucket=true") .RouteId("cs-modulectx-s3-prices-read") .Description("Reads the price lists and logs the cheapest item") .ConvertBody(typeof(string)) .Process(exchange => { var cheapest = ((string)exchange.In.Body!) .Split('\n', StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Select(line => line.Split(';')) .MinBy(cells => decimal.Parse(cells[1], CultureInfo.InvariantCulture))!; exchange.In.Body = $"{cheapest[0]} at {cheapest[1]}"; }) .Log("price list ${header.redbS3.Key}: cheapest ${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-s3/routes/objects.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-s3/routes/objects.route.xml ---- written ${header.redbS3.ProducedBucketName}/${header.redbS3.ProducedKey}, ETag ${header.redbS3.ETag} read ${header.redbS3.Key} (${header.redbS3.ContentLength} bytes): ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/.template.config/agents-scenario.md ---- Scatter-gather without a broker, `routes/quotes.route.xml`: a timer sends a price request to three `direct://` supplier routes at once with ``; supplier C is slower than the timeout and is left out. Usually changed: the recipients become real endpoints (HTTP, request-reply over a queue, a `sql:` query); the strategy (`groupedBody` keeps every answer, `max:`, `useLatest`, `concat:`); the timeout. `routes/QuoteRoute.cs` sends a second request in C# on its own timer (`bulk.period`) to the same three supplier routes of the XML file (it only produces to their `direct:` names) and folds the answers with a C# function that keeps the whole cheapest answer. Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.ScatterGather", "name": "redb.Route XML module: scatter-gather", "description": "Scatter-gather in XML markup: one request to three suppliers in parallel, the best price in time; a second in C#.", "shortName": "redb-route-scatter-gather", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/README.md ---- # RouteModule A Tsak module that shows scatter-gather in XML markup (`urn:redb:route:1.0`): one request goes to several recipients at once, the answers that arrive in time are folded into one result. It needs no broker. | Route | What it does | |---|---| | `modulectx-quote` | every 3 seconds asks three suppliers for a price at once, waits at most one second and logs the lowest price | | `modulectx-supplier-a` | answers at once | | `modulectx-supplier-b` | answers after 300 ms, sometimes cheaper than A | | `modulectx-supplier-c` | the cheapest, but needs 2 seconds: the request gives up on it and goes on with the others | | `cs-modulectx-quote` | C#: every 5 seconds asks the same three suppliers for 50 pieces and logs the whole best answer | The log shows `best price for item-1: 95` and `Scatter-gather: endpoint direct://modulectx-supplier-c timed out`. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `routes/quotes.route.xml` | the request and the three suppliers | | `routes/QuoteRoute.cs` | a second request in C#, to the same suppliers | | `context.xml` | the C# route builder; room for beans and the one-time init pipeline | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the endpoint options, bean references and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). ## The same request in C# `routes/QuoteRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own (`bulk.period`, 5 seconds) it sends a request for 50 pieces to the three supplier routes of the XML file, with the same one-second timeout, and logs `best price for item-1 x 50: {"supplier":"B","price":95}`. The C# route only sends to the suppliers; the XML routes stay their only consumers. The difference to notice: XML names a strategy (`min:${jpath('$.price')}`) and keeps the price alone; C# passes a function, `(best, next) => Price(next) < Price(best) ? next : best`, which keeps the whole answer of the winning supplier. ## Change it - **Real recipients.** A `` is any endpoint that answers: `https://` with `redb.Route.Http`, a request-reply over `rabbitmq://`, a `sql:` query, a `direct://` route of the module. - **The result.** `strategy` decides it: `min:` and `max:` keep a number, `groupedBody` keeps every answer as a list, `useLatest` the last one, `concat:` joins them. - **Waiting.** `timeout` bounds the whole request; without it the request waits for every recipient. `stopOnException="true"` gives up at the first failing recipient instead of ignoring it. - **Order.** `parallel="false"` asks the recipients one after the other. - **Request period.** `quotes.period` in the context configuration, 3000 ms by default. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "quotes.period": "3000", "bulk.period": "5000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/routes/QuoteRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/routes/QuoteRoute.cs ---- using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; namespace RouteModule.Routes; /// /// The quote request of routes/quotes.route.xml written in C#, on a timer of its own: the same three suppliers /// of the XML file, the same timeout, and the best answer picked by a C# function instead of a strategy name. /// public sealed class QuoteRoute : RouteBuilder { protected override void Configure() { // Every {{bulk.period:5000}} ms a bulk request (50 pieces) goes to the three supplier routes of // the XML file at once; what arrives within one second is folded pair by pair into the lowest price. From("timer://cs-modulectx-quote?period={{bulk.period:5000}}") .RouteId("cs-modulectx-quote") .Description("Asks three suppliers for a price and keeps the best one, the C# form") .SetHeader("item", Expr("item-${header.CamelTimerCounter % 3}")) .SetBody(Expr("""{"item":"${header.item}","qty":50}""")) .ScatterGather(scatter => scatter .Recipients("direct://modulectx-supplier-a", "direct://modulectx-supplier-b", "direct://modulectx-supplier-c") .AggregationStrategy((best, next) => Price(next) < Price(best) ? next : best) .Timeout(TimeSpan.FromSeconds(1)) .ParallelProcessing(true)) .Log("best price for ${header.item} x 50: ${body}"); } // The price of a supplier answer {"supplier":..,"price":..}. private static decimal Price(IExchange answer) { using var json = JsonDocument.Parse(answer.In.Body?.ToString() ?? "{}"); return json.RootElement.GetProperty("price").GetDecimal(); } } Path: redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/routes/quotes.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-scatter-gather/routes/quotes.route.xml ---- best price for ${header.item}: ${body} supplier A quotes ${body} supplier B quotes ${body} supplier C got the request and needs 2 seconds; the request gives up after 1 Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/.template.config/agents-scenario.md ---- SQL batches (`redb.Route.Sql`), `routes/orders.route.xml`: a timer sends single orders (headers `orderId`, `amount`) to `seda://modulectx-orders`; `` makes a batch, and one `sql:INSERT ...?batchSize=100&breakBatchOnError=false` writes it in one transaction, each item binding `:#orderId` and `:#amount` from its own headers. A row the database refuses (the table has `CHECK (amount >= 0)`) is undone under its savepoint and listed in `redbSql.batchErrors`. The connection is the bean `main-db` in `context.xml` with `ProviderName` `Microsoft.Data.Sqlite`, `Npgsql` or `Microsoft.Data.SqlClient`. Key: `db.connection` (SQLite has a default file). Usually changed: the table and the columns; `completionSize` and `completionTimeout` (rows per transaction); `breakBatchOnError` left out for all-or-nothing batches. `routes/OrdersBatchRoute.cs` writes the same table in C# on its own timer (`batch.period`): the body is a `List` of a C# record and `:#orderId`, `:#amount` bind from its properties; no aggregator. Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.SqlBatch", "name": "redb.Route XML module: SQL batch insert", "description": "SQL batches in XML markup: batches of 20 in one transaction each, a bad row skipped and reported; records from C#.", "shortName": "redb-route-sql-batch", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" }, "db": { "type": "parameter", "datatype": "choice", "choices": [ { "choice": "sqlite", "description": "SQLite: a file next to the worker, no server needed" }, { "choice": "postgres", "description": "PostgreSQL" }, { "choice": "mssql", "description": "SQL Server" } ], "defaultValue": "sqlite", "displayName": "Database", "description": "The database the routes work with: the provider, the connection string and the SQL dialect of the table." } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/README.md ---- # RouteModule A Tsak module that writes to a SQL database in batches, written in XML markup (`urn:redb:route:1.0`). | Route | What it does | |---|---| | `modulectx-orders-in` | one test order every 200 ms into the in-memory queue `seda://modulectx-orders`; every seventh one has a negative amount | | `modulectx-orders-batch` | collects 20 orders, or what came within 3 seconds, and writes them with one `INSERT` per row in one transaction; logs how many rows were written and which rows the database refused | | `cs-modulectx-orders-batch` | C#: every 5 seconds builds a batch of 20 typed orders itself and writes it the same way; the seventh row is refused | The table has `CHECK (amount >= 0)`. With `breakBatchOnError=false` every row runs under its own savepoint: a refused row is undone alone and reported in `redbSql.batchErrors`, the other rows of the batch commit. With `breakBatchOnError=true` (the default of the connector) the first refused row rolls back the whole batch and the exchange fails with the database's exception. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `main-db` connection (driver and connection string) and the `CREATE TABLE` that runs before the routes start | | `routes/orders.route.xml` | the two routes | | `routes/OrdersBatchRoute.cs` | the batch route in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration, with the connection strings of all three databases | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Databases The project is created for one database (`--db sqlite`, the default, or `--db postgres`, `--db mssql`). The worker ships the three drivers and registers them under these names: | Database | `ProviderName` in `context.xml` | `db.connection` | |---|---|---| | SQLite | `Microsoft.Data.Sqlite` | `Data Source=modulectx.db` (the default, a file next to the worker) | | PostgreSQL | `Npgsql` | `Host=...;Port=5432;Database=...;Username=...;Password=...` | | SQL Server | `Microsoft.Data.SqlClient` | `Server=...,1433;Database=...;User Id=...;Password=...;TrustServerCertificate=true` | How the statements travel is the driver's choice: one `DbBatch` round trip per `batchSize` statements on PostgreSQL and SQL Server when the batch stops at the first error, a reused command per row on SQLite and whenever every row has its own savepoint. For PostgreSQL and SQL Server `db.connection` has no default, and the module stops at init until the deployment supplies it. ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the bean, the endpoint options and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No database is needed for the build. ## Run 1. Give the context its configuration: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. The password of a server database goes into an environment variable. 2. Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log then shows `batch written: 17 row(s)` every few seconds and a line per refused row. ## The same batch in C# `routes/OrdersBatchRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. On a timer of its own (`batch.period`, 5 seconds) it writes 20 orders `cs-order--` into the same table through the same `main-db` bean, with the same `batchSize` and `breakBatchOnError=false`, and logs the same two kinds of lines. The difference to notice: there is no aggregator. The C# route builds the batch itself as a `List` of a C# record, and each `:#name` binds from a property of the record (`OrderId`, `Amount`) instead of from the headers of an aggregated exchange. ## Change it - **Batch size.** `completionSize` and `completionTimeout` on `` decide how many rows one transaction holds; `batchSize` on the `sql:` endpoint is the number of statements per round trip. - **Where the rows come from.** Each item of the batch binds `:#name` from its own headers (`groupedExchange`). A list of dictionaries, JSON objects or the rows of another `sql:` query works the same way, by key or property name. - **Generated keys.** `INSERT ... RETURNING id` (PostgreSQL, SQLite) or `OUTPUT inserted.id` (SQL Server) with `outputType=SelectList` puts the keys into `redbSql.generatedKeys`. - **All or nothing.** Leave `breakBatchOnError` out, and catch the failure with `onException` or a dead letter channel. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "The connection strings of the other databases, with ProviderName in context.xml:", " Microsoft.Data.Sqlite Data Source=modulectx.db", " Npgsql Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=...", " Microsoft.Data.SqlClient Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=...;TrustServerCertificate=true" ], "Contexts": { "default": {}, "modulectx": { //#if (db == "sqlite") "db.connection": "Data Source=modulectx.db", //#elseif (db == "postgres") "db.connection": "Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=change-me", //#else "db.connection": "Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=change-me;TrustServerCertificate=true", //#endif "orders.period": "200", "batch.period": "5000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/routes/OrdersBatchRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/routes/OrdersBatchRoute.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.Sql; namespace RouteModule.Routes; /// /// The batch write of routes/orders.route.xml in C#, on a timer of its own: instead of aggregating single orders, /// the route builds the batch itself as a list of typed records and writes it into the same orders table through /// the same main-db bean, with the same savepoint per row. /// public sealed class OrdersBatchRoute : RouteBuilder { /// One order of a batch; :#orderId and :#amount bind from its properties. public sealed record Order(string OrderId, int Amount); protected override void Configure() { // Every {{batch.period:5000}} ms a batch of 20 orders; the seventh one has a negative amount, which the // CHECK of the table refuses. From("timer://cs-modulectx-batch?period={{batch.period:5000}}") .RouteId("cs-modulectx-orders-batch") .Description("Writes a batch of typed orders, the C# form") .SetBody(exchange => { var tick = Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"]); return Enumerable.Range(1, 20) .Select(i => new Order($"cs-order-{tick}-{i}", i == 7 ? -i : i)) .ToList(); }) .To("sql:INSERT INTO orders (order_id, amount) VALUES (:#orderId, :#amount)?dataSource=#main-db&batchSize=100&breakBatchOnError=false") .Log("batch written: ${header.redbSql.updateCount} row(s)") // The refused rows, one log line each; the header name is the constant SqlHeaders.BatchErrors. .Filter(exchange => exchange.In.Headers.TryGetValue(SqlHeaders.BatchErrors, out var errors) && errors != null) .Split(Expr("${header.redbSql.batchErrors}")) .Log("row ${body.Index} of the batch refused: ${body.Message}", LogLevel.Warning); } } Path: redb/redb.Templates/templates/route-xml/redb-route-sql-batch/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql-batch/routes/orders.route.xml ---- batch written: ${header.redbSql.updateCount} row(s) row ${body.Index} of the batch refused: ${body.Message} Path: redb/redb.Templates/templates/route-xml/redb-route-sql/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/.template.config/agents-scenario.md ---- SQL outbox (`redb.Route.Sql`), `routes/outbox.route.xml`: a timer inserts rows into `orders_outbox`, a poll consumer (`mode=Poll`) reads the rows with status 0 and sets status 1 (`onSuccess`) or status 2 and the message (`onFailure`, `:#redbError`). The connection is the bean `main-db` (`SqlConnectionFactory`) in `context.xml` with `ProviderName` `Microsoft.Data.Sqlite`, `Npgsql` or `Microsoft.Data.SqlClient`; its `onInit` creates the table in that database's dialect. Facts to keep: parameters are `:#name` bound from `param.name=...`, a header or a column of the polled row; the SQL text must not contain `?`; do not add `transacted=true` to the poll (a failure would roll back its `onFailure` and the row would be read again forever), and do not put an `onException` with `handled="false"` around it in this version. Key: `db.connection` (SQLite has a default file). `routes/OutboxReportRoute.cs` is a C# report on its own timer (`report.period`): a read-only `SELECT status, COUNT(*) ... GROUP BY status` with `outputType=SelectList` through `#main-db`. A C# route must not poll `orders_outbox` for status 0: the XML reader owns those rows. Path: redb/redb.Templates/templates/route-xml/redb-route-sql/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Sql", "name": "redb.Route XML module: SQL outbox", "description": "The SQL outbox in XML markup: a route writes rows, a poll consumer marks them done or failed; a report in C#.", "shortName": "redb-route-sql", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" }, "db": { "type": "parameter", "datatype": "choice", "choices": [ { "choice": "sqlite", "description": "SQLite: a file next to the worker, no server needed" }, { "choice": "postgres", "description": "PostgreSQL" }, { "choice": "mssql", "description": "SQL Server" } ], "defaultValue": "sqlite", "displayName": "Database", "description": "The database the routes work with: the provider, the connection string and the SQL dialect of the table." } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-sql/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/README.md ---- # RouteModule A Tsak module that works with a SQL database, written in XML markup (`urn:redb:route:1.0`). It is the outbox pattern: one route writes rows, a poll consumer reads the new ones and marks each as done or failed. | Route | What it does | |---|---| | `modulectx-outbox-write` | inserts a test order into `orders_outbox` (status 0) every 5 seconds; every fifth one has amount 0 | | `modulectx-outbox-read` | every 2 seconds reads up to 50 rows with status 0, one exchange per row; sets status 1 when the route finished the row, status 2 and the message in `error` when it failed | | `cs-modulectx-outbox-report` | C#: every 30 seconds logs how many rows are new, done and failed (`report.period`) | A failed row does not hold up the others and is not read again; the rows with status 2 wait for a person. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `context.xml` | the `main-db` connection (driver and connection string) and the `CREATE TABLE` that runs before the routes start | | `routes/outbox.route.xml` | the two routes | | `routes/OutboxReportRoute.cs` | the report route in C# | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration, with the connection strings of all three databases | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Databases The project is created for one database (`--db sqlite`, the default, or `--db postgres`, `--db mssql`). The worker ships the three drivers and registers them under these names: | Database | `ProviderName` in `context.xml` | `db.connection` | |---|---|---| | SQLite | `Microsoft.Data.Sqlite` | `Data Source=modulectx.db` (the default, a file next to the worker) | | PostgreSQL | `Npgsql` | `Host=...;Port=5432;Database=...;Username=...;Password=...` | | SQL Server | `Microsoft.Data.SqlClient` | `Server=...,1433;Database=...;User Id=...;Password=...;TrustServerCertificate=true` | To switch later, change `ProviderName`, the connection string and the `CREATE TABLE` in `context.xml`: the column types and the identity column differ between the three. For PostgreSQL and SQL Server `db.connection` has no default, and the module stops at init until the deployment supplies it. ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the bean, the endpoint options and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. No database is needed for the build. ## Run 1. Give the context its configuration: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. The password of a server database goes into an environment variable. 2. Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The log then shows `row N processed` and, for every fifth row, `row N rejected: no amount`. ## A report in C# `routes/OutboxReportRoute.cs` is a `RouteBuilder` that `context.xml` adds with ``. Through the same `main-db` bean it counts the rows per status on a timer of its own and logs `outbox: 0 new, 8 done, 2 failed`. It only reads the table, so it never takes a row from the XML reader, and its query is the same on all three databases. The difference to notice: the XML reader gets one exchange per row with the columns as headers; the C# route sends a `SELECT` with `outputType=SelectList` and gets all rows as a list of column dictionaries, which it folds into one line in C#. ## Change it - **Your own table.** Replace `orders_outbox` in `context.xml` and in both routes; the poll query may select any columns, every column arrives as a header and in the body. - **Parameters.** `:#name` in the SQL binds `param.name=...`, a header or a column of the polled row; a value never becomes SQL text. - **Poll rate.** `delay` (ms between polls) and `maxMessagesPerPoll` on the poll endpoint. - **Writing many rows at once.** See the `redb-route-sql-batch` template. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-sql/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-sql/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing.", "The connection strings of the other databases, with ProviderName in context.xml:", " Microsoft.Data.Sqlite Data Source=modulectx.db", " Npgsql Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=...", " Microsoft.Data.SqlClient Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=...;TrustServerCertificate=true" ], "Contexts": { "default": {}, "modulectx": { //#if (db == "sqlite") "db.connection": "Data Source=modulectx.db", //#elseif (db == "postgres") "db.connection": "Host=localhost;Port=5432;Database=modulectx;Username=modulectx;Password=change-me", //#else "db.connection": "Server=localhost,1433;Database=modulectx;User Id=modulectx;Password=change-me;TrustServerCertificate=true", //#endif "orders.period": "5000", "report.period": "30000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-sql/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-sql/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-sql/routes/OutboxReportRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/routes/OutboxReportRoute.cs ---- using redb.Route.Core; namespace RouteModule.Routes; /// /// A sibling of routes/outbox.route.xml in C#: a report of orders_outbox on a timer of its own, through the same /// main-db bean. It only reads the table, so it never takes a row from the XML reader. /// public sealed class OutboxReportRoute : RouteBuilder { protected override void Configure() { // Every {{report.period:30000}} ms the number of rows per status. The query is the same on SQLite, // PostgreSQL and SQL Server; the rows arrive as a list of column dictionaries. From("timer://cs-modulectx-report?period={{report.period:30000}}") .RouteId("cs-modulectx-outbox-report") .Description("Logs how many outbox rows are new, done and failed") .To("sql:SELECT status, COUNT(*) AS n FROM orders_outbox GROUP BY status?dataSource=#main-db&outputType=SelectList") .Process(exchange => { var counts = new int[3]; foreach (var row in (IEnumerable>)exchange.In.Body!) counts[Convert.ToInt32(row["status"])] = Convert.ToInt32(row["n"]); exchange.In.Body = $"outbox: {counts[0]} new, {counts[1]} done, {counts[2]} failed"; }) .Log("${body}"); } } Path: redb/redb.Templates/templates/route-xml/redb-route-sql/routes/outbox.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-sql/routes/outbox.route.xml ---- row ${header.id} rejected: no amount row ${header.id} processed: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/.template.config/agents-scenario.md ---- XML documents without a broker, `routes/orders.route.xml`: a timer builds an order document, `` checks it and `` turns it into an invoice. A document the schema refuses throws `redb.Route.Validation.ValidationException`; `onException` (handled) passes it with the reason in the header `rejectReason` to `direct://modulectx-rejected`. Facts to keep: stylesheets and schemas are files under `resources/` and are named by that path; the built-in engine is XSLT 1.0 (`XslCompiledTransform`); `validateJsonSchema` is the same step for JSON. Usually changed: the timer becomes `file://`, `sftp://`, an HTTP endpoint or a queue; the schema and the stylesheet; what happens to a rejected document (an error folder, a reply to the sender). `routes/OrdersRoute.cs` runs the same check and transformation in C# on its own timer (`cs.orders.period`) and its own `direct:` rejected route: the document comes from LINQ to XML, the schema and stylesheet are the same files of `resources/` as `EmbeddedResource` (`order.xsd`, `order-to-invoice.xslt`), passed to `ValidateXsd` and `XsltContent`. Edit the files once; both forms read them. Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.ValidatorXslt", "name": "redb.Route XML module: XSD check and XSLT", "description": "XML documents in XML markup: an XSD check, an XSLT transformation, a rejected document routed; the same in C#.", "shortName": "redb-route-validator-xslt", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/README.md ---- # RouteModule A Tsak module that checks XML documents against a schema and transforms them with XSLT, written in XML markup (`urn:redb:route:1.0`). It needs no broker. | Route | What it does | |---|---| | `modulectx-orders` | every 3 seconds builds an order document, checks it against `resources/order.xsd`, turns it into an invoice with `resources/order-to-invoice.xslt` and logs it; every fourth order has a line with quantity 0 | | `modulectx-rejected` | logs the documents the schema refused, with the reason | | `cs-modulectx-orders`, `cs-modulectx-rejected` | C#: the same two routes on a timer of their own (every 5 seconds), order ids `cs-order-` | The log shows `invoice: ...` and, for every fourth order, `order rejected: Validation failed: ... The 'qty' attribute is invalid`. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `routes/orders.route.xml` | the check, the transformation and the error handling | | `routes/OrdersRoute.cs` | the same routes in C# | | `resources/order.xsd` | the schema of an order, for both forms | | `resources/order-to-invoice.xslt` | the stylesheet: positions with their amounts and the total, for both forms | | `context.xml` | the C# route builder; room for beans and the one-time init pipeline | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup and that every file a route names is under `resources/`, then writes `pkg/routemodule-1.0.0.tpkg` with the `resources/` folder inside. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). ## The same route in C# `routes/OrdersRoute.cs` is `routes/orders.route.xml` written as a `RouteBuilder`, on a timer of its own (`cs.orders.period`, 5 seconds) and a rejected route of its own. `context.xml` adds it with ``. Both forms run with the module and log the same lines, the C# ones for `cs-order-`. The difference to notice: XML writes the document as text and names the files of `resources/`; C# builds the document with LINQ to XML (`new XElement("order", ...)`), and gets the same two files compiled into the assembly (`EmbeddedResource` in `RouteModule.csproj`), passed as text to `ValidateXsd` and `XsltContent`. ## Change it - **Real input.** Replace the timer with `file://inbox`, `sftp://`, an HTTP endpoint or a queue; the check and the transformation stay. - **The schema.** `validateXsd` takes `file` and, for a namespaced schema, `targetNamespace`. `throwOnFailure="false"` lets the document through and only reports. - **The stylesheet.** The engine is XSLT 1.0; `output` picks what the body becomes (text, bytes or a document). - **JSON.** `` is the same step for JSON bodies. - **Rejected documents.** `modulectx-rejected` only logs; write them to an error folder or answer the sender instead. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "orders.period": "3000", "cs.orders.period": "5000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/resources/order-to-invoice.xslt Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/resources/order-to-invoice.xslt ---- Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/resources/order.xsd Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/resources/order.xsd ---- Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/routes/OrdersRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/routes/OrdersRoute.cs ---- using System.Xml.Linq; using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.Validation; namespace RouteModule.Routes; /// /// The route of routes/orders.route.xml written in C#, on a timer of its own: the same schema check, the same /// stylesheet and the same rejected path. The order document is built with LINQ to XML, and the schema and /// stylesheet are the files of resources/ compiled into this assembly. /// public sealed class OrdersRoute : RouteBuilder { protected override void Configure() { // A document that does not match the schema: the exchange ends, the reason goes to the rejected route. OnException() .Handled() .SetHeader("rejectReason", Expr("${exception.message}")) .To("direct://cs-modulectx-rejected"); // Every {{cs.orders.period:5000}} ms a test document; every fourth one has a line with qty 0. From("timer://cs-modulectx-orders?period={{cs.orders.period:5000}}") .RouteId("cs-modulectx-orders") .Description("Checks an XML order against the XSD and turns it into an invoice, the C# form") .SetBody(exchange => Order(Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"])).ToString(SaveOptions.DisableFormatting)) .ValidateXsd(Resource("order.xsd")) .XsltContent(Resource("order-to-invoice.xslt")) .Log("invoice: ${body}"); From("direct://cs-modulectx-rejected") .RouteId("cs-modulectx-rejected") .Description("Logs the documents the schema refused, the C# form") .Log("order rejected: ${header.rejectReason}", LogLevel.Warning); } // The same document as the XML route writes as text. private static XElement Order(int tick) => new("order", new XAttribute("id", $"cs-order-{tick}"), new XElement("customer", "ACME"), new XElement("line", new XAttribute("sku", "A-1"), new XAttribute("qty", tick % 4 == 3 ? 0 : 2), new XAttribute("price", "9.50")), new XElement("line", new XAttribute("sku", "B-2"), new XAttribute("qty", 1), new XAttribute("price", "20"))); // A file of resources/, embedded under its file name (EmbeddedResource in RouteModule.csproj). private static string Resource(string name) { using var stream = typeof(OrdersRoute).Assembly.GetManifestResourceStream(name) ?? throw new InvalidOperationException($"{name} is not embedded in the module assembly."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } } Path: redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-validator-xslt/routes/orders.route.xml ---- invoice: ${body} order rejected: ${header.rejectReason} Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/.template.config/agents-scenario.md ---- XML to JSON and back without a class, no broker. `context.xml` declares ``. `routes/orders.route.xml` builds an XML order on a timer, checks it with `validateXsd` (`targetNamespace="urn:example:orders"`), turns it into JSON with `` and posts it to the module's own API on port 5181. `routes/api.route.xml` is that API: ``, `validateXsd` again, 202; `onException` answers 400 for `JsonException`, `InvalidOperationException` (a key the schema has no place for) and `ValidationException`. Facts to keep: the schema decides arrays (`maxOccurs` above 1, so one `Item` is still an array), JSON numbers and booleans from the XSD types, and on the way back the namespace and the order of the children; `arrays=` adds element paths the schema does not describe (`xs:any`); the notation is Json.NET's (`@attr`, `#text`). `marshal` writes bytes: `convertBody type="System.String"` before a log. JSON to XML does not check required elements, `validateXsd` after it does. Options go on the named instance, not on the step. When the document has a class, the typed `unmarshal`/`marshal` with `application/xml` and `application/json` is the better path. `routes/OrdersRoute.cs` runs the same round trip in C# on its own timer (`cs.orders.period`), id `cs-modulectx-orders`: `MarshalXmlJson(o => ...)` and `UnmarshalXmlJson(o => ...)` with `SchemaSet` compiled from the embedded `order.xsd`, without the HTTP hop. Usually changed: the timer becomes `file://`, `sftp://` or a queue and the POST a partner URL; the schema; `arrays=` for content under `xs:any`. Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.XmlJson", "name": "redb.Route XML module: XML to JSON and back", "description": "XML documents without a class in XML markup: XML to JSON by an XSD, an HTTP API that turns JSON back into XML; the same round trip in C#.", "shortName": "redb-route-xmljson", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/README.md ---- # RouteModule A Tsak module that turns XML documents into JSON and back without a class for them, written in XML markup (`urn:redb:route:1.0`). An XSD decides which elements are arrays, which values are numbers and booleans and, on the way back, the namespace and the order of every element. It needs no broker. | Route | What it does | |---|---| | `modulectx-orders` | every 3 seconds builds an XML order, checks it against `resources/order.xsd`, turns it into JSON and posts it to the module's own API | | `POST /api/orders` | port 5181: turns the JSON back into XML, checks it against the same schema, answers 202; a body that is not an order gets 400 with the reason in the log | | `cs-modulectx-orders` | C#: the same round trip on a timer of its own (every 5 seconds), XML to JSON and straight back, order ids `cs-order-` | The log shows, for an order of one item: json: {"Order":{"@id":"order-0","Customer":"ACME","Express":true,"Items":{"Item":[{"Sku":"A-1","Qty":2,"Price":9.50}]}}} xml: ACME... api answered: {"accepted":true} `Item` is an array although the order has one, because the schema says it repeats; `Qty` and `Price` are numbers and `Express` a boolean, because of their schema types. The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## When a class exists, use it This module is for documents without a class: a partner format you only pass on, a schema too large to map by hand, or a gateway that turns any XML into JSON for a JavaScript consumer. When the document has a class, the typed path validates and names every field: ``, then ``. ## Layout | Path | What | |---|---| | `context.xml` | the `orders-json` data format and the C# route builder | | `routes/orders.route.xml` | the XML order, its check, XML to JSON, the POST | | `routes/api.route.xml` | the API: JSON to XML, the check, 202 or 400 | | `routes/OrdersRoute.cs` | the same round trip in C# | | `resources/order.xsd` | the schema of an order, for both forms | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration: `orders.period`, `cs.orders.period` | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## The data format `context.xml` declares one named instance and the routes refer to it by name: ```xml ``` The JSON is in Json.NET's notation: an attribute is `"@id"`, the text of an element with attributes `"#text"`. `namespaces="Drop"` writes local names (`"Order"`); without it the names keep their prefixes and the declarations appear as `"@xmlns:p"` keys. On the way back the schema gives every element its namespace and puts the children in the order of the sequence, whatever the order of the keys; `prefixes=` names the prefix (without it, `ns0`). `marshal` writes UTF-8 bytes, so the route converts them to text before the log. After `marshal` the content type is `application/json`, which the API's `consumes` expects. ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, that `resources/order.xsd` is there and compiles, and that every `arrays=` path names an element of the schema, then writes `pkg/routemodule-1.0.0.tpkg` with the `resources/` folder inside. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker (`dotnet new tsak-worker` from `redb.Tsak.Templates`, or the `redb-tsak-worker` image). The worker ships `redb.Route.DataFormats.XmlJson`, so the package carries only this project's assembly. Post an order of your own, and one the schema refuses: curl -X POST -H "Content-Type: application/json" http://localhost:5181/api/orders \ -d '{"Order":{"@id":"o-1","Customer":"ACME","Express":false,"Items":{"Item":[{"Sku":"A-1","Qty":1,"Price":5}]}}}' curl -X POST -H "Content-Type: application/json" http://localhost:5181/api/orders \ -d '{"Order":{"@id":"o-2","Customer":"ACME","Discount":5}}' The second answers 400; the log says `order refused: xmljson: /Order/Discount: the content of /Order in the schema has no place for 'Discount'`. ## The same round trip in C# `routes/OrdersRoute.cs` is a `RouteBuilder` next to the XML routes, on a timer of its own (`cs.orders.period`, 5 seconds). `context.xml` adds it with ``. The difference to notice: XML names one shared instance in `context.xml`; C# passes the same options on each step, `MarshalXmlJson(o => ...)` and `UnmarshalXmlJson(o => ...)`, with the schema compiled once from the file of `resources/` built into the assembly (`EmbeddedResource` in `RouteModule.csproj`) and handed over as `SchemaSet`. The C# route skips the HTTP hop and turns the JSON straight back. ## Change it - **Real input.** Replace the timer with `file://inbox`, `sftp://` or a queue, and the POST with the partner's URL; the checks and the conversion stay. - **Your schema.** Put it under `resources/` and point `schema=` at it. A schema with imports reads them from the package only, never from the network: `schemaRoot=` is the folder they may come from. - **Arrays the schema does not know.** Content under `xs:any` has no schema answer: list the repeating elements, `arrays="//Item,//Tag"`. Without a schema, `arrays=` is the only rule besides the document itself. - **Names.** `namespaces="Keep"` keeps the prefixes in JSON; `textKey` and `attributePrefix` change `#text` and `@` (`$` for a WSO2 consumer); `indent="true"` for readable output. - **Required elements.** JSON to XML places the keys the JSON has; whether the required ones are all there is `validateXsd`'s job, which is why the API checks after the step. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "orders.period": "3000", "cs.orders.period": "5000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/resources/order.xsd Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/resources/order.xsd ---- Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/OrdersRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/OrdersRoute.cs ---- using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using redb.Route.Core; using redb.Route.DataFormats.XmlJson; namespace RouteModule.Routes; /// /// The round trip of routes/orders.route.xml and routes/api.route.xml written in C#, on a timer of its own: an XML /// order to JSON and straight back to XML, without the HTTP hop. The options the XML gives a named format in /// context.xml are set on each step here, and the schema is the file of resources/ compiled into this assembly. /// public sealed class OrdersRoute : RouteBuilder { private const string OrdersNs = "urn:example:orders"; // One compiled schema for the checks and for the format; it is only read. private static readonly XmlSchemaSet Schema = LoadSchema(); protected override void Configure() { // Every {{cs.orders.period:5000}} ms an order: the even ones have one Item, the odd ones two. From("timer://cs-modulectx-orders?period={{cs.orders.period:5000}}") .RouteId("cs-modulectx-orders") .Description("Turns an XML order into JSON and back, the C# form") .SetBody(exchange => Order(Convert.ToInt32(exchange.In.Headers["CamelTimerCounter"])).ToString(SaveOptions.DisableFormatting)) .ValidateXsd(Schema) .MarshalXmlJson(Options) .ConvertBody(typeof(string)) .Log("cs json: ${body}") .UnmarshalXmlJson(Options) .ValidateXsd(Schema) .Log("cs xml: ${body}"); } // The options of in context.xml, with the schema already compiled. private static void Options(XmlJsonOptions options) { options.SchemaSet = Schema; options.Namespaces = XmlJsonNamespaces.Drop; options.Prefixes["o"] = OrdersNs; } // The same document the XML route writes as text. private static XElement Order(int tick) { XNamespace ns = OrdersNs; var items = new XElement(ns + "Items", Item(ns, "A-1", 2, "9.50")); if (tick % 2 == 1) items.Add(Item(ns, "B-2", 1, "20")); return new XElement(ns + "Order", new XAttribute("id", $"cs-order-{tick}"), new XElement(ns + "Customer", "ACME"), new XElement(ns + "Express", tick % 3 == 0 ? "true" : "false"), items); } private static XElement Item(XNamespace ns, string sku, int qty, string price) => new(ns + "Item", new XElement(ns + "Sku", sku), new XElement(ns + "Qty", qty), new XElement(ns + "Price", price)); // resources/order.xsd, embedded under its file name (EmbeddedResource in RouteModule.csproj). private static XmlSchemaSet LoadSchema() { using var stream = typeof(OrdersRoute).Assembly.GetManifestResourceStream("order.xsd") ?? throw new InvalidOperationException("order.xsd is not embedded in the module assembly."); using var reader = XmlReader.Create(stream); var set = new XmlSchemaSet(); set.Add(OrdersNs, reader); set.Compile(); return set; } } Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/api.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/api.route.xml ---- order refused: ${exception.message} xml: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/orders.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route-xmljson/routes/orders.route.xml ---- json: ${body} api answered: ${body} Path: redb/redb.Templates/templates/route-xml/redb-route/.template.config/agents-scenario.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/.template.config/agents-scenario.md ---- The base template: one route, `routes/main.route.xml`, a timer that writes a line to the log every `{{hello.period:5000}}` ms. `context.xml` is empty apart from commented examples. Usually changed: the timer becomes a connector endpoint (`rabbitmq://`, `kafka://`, `sql:`, `file://`, an HTTP endpoint); add the connector package to the `.csproj` and its connection as a bean in `context.xml`. `routes/HelloRoute.cs` is the same route in C# (`cs-modulectx-hello`, its own timer); both run with the module. Path: redb/redb.Templates/templates/route-xml/redb-route/.template.config/template.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/.template.config/template.json ---- { "$schema": "http://json.schemastore.org/template", "author": "RedBase", "classifications": [ "Integration", "XML", "Tsak", "RedBase", "RouteXml" ], "identity": "RedBase.Route.Xml.Basic", "name": "redb.Route XML module", "description": "A Tsak module with routes in XML markup: a timer that writes to the log, and the same route in C#.", "shortName": "redb-route", "tags": { "type": "project", "redbSmoke": "pack" }, "sourceName": "RouteModule", "preferNameDirectory": true, "symbols": { "context": { "type": "parameter", "datatype": "string", "defaultValue": "", "displayName": "Context name", "description": "The route context the module runs in. Empty: the module name in lower case." }, "nameLower": { "type": "generated", "generator": "casing", "parameters": { "source": "name", "toLower": true }, "fileRename": "routemodule" }, "contextName": { "type": "generated", "generator": "coalesce", "parameters": { "sourceVariableName": "context", "fallbackVariableName": "nameLower" }, "replaces": "modulectx" } }, "sources": [ { "exclude": [ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json", "pkg/**", "schema/**" ] } ] } Path: redb/redb.Templates/templates/route-xml/redb-route/README.md Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/README.md ---- # RouteModule A Tsak module whose routes are written in XML markup (`urn:redb:route:1.0`). The module is a package (`.tpkg`) that a Tsak worker loads from its `modules/` folder; there is no `Main` to run. The project targets net10.0, the framework of the Tsak worker that loads it: a module built for net11.0 does not load in that worker. ## Layout | Path | What | |---|---| | `routes/*.route.xml` | the routes | | `routes/HelloRoute.cs` | the same route in C#, a `RouteBuilder` | | `context.xml` | components, context-wide beans, the one-time init pipeline, the C# route builders | | `resources/` | XSLT and schema files the routes refer to (create the folder when needed) | | `config/routemodule.config.json` | identity inside the package: context name and auto start | | `config/context.sample.json` | deployment sample of the context configuration | | `.config/dotnet-tools.json` | the `redb-route-xml` tool, same version as the redb packages | ## Build the package dotnet tool restore dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 The build checks the markup, the endpoint options against the connectors in `bin/`, bean references and the configuration keys, then writes `pkg/routemodule-1.0.0.tpkg`. A broken reference is a build error. `dotnet redb-route-xml check .` runs the same checks without writing the package. ## Run Drop `pkg/routemodule-.tpkg` into the `modules/` folder of a Tsak worker. A worker of your own comes from `dotnet new install redb.Tsak.Templates` and `dotnet new tsak-worker`, or use the `redb-tsak-worker` image. The worker loads the package within seconds and the log shows `hello from RouteModule` every 5 seconds, and the same line from the C# route. Settings come from the context configuration, not from the package: copy `config/context.sample.json` as `context.json` next to the package, or put the keys into the worker's appsettings under `Tsak:Contexts:modulectx`. Secrets go into environment variables. ## The same route in C# `routes/HelloRoute.cs` is `routes/main.route.xml` written as a `RouteBuilder`: the same steps, the same `{{hello.period:5000}}` key, the same log, on a timer of its own (`cs-modulectx-hello`). `context.xml` adds it to the context with ``, and `RoutePackageIncludeAssembly` puts `RouteModule.dll` into the package. Both routes run with the module: the log shows `hello from RouteModule` and `hello from RouteModule (C#)` every 5 seconds. The difference to notice: the XML route is markup checked by the build, the C# one is a class checked by the compiler; a step reads the same in both. ## Add a connector Add the connector package at the same version and use its scheme in a route: The worker image already ships the connectors; the reference is there so the build-time check knows the endpoint options. ## Editor The `redb Route XML` extension for VS Code (`redb.redb-route-xml`) binds the schema by namespace and completes elements and endpoint options. Without the extension, generate the schema from the build output and point the XML extension at it: dotnet redb-route-xml xsd bin/Debug/net10.0 --out schema ## More - Diagram of a route: `dotnet redb-route-xml mermaid routes/main.route.xml` - C# from a route: `dotnet redb-route-xml csharp routes/main.route.xml --namespace RouteModule.Routes` - Documentation: [redbase.app](https://redbase.app) Path: redb/redb.Templates/templates/route-xml/redb-route/RouteModule.csproj Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/RouteModule.csproj ---- routemodule true Path: redb/redb.Templates/templates/route-xml/redb-route/config/context.sample.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/config/context.sample.json ---- { "//": [ "Deployment sample: copy it as context.json next to the package on the host. Never put real secrets here.", "The merged configuration, later layers win:", " 1. host appsettings, Contexts default section", " 2. host appsettings, this context's section", " 3. this file: Contexts.default, then Contexts.modulectx", " 4. in-package config/routemodule.config.json: ContextName and AutoStart only", " 5. Override: environment variables (secrets live here)", "Every {{key}} without a {{key:default}} in the XML must get a value from one of these layers:", "the built package lists them in manifest.json under RequiredConfigKeys, and the module stops at init when one is missing." ], "Contexts": { "default": {}, "modulectx": { "hello.period": "5000" } } } Path: redb/redb.Templates/templates/route-xml/redb-route/config/routemodule.config.json Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/config/routemodule.config.json ---- { "//": "In-package identity only. Settings and secrets come from the merged context configuration, see config/context.sample.json.", "ContextName": "modulectx", "AutoStart": true } Path: redb/redb.Templates/templates/route-xml/redb-route/context.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/context.xml ---- Path: redb/redb.Templates/templates/route-xml/redb-route/routes/HelloRoute.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/routes/HelloRoute.cs ---- using redb.Route.Core; namespace RouteModule.Routes; /// /// The route of routes/main.route.xml written in C#: the same configuration key and the same log, on a timer of /// its own. Both routes run with the module. /// public sealed class HelloRoute : RouteBuilder { protected override void Configure() { // {{hello.period:5000}} reads the same key as the XML route; 5000 ms when it is not set. From("timer://cs-modulectx-hello?period={{hello.period:5000}}") .RouteId("cs-modulectx-hello") .Description("Writes a line to the log on every tick, the C# form") .SetBody("hello from RouteModule (C#)") .To("log://modulectx"); } } Path: redb/redb.Templates/templates/route-xml/redb-route/routes/main.route.xml Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/route-xml/redb-route/routes/main.route.xml ----