Bundle: redb-tsak / root files (_root.txt), 16 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-tsak Index: https://redbase.app/src/dev-2026-12-06/redb-tsak/_index.txt ==== Path: redb-tsak/API_GUIDE.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/API_GUIDE.md ---- # redb.Tsak — Management API Guide What the REST API is, how it is wired, and why a runtime container needs this many endpoints. Written so you can answer those questions **without opening `src/`**. > Operators and integrators: this is the reference for driving a Tsak node from > curl, CI, Kubernetes, or your own C# service. For deployment see > [DEPLOYMENT.md](DEPLOYMENT.md), for settings see [CONFIG_GUIDE.md](CONFIG_GUIDE.md). --- ## 1. Where the API lives The management API is **not** a separate ASP.NET application bolted onto the worker. It is a redb.Route context named `_system`, started by `SystemContextBuilder` alongside your own module contexts, on the same runtime, with the same lifecycle. ``` Tsak worker process ├── _system ← the management API (this document) ├── orders ← your module context └── billing ← your module context ``` Consequences that matter in practice: - `tsak context list` shows `_system` next to your contexts. It has routes, metrics, and in-flight exchanges like any other context — the API can be observed by itself. - One HTTP listener, one port: `Tsak:Api:Host` / `Tsak:Api:Port` (default `0.0.0.0:9090`). - The whole API can be switched off with `Tsak:Api:Enabled=false` — the worker then runs your routes headlessly, with no control plane exposed. - The Web dashboard is a **separate** process/port (default `5100`) and is just another client of this API. Nothing in the API depends on the UI being deployed. --- ## 2. How a request is served There is exactly **one** route for the whole API — a catch-all HTTP listener whose `Process` block is the entire pipeline: ``` HTTP request │ ▼ from("http:0.0.0.0:9090/{**path}") ← single listener, single socket │ ├─ BridgeHttpHeaders redbHttp.* → route.* + query.* headers │ ├─ AuthorizeProcessor skipped when path matches Tsak:Api:AuthExempt │ └─ KeyedThrottleProcessor per-IP gate, only on /api/auth/* │ ├─ ControllerDispatcherProcessor path/method → controller method │ └─ AuthController, ContextsController, HealthProbeController, … │ └─ PrepareHttpResponse object → JSON, status code, content type ``` Controllers are plain classes deriving from `RedbController` (from `redb.Route.Controllers`), annotated with `[Route]` / `[HttpGet]` / `[HttpPost]` / `[FromQuery]`. They are discovered by **assembly scan**, so adding an endpoint means adding a method — no registration, no DI wiring, no change to `SystemContextBuilder`. Pro contributes its own controllers by registering an `ISystemContextPlugin`, which hands additional assemblies to the same registry. Inside a controller you work with Route primitives, not ASP.NET ones: `Exchange` for the message, `Context.GetService()` for dependencies, `ApiResponse.*` + `Exchange.Stop()` to short-circuit with a status code. ### The three routes that are *not* controllers Two endpoints need to bypass the shared pipeline, so they are registered as their own routes on the same port (path specificity makes them out-rank the catch-all): | Route id | Path | Why it is standalone | |---|---|---| | `system-echo` | `/api/echo` (`Tsak:Api:Echo:Path`) | Own pipeline with **no** auth processor, and `AutoStart(false)` so it can be started/stopped on demand from the Routes API or dashboard. Reflects the request back as JSON — "am I reaching the host, and what did it actually receive?" While stopped, the catch-all answers the path with `503` naming the route to start (not `401`). | | `system-metrics` | `/metrics` | Proxies the loopback OpenTelemetry scrape listener so Prometheus can scrape the main port. Returns `text/plain; version=0.0.4`, not JSON. Mounted only when `Tsak:Metrics:Prometheus:Enabled=true`. | The **health probes are not** in this list — they are ordinary controllers (`HealthProbeController`), because they need nothing special: authentication is skipped declaratively via `Tsak:Api:AuthExempt`, and their response is plain JSON. --- ## 3. Why there are this many endpoints Every endpoint exists to answer a question you would otherwise answer by SSH-ing into the box, reading log files, or restarting the process and hoping. The API surface is the set of operational questions a route runtime gets asked: | Question | Endpoints | Who asks | |---|---|---| | *Is the process alive / ready for traffic?* | `/api/health/*` | Kubernetes, load balancers | | *What is actually running right now?* | `/api/contexts`, `.../routes`, `/api/modules`, `/api/dashboard` | operators, UI | | *Why is this route stuck?* | `.../inflight`, `.../force-stop`, `/api/watchdog/*`, `/api/diagnostics/*` | on-call | | *What happened just before it broke?* | `/api/lifecycle`, `/api/logs*` | on-call | | *Who did what, and when?* | `/api/audit` | admins, compliance | | *How much is it costing me?* | `/api/system/metrics`, `/metrics/history`, `.../routes/{id}/metrics`, Prometheus `/metrics` | monitoring | | *Deploy / roll a module without downtime* | `/api/contexts/{name}/start`, `/stop`, `/restart`, `/api/modules/{name}` DELETE | CI/CD | | *What is the cluster doing?* | `/api/cluster/*` | operators (Pro) | | *When does this job fire, and can I pause it?* | `/api/scheduler/*` | operators | | *Who is allowed to do all of the above?* | `/api/auth/keys*`, `/api/users*` | admins | The design rule: anything the dashboard can show, the API can return, and anything the API can do, the `tsak` CLI can do — so a human, a script, and the UI are never on unequal footing. --- ## 4. Endpoint map **71 endpoints across 16 controllers.** All speak JSON. 14 controllers ship in `redb.Tsak.Core`; `ClusterController` comes from `redb.Tsak.Core.Pro` via `ISystemContextPlugin`. ### Health probes — `/api/health` (5, auth-exempt) | Method | Path | 200 when | |---|---|---| | GET | `/api/health/startup` | contexts are loaded and the cluster coordinator has synced | | GET | `/api/health/live` | process is responsive; no hung exchanges reported by the watchdog | | GET | `/api/health/ready` | full health evaluation is not `Unhealthy` | | GET | `/api/health/deploy` | a new package can be hot swapped into this node (`409`: deploy it cold) | | GET | `/api/health/deploy/cluster` | every alive node of the cluster can take a hot swap (`409`: at least one cannot) | Failures of the first three return `503` with a short reason. Bodies are intentionally minimal — kubelet does not read them. See §6 for the rich variant, and "Deploy advice" below for the last two. ### Deploy advice — `/api/health/deploy` An orchestrator or a CI/CD step (Kubernetes job, TeamCity) asks before it deploys a package: drop it into `modules/` of the running node, or deploy it cold. The status code alone is the answer; the endpoint only advises and changes nothing. | Status | `verdict` | What the pipeline does | |---|---|---| | `200` | `hot-swap` | copy the `.tpkg` into `modules/` of the running node | | `409` | `cold-deploy` | cordon the node, stop it, replace the packages in `modules/` while it is down, start it, wait for `/api/health/ready`, uncordon | A cold deploy is not "restart, then hot swap": a restart with the old packages followed by a swap leaves one more old version in memory for nothing. The steps for Kubernetes and for compose with TeamCity are in DEPLOYMENT.md, "Deploy advice in a pipeline". ```json { "nodeId": "worker-1", "verdict": "cold-deploy", "reasons": ["orphaned-contexts-above-limit"], "moduleContextsAlive": 21, "orphanedModuleContexts": 7, "maxOrphanedModuleContexts": 5, "workingSetMb": 812.4, "maxWorkingSetMb": null, "collectible": false, "timestamp": "2026-11-02T12:00:00Z" } ``` | Reason | When | |---|---| | `orphaned-contexts-above-limit` | more old module versions stay in memory than `Tsak:HotReload:MaxOrphanedContexts` allows | | `next-swap-exceeds-limit` | with `Collectible=false` every swap leaves its old version in memory, and the next one would go above the limit | | `working-set-above-limit` | the working set is above `Tsak:HotReload:MaxWorkingSetMb` (no limit unless set) | | `node-cordoned` | the node is cordoned (Pro cluster): it is in maintenance | | `startup-not-finished` | `/api/health/startup` would answer `503` | | `node-unreachable` | cluster form only: the node is alive in the registry, but its own `/api/health/deploy` did not answer | `/api/health/deploy/cluster` asks the same of every alive node in one call, on any node: the answering node advises itself and asks each other node at the `ApiEndpoint` it registered. The body is `{ "verdict", "answeredBy", "nodes": [ ...one advice per node... ] }`, and the status is `200` only when every node says `hot-swap`. Outside a cluster the list holds the answering node alone. Both endpoints are open like the probes: a pipeline step asks without a dashboard session or an API key. The body holds the node id, the verdict, the reason codes and the counts behind them (module contexts, working set, the `Collectible` flag). No configuration, connection, route or module name is in it, so it tells a caller nothing it could use against the node. Client `GetDeployAdviceAsync` / `GetClusterDeployAdviceAsync` (a `409` comes back as the answer, not as an exception), CLI `tsak system deploy-advice [--cluster]` (exit code `0` hot-swap, `3` cold-deploy, `1` and `2` errors). ### System — `/api/system` (5) | Method | Path | Returns | |---|---|---| | GET | `/api/system/health` | aggregated health with per-component statuses | | GET | `/api/system/metrics` | latest CPU / memory / GC / thread snapshot | | GET | `/api/system/metrics/history` | stored metric points for charting | | GET | `/api/system/info` | version, uptime, machine info, module contexts in memory (`ModuleContextsAlive`, `OrphanedModuleContexts`) | | GET | `/api/system/config` | effective merged config (`Tsak:*`/`ConnectionStrings:*`), secrets redacted (`admin`) | `/api/system/config` answers "what settings is this node actually on" on an incident — a flat key→value map with sensitive keys masked and connection-string passwords stripped. `admin` only (it reveals topology). Client `GetConfigAsync`, CLI `tsak system config`. ### Contexts — `/api/contexts` (8) | Method | Path | Purpose | |---|---|---| | GET | `/api/contexts` | list all contexts with status and counts | | GET | `/api/contexts/{name}` | one context in detail | | POST | `/api/contexts/{name}/start` | start | | POST | `/api/contexts/{name}/stop` | graceful stop | | POST | `/api/contexts/{name}/restart` | stop + start | | POST | `/api/contexts/{name}/reset-route-states` | clear persisted per-route start/stop state | | GET | `/api/contexts/{name}/endpoints` | endpoints exposed by the context, with health | | DELETE | `/api/contexts/{name}` | remove the context | ### Routes — `/api/contexts/{name}/routes` (8) Routes live under their context, which is why they share the `/api/contexts` prefix. | Method | Path | Purpose | |---|---|---| | GET | `.../routes` | list routes of a context | | GET | `.../routes/{routeId}` | one route in detail | | POST | `.../routes/{routeId}/start` | start a single route | | POST | `.../routes/{routeId}/stop` | graceful stop of a single route | | POST | `.../routes/{routeId}/force-stop` | abandon in-flight work and stop | | GET | `.../routes/{routeId}/inflight` | exchanges currently inside this route | | GET | `/api/contexts/{name}/inflight` | in-flight exchanges across the whole context | | GET | `.../routes/{routeId}/metrics` | per-route counters and timings | `inflight` + `force-stop` are the pair you reach for when a route will not drain: look at what is stuck, then decide whether to abandon it. ### Modules — `/api/modules` (6) | Method | Path | Purpose | |---|---|---| | GET | `/api/modules` | loaded modules, versions, origin (`.tpkg` or bare directory) | | GET | `/api/modules/{name}` | module detail | | DELETE | `/api/modules/{name}` | unload a module and shut down its contexts gracefully | | POST | `/api/modules/upload` | deploy a signed `.tpkg` (admin; **off by default**) | | POST | `/api/modules/validate` | dry-run: validate a `.tpkg` without installing (admin) | | POST | `/api/modules/{name}/rollback` | restore the previous on-disk version (admin) | A package update is **staged**: the new `.tpkg` is loaded and checked in a throwaway ALC before the running version is torn down, so a broken package leaves the live context running. Upload/rollback deploy **executable code**, so they are disabled by default (`Tsak:Modules:Upload:Enabled`), admin-only, audited, and gated by signature verification. The full trust model — the two verification boundaries, the two "require signature" switches, and the keygen/sign flow — is in **[MODULE_DEPLOYMENT.md](MODULE_DEPLOYMENT.md)**. ### Watchdog — `/api/watchdog` (6) | Method | Path | Purpose | |---|---|---| | GET | `/api/watchdog/status` | suspected / hung exchange counters | | GET | `/api/watchdog/alerts` | recent alerts | | POST | `/api/watchdog/enable` | turn detection on at runtime | | POST | `/api/watchdog/disable` | turn it off (e.g. during a known long batch) | | GET | `/api/watchdog/alerts/status` | is alert delivery active, and which channels are enabled | | POST | `/api/watchdog/test-alert` | send a synthetic alert through every enabled channel (per-channel result) | New alerts are pushed to configurable channels (all off by default): **webhook**, **telegram**, **email** (all native, no extra deps) and a generic **endpoint** channel that sends to any redb.Route producer URI (`kafka:`, `rabbitmq:`, `amqp:`, `sqs:`, `mqtt:` …) — one channel for every broker, no per-connector code. Delivery is fire-and-forget with dedup by incident. Configure under `Tsak:Watchdog:Alerts`; verify with `test-alert`. ### Diagnostics & lifecycle — `/api/diagnostics`, `/api/lifecycle` (3) | Method | Path | Purpose | |---|---|---| | GET | `/api/diagnostics/dump` | full dump — GC, threads, contexts, routes (cluster-wide) | | GET | `/api/diagnostics/{contextName}/{routeId}` | route-scoped diagnostics | | GET | `/api/lifecycle` | recent lifecycle events, filterable by context and limit | ### Audit — `/api/audit` (1, admin) | Method | Path | Purpose | |---|---|---| | GET | `/api/audit?actor=&action=&target=&since=&until=&limit=&offset=` | persisted admin-action trail, newest-first | Every mutating admin action (marked `[AuditAdminAction]`) is persisted to the flat `tsak_audit_log` table — who, what, target, status, duration, source IP — and survives restarts. Requires the `admin` role: the trail records who did what, so it must not be enumerable by a lower-privilege caller. Without a database the trail lives in the log instead (a `[tsak-audit]`-anchored JSON line) and this endpoint reports `available: false`. Filtering and paging are **server-side** (the table can be large): `limit` is clamped to 1..1000, `offset` pages. Exposed through `ITsakApiClient.GetAuditAsync`, the `tsak audit` CLI command, and the dashboard **Audit** page. ### Dead-letter queue — `/api/exchanges` (3) | Method | Path | Purpose | |---|---|---| | GET | `/api/exchanges/failed?context=&route=&status=&since=&until=&limit=&offset=` | failed exchanges, newest-first (`operator`) | | POST | `/api/exchanges/{id}/replay` | re-run the entry's route tail from its snapshot (`operator`) | | DELETE | `/api/exchanges/{id}` | discard an entry (`admin`) | An exchange that fails at a redb.Route **replay checkpoint** (`.Replayable("…")` in the route) is captured into the flat `tsak_dlq` table — snapshot, route, marker, exception. **Opt-in by construction**: only routes carrying a marker leave a checkpoint, so the DLQ never tries to own an exchange a broker/transaction already redelivers. The capture is the context's error handler, so it takes the failures no `OnException` took — an `OnException` that takes one owns it, as in Apache Camel, and dead-letters it explicitly with `.To("tsak-dlq:")`. A module's own `` runs after the capture. Replay rehydrates the snapshot and re-runs the route tail (the tail gets fresh redb/SQL connections). Replay is **at-least-once + manual** — make replayed side-effects idempotent. Client `GetFailedExchangesAsync`/`ReplayExchangeAsync`, CLI `tsak dlq`, dashboard **Dead-letter** page. Without a database the endpoint reports `available: false`. ### Logs — `/api/logs` (3) | Method | Path | Purpose | |---|---|---| | GET | `/api/logs?afterId=&limit=&level=` | ring-buffer entries; `afterId` makes tailing incremental | | GET | `/api/logs/files` | list rolling log files with size and mtime | | GET | `/api/logs/files/{filename}` | download one file as a ZIP | ### Scheduler — `/api/scheduler` (8) | Method | Path | Purpose | |---|---|---| | GET | `/api/scheduler/status` | the node's summary (started / standby / stopped, job counts) and `schedulers[]`, one entry per context | | GET | `/api/scheduler/scheduled` | every scheduled job with its context, triggers and next fire time | | GET | `/api/scheduler/jobs` | jobs **currently executing**, with their context | | POST | `/api/scheduler/start?context=` | start the schedulers — of one context, or all | | POST | `/api/scheduler/standby?context=` | pause firing without losing schedules — one context, or all | | POST | `/api/scheduler/pause-job?key={jobKey}&context=` | pause one job | | POST | `/api/scheduler/resume-job?key={jobKey}&context=` | resume it | | POST | `/api/scheduler/fire-job?key={jobKey}&context=` | fire a job immediately, out of schedule (`operator`) | Every context runs its own Quartz scheduler, and a job key is unique within it only: two modules may both schedule `redb.nightly`. `context` is optional. Without it a job action finds the key in the one context that has it; a key held by several contexts is refused (`success: false`) with their names — never guessed. The summary fields of `status` sum the contexts (`isStarted`: all started, `inStandbyMode`: at least one in standby). ### Cluster — `/api/cluster` (6, Pro) | Method | Path | Purpose | |---|---|---| | GET | `/api/cluster` | leader, epoch, membership, assignment state | | GET | `/api/cluster/nodes` | node list with heartbeats and `cordoned` flag | | POST | `/api/cluster/rebalance` | force a reassignment pass | | DELETE | `/api/cluster/nodes/{nodeId}` | evict a dead node from the registry | | POST | `/api/cluster/nodes/{nodeId}/cordon` | cordon a node — keeps current work, takes no new work, drains locks to peers | | POST | `/api/cluster/nodes/{nodeId}/uncordon` | uncordon — resume taking work | Cordon is the graceful middle state for planned maintenance / rolling upgrade: `remove-node` is a hard eviction, `cordon` lets the node drain first. A cordoned node stays Online (heartbeating) but its clustered route locks release to peers. ### Auth & users — `/api/auth`, `/api/users` (8) | Method | Path | Purpose | |---|---|---| | POST | `/api/auth/keys` | create an API key (raw value returned **once**) | | GET | `/api/auth/keys` | list key metadata — never the secrets | | DELETE | `/api/auth/keys/{id}` | revoke a key | | GET | `/api/users` | list users | | GET | `/api/users/{login}` | one user | | POST | `/api/users` | create | | PUT | `/api/users/{login}` | update | | DELETE | `/api/users/{login}` | delete | `/api/users` is backed by redb's user provider, so it requires a redb-backed storage mode — in standalone/in-memory mode there is nothing to store users in. ### Dashboard — `/api/dashboard` (1) | Method | Path | Purpose | |---|---|---| | GET | `/api/dashboard` | one aggregated snapshot: metrics + contexts + top routes + alerts | Exists so the UI renders a screen with a single round-trip instead of six. --- ## 5. Authentication Auth is **opt-in**: `Tsak:Auth:Enabled` (default `false`). With it off, every endpoint is open — appropriate only for a private network or a local dev box. With it on, each request carries a key in either form: ``` Authorization: Bearer tsak_xxxxxxxx X-Api-Key: tsak_xxxxxxxx ``` - Keys are created via `/api/auth/keys` and carry roles; see **Roles** below. - Failures are `401` (missing/invalid key) or `403` (valid key, insufficient roles). - `/api/auth/*` is additionally rate-limited per remote IP — `Tsak:Api:AuthThrottle:Limit` (default 10) per `WindowSeconds` (default 60). Set the limit to `0` to disable. - `Tsak:Api:AuthExempt` lists paths that skip auth entirely. Default: `["/api/health/*", "/api/health"]`. A trailing `*` is a prefix match; otherwise the match is exact and case-insensitive. ### Roles Every key carries a comma-separated role list. Three roles form a ladder — a higher one satisfies any requirement for a lower one: | Role | May do | |---|---| | `viewer` | every `GET`: contexts, routes, modules, metrics, health, lifecycle, dashboard | | `operator` | plus lifecycle actions — start / stop / restart contexts and routes, scheduler control, watchdog toggle, diagnostics dumps, log access | | `admin` | plus API keys, users, module removal, context removal, route `force-stop`, cluster rebalance and node eviction | Custom roles (any other string) are matched by exact name only — `admin` does **not** satisfy a requirement for `release-bot`. Endpoints declare their requirement with `[RequiresRole(...)]` on the action or the controller. An endpoint with no attribute falls back to a safe default derived from the HTTP method: `GET` needs `viewer`, everything else needs `operator` — a newly added endpoint is therefore never open by accident. **Technical endpoints are never role-gated.** The check runs only for authenticated requests, so the auth-exempt Kubernetes probes pass straight through; on top of that `HealthProbeController` is marked `[NoRoleRequired]`, so even if an operator narrows `Tsak:Api:AuthExempt`, a probe can start requiring a key but will never answer `403` — a probe rejected on privileges would take a healthy pod out of rotation. The echo and Prometheus routes have their own pipelines and never reach the check at all. Two switches control the behaviour: - `Tsak:Auth:EnforceRoles` (default `true`) — turn role checking off entirely. - `Tsak:Auth:RolelessKeysAreAdmin` (default `true`) — keys issued before roles were enforced carry no roles; they keep working as `admin` and log a one-time warning. Set to `false` to deny them once all keys have been re-issued with explicit roles. **Deployment note.** Three things answer without a key: the health probes (by the exempt list) plus `/api/echo` and `/metrics` (own pipelines). None of them expose business data, but all three confirm the node exists and `/metrics` describes its load — keep the API port on an internal network or behind an ingress rule rather than on the public internet. `/api/echo` additionally ships stopped (`AutoStart(false)`), so it answers only after somebody starts it. --- ## 6. Health: two endpoints, two audiences | | `/api/health/{startup,live,ready}` | `/api/system/health` | |---|---|---| | Audience | kubelet, load balancers | humans, CLI, dashboard | | Auth | exempt by default | subject to auth | | Body | `{"status":"ok"}` or `503` + reason | full `HealthCheckResult` with per-check statuses | | Cost | minimal | runs every contributor | `HealthCheckService` aggregates the built-in `contexts` / `routes` / `metrics` / `watchdog` / `control-plane` / `redb` / `hotreload` checks with two extension points, and **never throws**: an exception inside a probe becomes `Unhealthy`, not a `500`. Worst status wins: `Unhealthy` > `Degraded` > `Healthy`. A check that is not healthy can say why in `details` (keyed like `checks`), and the `description` repeats it: ```json { "status": "Degraded", "description": "Some checks degraded. redb: 1 schema problem(s) need a person. [host] REDB schema problem: root field 'Total' of scheme 'Order' (id 7) exists 2 times ... See https://github.com/redbase-app/redb/blob/main/UPGRADING.md#duplicate-root-structures", "checks": { "contexts": "Healthy", "metrics": "Healthy", "control-plane": "Healthy", "redb": "Degraded" }, "details": { "redb": "1 schema problem(s) need a person. [host] REDB schema problem: ..." }, "timestamp": "2026-10-22T09:00:00Z" } ``` `redb` is `Degraded` while a redb database of the worker, the host's own or a named instance a context declares (`[context/name]` in the text), has schema problems that need a person: a root field of a scheme written twice by nodes of an older redb, for example. The service keeps working, and redb logs the problem as an error at every start until it is resolved by hand (redb UPGRADING.md, "Duplicate root structures"); the check makes it visible to monitoring. It reads the list the last start or scheme synchronization left (`IRedbService.SchemaProblems`), so a health poll queries no database. A worker without redb storage has no `redb` check. `routes` is `Unhealthy` while a started context has an `Errored` route: its consumer failed to start and waits for redb.Route's start retry (`RedbRoute:ConsumerStartRetry`), or the retries ran out, so the route takes no messages. The detail names up to ten routes, `"2 route(s) Errored: orders/orders-in, billing/invoices-in."`, and counts the rest. Apache Camel reports such a route DOWN since 4.7, and its two switches are here too: `RedbRoute:ConsumerStartRetry:UnhealthyOnRestarting` (a route waiting for a retry) and `UnhealthyOnExhausted` (a route no retry waits for) set to `false` make that phase `Degraded`, which readiness passes unless `Tsak:Health:DegradedNotReady=true`. `/api/health/live` does not read the check. `hotreload` is `Degraded` while more module contexts stay in memory after their modules were replaced or removed than `Tsak:HotReload:MaxOrphanedContexts` allows (default `KeepVersions + 3`); the detail ends with "restart the node to reclaim memory". The same count is `OrphanedModuleContexts` in `/api/system/info`. See DEPLOYMENT.md, "After a series of hot swaps". - `IHealthContributor` — sees the whole evaluation bag. Pro's `ClusterHealthContributor` uses it to report leader and member health. - `IModuleHealthContributor` — per-module probe, published under the key `module:{name}`. Implement it in your module to surface "my downstream is unreachable" to `/api/health/ready`, which is what makes Kubernetes take the pod out of rotation. Note that `Degraded` still returns `200` on readiness; only `Unhealthy` is a `503`. A deployment that wants a degraded node out of rotation sets `Tsak:Health:DegradedNotReady=true`, and the `503` then carries the description. --- ## 7. Four ways to call it ```bash # 1. curl — everything is JSON curl -s http://localhost:9090/api/health/ready -o /dev/null -w '%{http_code}\n' curl -s -H "X-Api-Key: $KEY" http://localhost:9090/api/system/health | jq ``` ```bash # 2. tsak CLI — same operations, tabular or --output json for CI tsak context list tsak system health tsak route inflight orders route-1 ``` ```csharp // 3. Typed C# client — ITsakApiClient covers the whole surface services.AddSingleton(_ => new TsakApiClient("http://tsak-prod:9090", key)); public class Ops(ITsakApiClient tsak) { public async Task RestartFailedAsync(CancellationToken ct) { foreach (var c in (await tsak.ListContextsAsync(ct)).Where(c => c.Status == "Failed")) await tsak.RestartContextAsync(c.Name, ct); } } ``` 4. **Web dashboard** — a Blazor app on its own port that consumes exactly the endpoints above. --- ## 8. Extending the API | You want to… | Do this | |---|---| | add endpoints from a Pro/host assembly | implement `ISystemContextPlugin`, return your assembly from `GetControllerAssemblies()`, register it in DI | | require a specific role on an endpoint | annotate the action or controller with `[RequiresRole(TsakRoles.Admin)]` | | expose a technical endpoint that must never 403 | annotate it `[NoRoleRequired]` and add its path to `Tsak:Api:AuthExempt` | | report module health to k8s | implement `IModuleHealthContributor` in the module | | add a system-wide health check | implement `IHealthContributor` | | expose an endpoint without auth | add its path to `Tsak:Api:AuthExempt` | | expose an endpoint that needs its own pipeline | register a route on the API port — a concrete path out-ranks the `{**path}` dispatcher | --- ## 9. Configuration keys | Key | Default | Effect | |---|---|---| | `Tsak:Api:Enabled` | `true` | build and start the `_system` context at all | | `Tsak:Api:Host` | `0.0.0.0` | listener bind address | | `Tsak:Api:Port` | `9090` | listener port (shared by API, echo, `/metrics`) | | `Tsak:Auth:Enabled` | `false` | require an API key | | `Tsak:Auth:EnforceRoles` | `true` | enforce `[RequiresRole]` on endpoints (no effect when auth is off) | | `Tsak:Auth:RolelessKeysAreAdmin` | `true` | keys with no roles keep full access (back-compat); `false` denies them | | `Tsak:Api:AuthExempt` | `["/api/health/*", "/api/health"]` | paths that skip auth | | `Tsak:Api:AuthThrottle:Limit` | `10` | per-IP attempts on the auth prefix; `0` disables | | `Tsak:Api:AuthThrottle:WindowSeconds` | `60` | throttle window | | `Tsak:Api:AuthThrottle:PathPrefix` | `/api/auth/` | what the throttle covers | | `Tsak:Api:Echo:Path` | `/api/echo` | echo route path | | `Tsak:Metrics:Prometheus:Enabled` | `false` | mount `/metrics` on the API port | | `Tsak:Metrics:Prometheus:Port` | `9464` | loopback OTel listener being proxied | | `Tsak:Audit:Enabled` | `true` | persist admin actions to `tsak_audit_log` (falls back to log with no DB) | | `Tsak:Audit:RetentionDays` | `90` | prune audit entries older than this; `0` keeps forever | | `Tsak:Dlq:Enabled` | `true` | capture failed exchanges (at route checkpoints) into `tsak_dlq` | | `Tsak:Dlq:RetentionDays` | `30` | prune DLQ entries older than this; `0` keeps forever | | `Tsak:Health:DegradedNotReady` | `false` | when `true`, the readiness probe also returns `503` on `Degraded` | | `Tsak:HotReload:MaxOrphanedContexts` | `KeepVersions + 3` | old module versions in memory before `hotreload` is Degraded and the deploy advice says `cold-deploy` | | `Tsak:HotReload:MaxWorkingSetMb` | none | working set (MB) above which the deploy advice says `cold-deploy` | | `Tsak:Modules:Upload:Enabled` | `false` | enable `POST /api/modules/upload` + `/rollback` (RCE surface — keep off unless needed) | | `Tsak:Modules:Signature:Required` | `false` | refuse unsigned/tampered `.tpkg` at load (needs `PublicKeyPath`) | --- ## See also - [README.md](README.md) — the project as a whole - [CONFIG_GUIDE.md](CONFIG_GUIDE.md) — the 5-layer configuration model - [DEPLOYMENT.md](DEPLOYMENT.md) — running the published images - [deploy/README.md](deploy/README.md) — Kubernetes manifests with the probes already wired - [SECURITY.md](SECURITY.md) — hardening and vulnerability reporting Path: redb-tsak/CHANGELOG.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/CHANGELOG.md ---- # Changelog — redb.Tsak All notable changes to redb.Tsak are documented in this file. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). --- ## Projects | Project | Description | |---------|-------------| | `redb.Tsak.Core` | Kernel: contracts, services, security, cluster, hot-reload, monitoring | | `redb.Tsak.Core.Pro` | Pro features: redb-backed key store, cluster topology | | `redb.Tsak.Worker` | Hosted process: DI wiring, Serilog, Quartz, Dockerfile | | `redb.Tsak.Contracts` | Shared wire DTOs | | `redb.Tsak.Client` | `ITsakApiClient` / `TsakApiClient` — HTTP client | | `redb.Tsak.CLI` | `tsak` command-line tool — 30 commands | | `redb.Tsak.Web` | Blazor Server dashboard — 10 pages | | `redb.Tsak.Web.Pro` | Pro web extensions | | `redb.Tsak.Templates` | `dotnet new` template pack — the `tsak-worker` host | --- > **Note on version history:** redb.Tsak has been running in production since version 1.0.0. > Versions 1.0.0 – 1.0.3 were not published to NuGet (internal deployments only). > The first public NuGet release is **1.0.4**. --- ## [Unreleased] Pending changes live in `changelog/unreleased/` until the release; `pwsh scripts/changelog.ps1 -Preview` shows them. ## [4.8.0] — 2026-12-01 ### Breaking - **`ITsakApiClient` has a new member, `GetLogsBeforeAsync`.** A class of your own that implements the interface (a test double, a wrapper) adds it; code that only calls the client is not affected. Packages: `redb.Tsak.Client`. Upgrade: [UPGRADING.md](UPGRADING.md#itsakapiclient-has-getlogsbeforeasync). - **Tsak no longer has licence code.** `ITsakLicenseManager`, `TsakLicenseManager`, `TsakLicenseNodeLimitException`, `LicenseConfigReader` and `ClusterOptions.LicenseCheckIntervalIterations` are removed, and `ClusterCoordinator` and `RedbNodeRegistry` lose their licence parameter. A cluster has no node limit; a `License` setting is ignored. Packages: `redb.Tsak.Core`, `redb.Tsak.Core.Pro`, `redb.Tsak.Web.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#no-licence-code-any-more). - **An `Errored` route makes the node not ready.** A route whose consumer failed to start (a broker not up yet) used to leave `/api/health/ready` at `200`; the new `routes` check is now Unhealthy and names the route until the start retry starts it, so readiness answers `503`. Liveness is unchanged. Packages: `redb.Tsak.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#an-errored-route-makes-the-node-not-ready). - **The redb.Tsak libraries target .NET 10 and .NET 11; .NET 8 and .NET 9 are no longer targets.** Both reached end of support on 10 November 2026. A host or module on .NET 8 or 9 stays on 4.7.x or moves to .NET 10. The worker and the dashboard stay .NET 10 applications. Upgrade: [UPGRADING.md](UPGRADING.md#net-10-and-net-11-only). ### Added - **`GET /api/logs?beforeId=` pages the node's log buffer backwards.** It returns the entries older than the given id, newest first (200 by default), for a "load older" view; `TsakApiClient.GetLogsBeforeAsync` calls it. `afterId` and `beforeId` cannot be combined. Packages: `redb.Tsak.Core`, `redb.Tsak.Client`. - **The worker's `RedbRoute` section applies to every module context**: the consumer start retry, thread pool profiles, attachment limits and the other route engine options. Before, Tsak ignored the section and ran each context on the defaults. The REST API's own context keeps the defaults. Packages: `redb.Tsak.Core`. - **A node switcher in the dashboard's top bar.** On a cluster the chip shows the node of the page; its list shows every node with its state (up or down and since when, leader, cordoned, version) and opens the same page, sub-page and address query on the chosen node. Keys: `n` opens it, `[` and `]` go to the previous and next node of the group. A page of a node that is down says so above its content; a route that is not on the chosen node says that too. Packages: `redb.Tsak.Web`. ### Changed - **Tsak 4.8.0 and its images run on redb 4.8.0 and redb.Route 4.8.0.** The worker's store takes the redb 4.8.0 database upgrade at its first start; all nodes of one cluster database move to 4.8.0 together, as the redb 4.8.0 upgrade notes describe. Packages: `redb.Tsak.Core`, `redb.Tsak.Worker`. - **The dashboard keeps a page's filters in its address.** The time range of a node page, the status filter of Routes, the type of Endpoints, the search of Dead-letter and Audit, and the tab, level and search of Logs now survive a reload, a shared link and a change of node. Packages: `redb.Tsak.Web`. - **The dashboard's log page keeps what it has read of each node while the browser tab is open.** Coming back to a node shows its lines at once and reads only the new ones; lines the node dropped meanwhile show as "N lines skipped", a restart of the node starts the view anew, "load older" pages back through the node's buffer, and long views scroll without slowing down. The filter works on the lines already read. Packages: `redb.Tsak.Web`. - **Microsoft dependencies move to the 10.0.15 servicing line.** Microsoft.Extensions.*, Microsoft.Data.Sqlite, System.Security.Cryptography.Xml / Pkcs and the ASP.NET Core packages are referenced at 10.0.15 (was 10.0.13). An application that pins one of them lower raises its pin. - **The worker and stack images check liveness instead of a running process.** Their Docker `HEALTHCHECK` now calls `GET /api/health/live` on the management API, so a hung worker shows as unhealthy; a route that failed to start does not. A deployment that overrides `HEALTHCHECK` sees no change; one with `Tsak:Api:Enabled=false` or the API bound to one non-loopback address overrides it (DEPLOYMENT.md, "Container health"). ### Fixed - **Stored dead-letter bodies and attachments and base64 module signatures read the same on .NET 10 and .NET 11.** A base64 value whose last character has non-zero unused bits, refused by .NET 11, is decoded as .NET 10 decodes it. ## Earlier versions Earlier releases are archived by line in [changelog/](changelog/): [4.7.x](changelog/CHANGELOG-4.7.x.md), [4.6.x](changelog/CHANGELOG-4.6.x.md), [4.5.x](changelog/CHANGELOG-4.5.x.md), [4.4.x](changelog/CHANGELOG-4.4.x.md), [4.3.x](changelog/CHANGELOG-4.3.x.md), [4.2.x](changelog/CHANGELOG-4.2.x.md), [4.1.x](changelog/CHANGELOG-4.1.x.md), [4.0.x](changelog/CHANGELOG-4.0.x.md), [3.x](changelog/CHANGELOG-3.x.md), [2.x](changelog/CHANGELOG-2.x.md), [1.x](changelog/CHANGELOG-1.x.md). The worker's development log of March 2026, before the versioned releases, is [changelog/worker-devlog-2026-03.md](changelog/worker-devlog-2026-03.md). Path: redb-tsak/CONFIG_GUIDE.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/CONFIG_GUIDE.md ---- # redb.Tsak Configuration Guide This guide is about **how** configuration is assembled: the five layers, how they merge, and which one wins. For **what** each setting is called and what it defaults to, see [PARAMETERS.md](PARAMETERS.md). ## 5-Layer Configuration Model redb.Tsak uses a 5-layer configuration model where each layer merges over the previous one. Later layers always win on conflicts. Nested objects are deep-merged (not replaced wholesale). ``` Layer 1: Tsak:Contexts:default ← base settings for ALL contexts Layer 2: Tsak:Contexts:{name} ← per-context overrides Layer 3: context.json (from modules/) ← module infrastructure defaults Layer 4: {Module}.config.json (modules/) ← module builder settings Layer 5: Tsak:Contexts:{name}:Override ← DevOps last word (always wins) ``` ### Layer Priority (lowest → highest) | Layer | Source | Who writes it | Purpose | |-------|--------|---------------|---------| | 1 | `appsettings.json` → `Tsak:Contexts:default` | Operator | Base defaults for all contexts | | 2 | `appsettings.json` → `Tsak:Contexts:{name}` | Operator | Per-context settings | | 3 | `modules/{Module}/context.json` | Module developer | Module infrastructure defaults | | 4 | `{Module}.config.json` inside the `.tpkg` | Module developer | The package's own config, module identity (`ContextName`, `AutoStart`) above all | | 4 | `modules/{Module}/{Module}.config.json` | Module developer / operator | Module builder/business settings; beside a `.tpkg` it overrides the package's own, without repacking | | 5 | `appsettings.json` → `Tsak:Contexts:{name}:Override` | DevOps | Final override (always wins) | Whether a context starts on its own: a start or stop an operator made through the API (kept by the worker) first, then `Tsak:Contexts:{name}:AutoStart` in appsettings, then `AutoStart` from the merged layers above (a package's `"AutoStart": false` is honoured), and `true` when nothing says otherwise. ## Configuration Examples ### appsettings.json ```json { "Tsak": { "Contexts": { "default": { "AutoStart": true, "RabbitMQ": { "Host": "rabbitmq.local", "Port": 5672, "VirtualHost": "/" } }, "api": { "Modules": ["Api.Orders", "Api.Catalog"], "RabbitMQ": { "VirtualHost": "/api" }, "Override": { "RabbitMQ": { "Host": "prod-rabbit.internal" } } } } } } ``` In this example, the `api` context will get: - `RabbitMQ.Host` = `"prod-rabbit.internal"` (from Override, layer 5) - `RabbitMQ.Port` = `5672` (inherited from default, layer 1) - `RabbitMQ.VirtualHost` = `"/api"` (from named context, layer 2) - `AutoStart` = `true` (inherited from default, layer 1) ### Module Config Files Module developers can ship config files alongside their DLLs in the `modules/` directory: ``` modules/ Api.Orders/ Api.Orders.dll context.json ← Layer 3: infrastructure defaults Api.Orders.config.json ← Layer 4: builder/business settings ``` **context.json** — infrastructure defaults the module needs: ```json { "RabbitMQ": { "Exchange": "orders", "QueuePrefix": "orders." }, "Redis": { "Database": 2 } } ``` **{Module}.config.json** — business/builder settings: ```json { "OrderProcessing": { "MaxRetries": 3, "TimeoutSeconds": 30 }, "FeatureFlags": { "EnableBulkImport": true } } ``` ### Deep Merge Behavior Nested objects are merged recursively, not replaced. Example: ``` default: { "RabbitMQ": { "Host": "a", "Port": 5672 } } named context: { "RabbitMQ": { "Host": "b" } } ───────────────────────────────────────────────────── result: { "RabbitMQ": { "Host": "b", "Port": 5672 } } ``` Port is preserved from default while Host is overridden by the named context. ## Reserved Keys The following keys are reserved and excluded from context configuration: - `Modules` — array of module names assigned to a named context - `Override` — the DevOps override section (layer 5) ## Hot Reload Config files (`context.json`, `{Module}.config.json`) are monitored by the hot-reload service. When a config file changes on disk, the affected module's context is automatically recreated with the updated configuration. No restart required. ### How it works 1. Each scan cycle checks timestamps of known config files 2. If a config file has changed since the last scan, the module's context is recreated 3. The full 5-layer merge is re-executed with the new file contents 4. The context is restarted automatically (if AutoStart is enabled) ## Accessing Config in Routes Configuration values are set as context properties. Access them in your route modules: ```csharp public class OrdersRoute : RouteBuilder { protected override void Configure() { var context = Context!; // Simple value (Layer 1-2) var autoStart = context.GetProperty("AutoStart"); // Nested object (Layer 1-5 merged) var rabbitConfig = context.GetProperty>("RabbitMQ"); var host = rabbitConfig?["Host"]?.ToString(); var port = rabbitConfig?["Port"]?.ToString(); } } ``` ## Named vs Anonymous Contexts - **Named context**: Defined in `Tsak:Contexts:{name}` with a `Modules` array. Multiple modules share one context. - **Anonymous context**: Created automatically for modules not assigned to any named context. One module = one context. ```json { "Tsak": { "Contexts": { "api": { "Modules": ["Api.Orders", "Api.Catalog"], "AutoStart": true } } } } ``` Modules `Api.Orders` and `Api.Catalog` share the `api` context. Any other module gets its own anonymous context. ## Graceful Shutdown on Module Removal When a module's DLL is removed from the `modules/` directory: 1. The hot-reload service detects the missing file (with debounce to avoid false positives during file replacement) 2. The module's context is gracefully stopped (connections closed, consumers drained) 3. The module is unregistered from the registry 4. The AssemblyLoadContext is cleaned up Configure the debounce threshold in `appsettings.json`: ```json { "Tsak": { "HotReload": { "RemovalDebounceScans": 2 } } } ``` Path: redb-tsak/CONTRIBUTING.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/CONTRIBUTING.md ---- # Contributing to redb.Tsak Thank you for your interest in contributing to **redb.Tsak** — the runtime container for redb.Route. > Before contributing, please read the redb.Route CONTRIBUTING guide. > The conventions there (coding style, PR process, commit messages) apply here as well. --- ## Table of Contents 1. [Reporting Bugs](#reporting-bugs) 2. [Feature Requests](#feature-requests) 3. [Development Setup](#development-setup) 4. [Code Guidelines](#code-guidelines) 5. [Adding a New CLI Command](#adding-a-new-cli-command) 6. [Adding a New REST Endpoint](#adding-a-new-rest-endpoint) 7. [Module Development](#module-development) 8. [Testing](#testing) 9. [Commit Format](#commit-format) --- ## Reporting Bugs When filing an issue include: - **Project**: which sub-project (`Worker`, `CLI`, `Web`, `Client`, `Core`, `Cluster`, etc.) - **Version**: `tsak --version` or the NuGet package version - **Deployment mode**: `InMemory` / `Redb:Postgres` / `Redb:MSSql` / Cluster - **.NET version**: `dotnet --version` - **Minimal reproduction**: - Relevant `appsettings.json` excerpt (no credentials — see DEPLOYMENT_SECRETS.md) - The `tsak` CLI command or REST call that triggers the bug - The module code (stripped down) if module loading is involved - **Expected behavior** - **Actual behavior** — include structured log output from `tsak logs` or the worker console --- ## Feature Requests Before opening a feature request: 1. Check whether the feature belongs in **redb.Tsak** (runtime container infrastructure) or in **redb.Route** (pipeline DSL and transports). Tsak does not implement connectors or EIP processors. 2. Search existing issues for duplicates. 3. Open an issue with: - **Problem statement** — what you cannot do today - **Proposed solution** — API shape, config keys, CLI commands - **Alternatives considered** - Whether this requires a breaking change to any public interface --- ## Development Setup ```bash # Clone git clone https://github.com/redbase-app/redb-tsak.git cd redb # Restore dotnet restore redb.Tsak # Build Worker dotnet build redb.Tsak/src/redb.Tsak.Worker # Run Worker (standalone, no DB) dotnet run --project redb.Tsak/src/redb.Tsak.Worker # Run CLI dotnet run --project redb.Tsak/src/redb.Tsak.CLI -- help # Run Web dashboard dotnet run --project redb.Tsak/src/redb.Tsak.Web ``` For cluster mode, start PostgreSQL and set: ```json { "ConnectionStrings": { "Postgres": "..." }, "Tsak": { "Storage": { "Type": "Redb" }, "Redb": { "Provider": "postgres" }, "Cluster": { "Enabled": true } } } ``` --- ## Code Guidelines All guidelines from the redb.Route CONTRIBUTING guide apply. Tsak-specific additions: - **No business logic in the Worker project** — `redb.Tsak.Worker` is only DI wiring, configuration binding, and hosted service registration. Business logic lives in `redb.Tsak.Core`. - **`_system` context is sacred** — never let API endpoints stop, delete, or modify the `_system` context. Its protection logic lives in `ContextManager` and must not be weakened. - **Constant-time comparisons for keys** — any code that compares API key hashes must use `CryptographicOperations.FixedTimeEquals`. Do not use `==` or `string.Equals` for secrets. - **No distributed state without epoch fencing** — cluster operations that mutate shared state must carry an epoch token to prevent split-brain on network partition recovery. - **Config changes must preserve 5-layer semantics** — if you add a new config key, define it in the `default` context and document which layers can override it. - **All new endpoints need auth checks** — use the `[RequireRole("...")]` attribute or the equivalent middleware. No anonymous write endpoints. - **Ring buffer log** — use structured Serilog logging, not `Console.WriteLine`. The `LogRingBuffer` sink must capture all operational events. --- ## Adding a New CLI Command 1. Create a command file in `redb.Tsak.CLI/Commands/`. 2. Subclass `TsakCommand` (or the appropriate group base). 3. Register the command in `Program.cs` under the correct group. 4. Add table rendering via `Spectre.Console` — match the visual style of existing commands. 5. Add `--output json` support using the shared `OutputFormatter`. 6. Write tests in `redb.Tsak.CLI.Tests/` — cover success path, error responses, and auth failure. 7. Update `README.md` command list. Command implementation checklist: - [ ] Handles `--server` / `--key` global options for targeting a remote Tsak instance - [ ] Propagates `CancellationToken` through all async calls - [ ] Returns appropriate exit codes (0 = success, 1 = error, 2 = auth failure) - [ ] Produces machine-readable JSON when `--output json` is passed - [ ] Includes a `--help` description --- ## Adding a New REST Endpoint 1. Identify which controller the endpoint belongs to (or create a new one if the category is new). 2. Add the corresponding method to `ITsakApiClient` and implement it in `TsakApiClient`. 3. Add a DTO to `redb.Tsak.Contracts` if new request/response shapes are needed. 4. Annotate with the appropriate `[RequireRole(...)]` attribute. 5. Document the endpoint in `README.md` — update the endpoint count in the table. 6. Add unit tests for the service layer and integration coverage for the controller method. --- ## Module Development A Tsak module is a plain .NET class library. To contribute module examples: 1. Follow the `InitRoute.main(IRouteContext)` entry point convention. 2. Ship `manifest.json`, `context.json`, and `{Module}.config.json` alongside the DLL. 3. Do not assume a specific DB or infrastructure — use `context.json` for defaults so operators can override via Layer 5. 4. Document the module's routes, transports, and config keys in its own `README.md`. 5. See redb.Route.Demo as a reference implementation. --- ## Testing Run the full test suite: ```bash dotnet test redb.Tsak/tests/redb.Tsak.Tests dotnet test redb.Tsak/tests/redb.Tsak.CLI.Tests ``` Testing requirements for PRs: - New services must have unit tests using `NSubstitute` for dependencies and `FluentAssertions` for assertions. - Cluster logic must be tested with mocked `IClusterCoordinator` — do not write tests that require actual distributed locking. - CLI commands must have tests covering at least the success path and authentication failure. - Hot-reload logic must have tests that simulate file-change events without touching the file system (use the `IFileSystemWatcher` abstraction). - All tests must pass without environment variables, database connections, or network access. --- ## Commit Format ``` (): [optional body] [optional footer] ``` Types: `feat`, `fix`, `docs`, `refactor`, `test`, `chore` Scopes: `core`, `worker`, `cli`, `web`, `client`, `contracts`, `cluster`, `hotreload`, `security`, `scheduler`, `monitoring`, `watchdog` Examples: ``` feat(cluster): add weighted assignment strategy Adds a WeightedRoundRobin assignment manager that distributes contexts based on node metric scores (CPU + memory composite). Closes #142 ``` ``` fix(security): use constant-time comparison in InMemory key store The InMemory store was using string.Equals which is susceptible to timing attacks. Replaced with CryptographicOperations.FixedTimeEquals. ``` ``` feat(cli): add `route stop` and `route start` commands ``` Path: redb-tsak/DEPLOYMENT.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/DEPLOYMENT.md ---- # redb.Tsak — Deployment Guide How to run the published redb.Tsak containers: images, configuration, passwords, storage modes, the dashboard, deploying your own modules, and reverse-proxy setup. > This guide is for **operators deploying the released images** from `ghcr.io/redbase-app/`. --- ## 1. Images Published to `ghcr.io/redbase-app/` (public, cosign-signed): | Image | What it is | Ports | |-------|------------|-------| | `redb-tsak-worker:` | Process-automation runtime (route contexts, modules, cluster). | `9090` (management/REST API) | | `redb-tsak-web:` | Blazor dashboard (monitoring, routes, logs). Talks to a worker. | `8085` | | `redb-tsak-stack:` | Worker **+** dashboard in one container (supervisord). | `9090`, `8085` | Tags: `:` (= `:-net10`), `:latest`; `` is the release you deploy, as listed on the [releases page](https://github.com/redbase-app/redb-tsak/releases). The worker, web and stack images and the standalone archives run on .NET 10, and the shared route connectors they carry are the net10.0 builds, so user modules (`.tpkg`) target net10.0. The redb packages themselves also ship net11.0 builds for applications of your own on .NET 11. Pro features (cluster, advanced storage) are on in the image; Pro is free of charge and needs no key (§9). ```bash docker pull ghcr.io/redbase-app/redb-tsak-stack: ``` --- ## 2. Quick start ```bash # Stack (worker + dashboard) — full Pro on embedded SQLite, one-node cluster, no key needed. docker run --rm -p 9090:9090 -p 8085:8085 ghcr.io/redbase-app/redb-tsak-stack: # dashboard: http://localhost:8085 (login admin / admin) # REST API: http://localhost:9090/api/health/live ``` The shipped `appsettings.json` boots with **SQLite + Pro enabled + a one-node cluster** (see §6) — zero external dependencies; Pro is free of charge and needs no key (§9). Override anything via env vars (§4). ### What the image ships with — and what to change before you leave it running The image is built for one command, so it starts with no secrets of its own: the packaging strips the development secret, and authentication is **off** — with authentication on and no secret the worker refuses to start, which would defeat the point. The consequences, all deliberate: | As shipped | Means | Before it faces anyone else | |---|---|---| | `Tsak:Auth:Enabled=false` | The management API on `9090` answers **without a key**: stop contexts, upload modules, issue keys, dump config. The node logs a `SECURITY:` warning at every start saying exactly this. | Set `Tsak__Auth__Enabled=true` **and** your own `Tsak__Auth__Secret`, then add a key (see "The first API key" in §4). | | `Tsak:Api:Host=0.0.0.0` | The API listens on every interface of the container — it has to, or a published port would reach nothing. Outside a container the code default is loopback (`127.0.0.1`). | Publish the port only where it belongs: `-p 127.0.0.1:9090:9090`, a private network, or behind a proxy that terminates TLS (§5). | | Dashboard login `admin` / `admin` | Anyone reaching `8085` administers the node. | `Tsak__Web__AdminLogin` / `Tsak__Web__AdminPassword`. | | SQLite at `/app/redb.db` | State lives inside the container and goes away with it. | Mount it: `-v tsak-data:/app` keeps the store and the logs, or point `ConnectionStrings__Sqlite` at a path you mount (`Data Source=/data/redb.db` with `-v tsak-data:/data`). | ```bash # The same quick start, but reachable only from this machine and with a key required. docker run --rm -p 127.0.0.1:9090:9090 -p 127.0.0.1:8085:8085 \ -e Tsak__Auth__Enabled=true \ -e Tsak__Auth__Secret="$(openssl rand -hex 32)" \ -e Tsak__Web__AdminPassword="$(openssl rand -hex 16)" \ -v tsak-data:/app \ ghcr.io/redbase-app/redb-tsak-stack: ``` With authentication on, the dashboard needs a key of its own: see "The first API key" in §4 — the CLI cannot issue it, because `tsak auth create` is a client of the API that key unlocks. ### Container health The `redb-tsak-worker` and `redb-tsak-stack` images report a container unhealthy when the worker's liveness endpoint `GET /api/health/live` stops answering `200`: the process hangs, the watchdog reports hung exchanges, or the management API is gone. A route that failed to start, or a module that is down, leaves the container healthy (that is readiness, `/api/health/ready`). The check calls `127.0.0.1` on `Tsak__Api__Port` (9090 by default) after a start period of 60 s (worker) or 90 s (stack); with `Tsak:Api:Enabled=false`, or `Tsak:Api:Host` bound to one non-loopback address, override `HEALTHCHECK` or switch it off. Docker itself only marks the container; a restart on unhealthy comes from Swarm, an orchestrator or an autoheal sidecar. The `redb-tsak-web` image still checks that its process runs. --- ## 3. Storage modes `Tsak:Storage:Type` + `Tsak:Redb:Provider` decide where state lives. | Mode | Config | Use | |------|--------|-----| | **SQLite (default)** | `Storage:Type=Redb`, `Redb:Provider=sqlite`, `ConnectionStrings:Sqlite=Data Source=redb.db` | Single box, embedded, full Pro + one-node cluster out of the box. | | **Postgres / MSSql** | `Redb:Provider=postgres\|mssql` + `ConnectionStrings:Postgres\|MSSql` | Multi-node cluster, shared store. | | **InMemory** | `Storage:Type=InMemory`, `Redb:Provider=` (empty) | Stateless demo, no Pro/cluster, nothing persists. | ```bash # Postgres-backed, persistent: docker run -p 9090:9090 \ -e Tsak__Storage__Type=Redb \ -e Tsak__Redb__Provider=postgres \ -e ConnectionStrings__Postgres="Host=pg;Port=5432;Username=tsak;Password=secret;Database=redb" \ -v tsak_data:/app \ ghcr.io/redbase-app/redb-tsak-worker: ``` > SQLite file: mount a volume to persist `redb.db` (it's written in the worker's working dir, > `/app` for the worker image, `/app/worker` for the stack image). --- ## 4. Worker configuration reference Every `appsettings.json` key maps to an env var by replacing `:` with `__` (arrays use the index). All keys below live under `Tsak:` unless noted; defaults are the **shipped image values**. ``` Tsak:Api:Port -> Tsak__Api__Port ConnectionStrings:Postgres -> ConnectionStrings__Postgres Tsak:Cluster:Enabled -> Tsak__Cluster__Enabled ``` ### `Tsak:Storage` — state backend | Key | Default | Meaning | |-----|---------|---------| | `Type` | `Redb` | `Redb` = persistent (uses `Redb:Provider`); `InMemory` = demo, nothing persists, no Pro/cluster. | ### `Tsak:Redb` + `ConnectionStrings` — store | Key | Default | Meaning | |-----|---------|---------| | `Redb:Provider` | `sqlite` | redb provider: `sqlite` / `postgres` / `mssql`. | | `Redb:UsePro` | `true` | Turn on Pro components. Free and unrestricted, no key. | | `Redb:PropsSaveStrategy` | `ChangeTracking` | Property write mode: `ChangeTracking` (Pro, what the image ships) or `DeleteInsert` (Free). Switching to Free means switching this too — the Free provider throws on a `ChangeTracking` batch, and the cluster bootstrap saves in a batch at startup, so the worker stops on boot. | | `ConnectionStrings:Sqlite` | `Data Source=redb.db` | SQLite file (Provider=sqlite). Persist via a volume. | | `ConnectionStrings:Postgres` | — | Npgsql connection string (Provider=postgres). | | `ConnectionStrings:MSSql` | — | SQL Server connection string (Provider=mssql). | ### `Tsak:Cluster` — redb-backed clustering (see §6) | Key | Default | Meaning | |-----|---------|---------| | `Enabled` | `true` | Join/form a cluster. `false` = standalone single node. | | `ClusterName` / `GroupName` | `default` | Nodes sharing both names + the same store form one cluster. | | `NodeId` | `""` | Empty = self-assign a unique id. Set a stable id for a fixed node. | | `ApiEndpoint` | `http://localhost:9090` | How peers reach this node's management API. | | `HeartbeatIntervalSeconds` | `15` | Heartbeat write cadence. | | `DeadNodeTimeoutSeconds` | `60` | No heartbeat for this long ⇒ node is dead. | | `LeaderLockTtlSeconds` | `30` | Leader lease TTL (re-election after expiry). | | `Strategy` | `round-robin` | Work distribution across nodes. | ### `Tsak:Api` — management / REST API | Key | Default | Meaning | |-----|---------|---------| | `Enabled` | `true` | Serve the management + route-dispatch API. | | `Host` / `Port` | `127.0.0.1` / `9090` in code, **`0.0.0.0` in the image** | Bind address/port. Loopback is the code default, so a worker you run yourself is not exposed until you say so; the image binds every interface because a container must, and relies on you publishing the port deliberately (§2). | | `Echo:Path` | `/api/echo` | Auth-exempt echo probe path (route ships `AutoStart=false`). | ### `Tsak:Auth` — management-API authentication | Key | Default | Meaning | |-----|---------|---------| | `Enabled` | `false` in code, **`false` in the image** | Require an API key on management endpoints (metrics/echo stay exempt). The image ships it off on purpose — see §2. Turn it on together with `Secret`: with authentication on and no secret the worker refuses to start. | | `Secret` | *(stripped in image)* | HMAC secret of the API keys — the key that `KeyHash` is computed with. **Set in prod.** | | `Keys[]` | `svc-web-dashboard` | Service keys: `Id`, `KeyHash`, `Name`, `Roles`, `UserId`. The Web dashboard presents `Tsak:Web:ServiceApiKey`; its hash must match a key here. See below — this is where the **first** key comes from. | #### The first API key `tsak auth create` talks to the worker's API and therefore needs a key already: the first one can only come from `Tsak:Auth:Keys`. Pick any random string as the key, store its hash here, and hand the key itself to whoever calls the API (`Tsak:Web:ServiceApiKey` for the dashboard). `KeyHash` is **HMAC-SHA256 of the key, keyed with `Tsak:Auth:Secret`**, as 64 hexadecimal characters: ```bash printf %s "$KEY" | openssl dgst -sha256 -hmac "$TSAK_AUTH_SECRET" | awk '{print $NF}' ``` ```powershell [Convert]::ToHexString([Security.Cryptography.HMACSHA256]::new( [Text.Encoding]::UTF8.GetBytes($secret)).ComputeHash([Text.Encoding]::UTF8.GetBytes($key))) ``` Case does not matter — the worker normalises the hash — but a value that is not 64 hexadecimal characters is refused with an error naming the key, instead of being seeded into a key that answers 401 forever. `Roles` takes either a string (`"admin,ops"`) or an array (`Roles:0`, `Roles:1` — the only shape environment variables can express: `Tsak__Auth__Keys__0__Roles__0=admin`). ### `Tsak:Modules` — module loading (see §7) | Key | Default | Meaning | |-----|---------|---------| | `AssemblyPaths` | `[ "modules" ]` | Dirs scanned for `.tpkg` (and their `context.json`). Mount your modules here, **never into `Libs/`**. | > Per-context / per-module settings (the 5-layer merge: `Tsak:Contexts`, `context.json`, > `{Module}.config.json`, `Override`) are documented in **[CONFIG_GUIDE.md](CONFIG_GUIDE.md)**. > Those module config files now live next to the `.tpkg` in the **`modules/`** dir. ### `Tsak:HotReload` — live module deploy | Key | Default | Meaning | |-----|---------|---------| | `Enabled` | `true` | Watch module dirs and reload on change. | | `ScanIntervalSeconds` | `10` | Scan cadence. | | `KeepVersions` | `2` | Old versions retained for rollback. | | `StartupTimeoutSeconds` | `60` | Max wait for a module to start. | | `RollingUpdate` | `false` | Reserved, not implemented: nodes reload independently. | | `Collectible` | `false` | Unload replaced module versions. Off: they stay in memory until restart. | | `MaxOrphanedContexts` | `KeepVersions + 3` | Left-over module versions in memory before the `hotreload` health check turns Degraded and the deploy advice says `cold-deploy` (see "After a series of hot swaps"). | | `MaxWorkingSetMb` | none | Working set (MB) above which the deploy advice says `cold-deploy`. | | `RemovalDebounceScans` | `2` | Scans a file must stay gone before unload (avoids false positives mid-replace). | ### `Tsak:Watchdog` — stuck-route detection | Key | Default | Meaning | |-----|---------|---------| | `Enabled` | `true` | Monitor route liveness. | | `CheckIntervalSeconds` | `10` | Check cadence. | | `SuspectedThresholdMinutes` / `HungThresholdMinutes` | `0.5` / `1.5` | Suspect → hung escalation. | | `AutoRestartHungRoutes` | `false` | Auto-restart hung routes (off = alert only). | ### `Tsak:Metrics` / `Tsak:Tracing` — observability | Key | Default | Meaning | |-----|---------|---------| | `Metrics:CollectionIntervalSeconds` | `10` | Sampling cadence. | | `Metrics:HistoryHours` | `12` | In-memory metric retention. | | `Metrics:Prometheus:Enabled` | `true` | Expose `/metrics` on the API port (auth-exempt). | | `Metrics:Prometheus:Port` | `9464` | Internal OTel listener (loopback). | | `Tracing:ServiceName` | `redb-tsak-worker` | OTLP service.name. | | `Tracing:Otlp:Enabled` | `true` | Export route/step spans via OTLP. | | `Tracing:Otlp:Endpoint` / `Protocol` | `http://localhost:4317` / `grpc` | Collector/Jaeger endpoint. | These feed any OTLP collector (Jaeger/Tempo) and a Prometheus scrape of `:/metrics`. ### Other | Section | Key | Default | Meaning | |---------|-----|---------|---------| | `Tsak:Logs` | `BufferSize` | `2000` | In-memory log ring buffer (dashboard tail). | | `Tsak:Contexts:default` | `AutoStart` | `true` | Auto-start contexts on boot. | | `Quartz` | `quartz.jobStore.*`, `threadCount` | AdoJobStore, `10` | The scheduler of every context; the pool is per context (§6). Quartz clustering stays `false` on SQLite. | | `Serilog` | `MinimumLevel`, `WriteTo` | Console + `Logs/log-.txt` (7-day roll) | Logging sinks/levels. | | `ASPNETCORE_PATHBASE` | — | — | Host under a sub-path, e.g. `/tsak` (see §5). | --- ## 5. Dashboard & passwords The dashboard (Web / Stack) is a **Blazor Server** app on port `8085`. | Secret | Key | Default in image | Change in prod? | |--------|-----|------------------|-----------------| | Dashboard login | `Tsak:Web:AdminLogin` / `Tsak:Web:AdminPassword` | `admin` / `admin` | **Yes** | | Management-API auth secret | `Tsak:Auth:Secret` | *(stripped — empty)* | set if `Auth:Enabled=true` | | Web→worker service key | `Tsak:Web:ServiceApiKey` | *(stripped)* | set when Web and Worker are separate | ```bash docker run -p 8085:8085 \ -e Tsak__Web__AdminLogin=admin \ -e Tsak__Web__AdminPassword='CHANGE_ME' \ ghcr.io/redbase-app/redb-tsak-stack: ``` ### Dashboard config (`Tsak:Web` + `Kestrel`) | Key | Default | Meaning | |-----|---------|---------| | `Tsak:Web:AdminLogin` / `AdminPassword` | `admin` / `admin` | Dashboard login. **Change in prod.** | | `Tsak:Web:Mode` | `standalone` | How the dashboard finds workers: `standalone` (fixed list) or `cluster` (auto-discover via the redb store). | | `Tsak:Web:Nodes[]` | — | **standalone mode:** explicit worker list — each `{ Id, Url, ApiKey }`. `ApiKey` must match a worker `Tsak:Auth:Keys` entry. | | `Tsak:Web:ServiceApiKey` | *(stripped)* | **cluster mode:** the key the dashboard uses to call workers' management API (worker validates its SHA-256 against `Tsak:Auth:Keys`). | | `Kestrel:Endpoints:Http:Url` | `:8085` (in image) | Dashboard bind URL (the image already binds `:8085`). | | `Kestrel:Endpoints:Https:Url` | — | Optional HTTPS bind (provide a cert). | | `ASPNETCORE_PATHBASE` | — | Serve under a sub-path, e.g. `/tsak` (see below). | Standalone vs cluster — pick how the dashboard reaches workers: ```bash # Standalone: dashboard talks to ONE named worker. -e Tsak__Web__Mode=standalone -e Tsak__Web__Nodes__0__Id=local -e Tsak__Web__Nodes__0__Url=http://worker:9090 -e Tsak__Web__Nodes__0__ApiKey= # Cluster: dashboard auto-discovers nodes from the shared redb store. -e Tsak__Web__Mode=cluster -e Tsak__Web__ServiceApiKey= ``` > In the **stack** image the dashboard and worker share one container — it's wired to the local > worker out of the box; you only set `AdminLogin`/`AdminPassword`. ### Behind a reverse proxy (nginx / traefik) — read this The dashboard needs its **Blazor SignalR WebSocket** (`/_blazor`) proxied with the upgrade headers. If the proxy doesn't upgrade WebSockets, the page renders and the login form shows, **but the login button does nothing** (the Blazor circuit never connects). Hosting under a sub-path (e.g. `https://host/tsak/`)? Set `ASPNETCORE_PATHBASE=/tsak` on the container and proxy that path: ```nginx location /tsak/ { proxy_pass http://tsak-container:8085; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; # <-- required for Blazor proxy_set_header Connection "upgrade"; # <-- required for Blazor proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; } ``` Without `Upgrade`/`Connection` headers the login button is dead — it is **not** a credentials problem. Access the dashboard at the path matching `ASPNETCORE_PATHBASE` (e.g. `/tsak/`), not `/`. --- ## 6. Clustering — one node out of the box The Tsak cluster is **redb-backed** (leader election + heartbeats live in the redb store; this is *not* Quartz clustering, which stays off on SQLite). The shipped config already runs it: `Tsak:Cluster:Enabled=true`, and clustering is free of charge and needs no key (§9), with no node cap. So **one worker = a working one-node cluster** (self-elected leader). To scale, run more nodes pointing at the **same redb store** (use Postgres/MSSql, §3) with the same `ClusterName`/`GroupName` and an empty `NodeId` (each self-assigns); they join automatically, as many as you need. Run standalone with `Tsak__Cluster__Enabled=false`. ### Quartz: a scheduler per context Each context runs its own Quartz scheduler, named `{instanceName}-{context}` (`TsakScheduler-{ClusterName}-{context}` with the shipped config), as Apache Camel runs one per CamelContext. On a clustered `AdoJobStore` the nodes that run a context form that context's Quartz cluster: a job fires on one of them. Two consequences: - Don't put `.Cluster(true)` on a `cron:` / `qtimer:` route: Quartz already fires it once per cluster, and Tsak leaves such a route on every node (with a Warning) rather than lose the fires other nodes take. - The `Quartz` section configures every context's scheduler; `threadCount` / `maxConcurrency` is the pool of each context, not of the node. ### Upgrading to the per-context scheduler Releases before the per-context scheduler ran one scheduler per node, named `TsakScheduler-{ClusterName}`. A node of the new release does not read that scheduler's rows, and a node of the old release does not know the new names: the two cannot share a cluster. **Upgrade with a full stop** — there is no compatibility mode: 1. Stop every worker of the cluster. 2. Deploy the new release on all of them. 3. Start them. Each context schedules its jobs again from its routes under its own scheduler name. The old scheduler's rows stay in the database: a node never deletes or pauses what a shared store holds. Removing them is an operator command, run once with every worker stopped (child tables first). PostgreSQL, with the shipped table prefix: ```sql BEGIN; DELETE FROM qrtz_fired_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_simple_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_simprop_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_cron_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_blob_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_triggers WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_job_details WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_calendars WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_paused_trigger_grps WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_scheduler_state WHERE sched_name = 'TsakScheduler-'; DELETE FROM qrtz_locks WHERE sched_name = 'TsakScheduler-'; COMMIT; ``` The same statements apply to SQL Server (`BEGIN TRANSACTION; … COMMIT;`). If `quartz.scheduler.instanceName` was configured to a name other than `TsakScheduler`, the old scheduler had exactly that name, and each context's scheduler is now `-`. --- ## 7. Deploying your own modules (`.tpkg`) Modules are hot-deployable `.tpkg` packages. The worker scans **`Tsak:Modules:AssemblyPaths`** (default `[ "modules" ]`) for them — a **dedicated `modules/` dir, separate from `Libs/shared`**. ``` /app[/worker]/ ├── Libs/shared/ ← image's connector DLLs. DO NOT mount over this. └── modules/ ← YOUR bind-mount: drop .tpkg + its context.json here. ``` > **Never bind-mount `Libs/`** — it hides the image's `Libs/shared` connector layer. Mount the > dedicated `modules/` dir instead. A module's external config goes in the **same** dir as a > `context.json` (TsakCoordinator reads it next to the `.tpkg`). ```yaml services: worker: image: ghcr.io/redbase-app/redb-tsak-stack: environment: - Tsak__Modules__AssemblyPaths__0=/app/worker/modules volumes: - ./modules:/app/worker/modules:ro # contains MyModule.tpkg (+ context.json) ``` Or hot-deploy at runtime (hot-reload watches the dir): copy a new `.tpkg` into `modules/` and the worker loads it without a restart. ### After a series of hot swaps Each hot swap leaves the old module version in memory with `Tsak:HotReload:Collectible=false` (the default), and with `true` a version that something still holds stays too. Once more of them pile up than `Tsak:HotReload:MaxOrphanedContexts` allows, the `hotreload` health check turns Degraded with "restart the node to reclaim memory". A restart is the only way to give that memory back. What to watch: `OrphanedModuleContexts` in `GET /api/system/info` (or `tsak system info`), the `hotreload` entry of `GET /api/system/health`, and the working set of the process. With `Collectible=true` a version that did not unload is also logged as a warning: `module context still alive after 10 collections`. Restart the nodes one at a time, so the cluster keeps serving: 1. Drain the node. In a cluster, cordon it (`POST /api/cluster/nodes/{nodeId}/cordon`): it finishes its work, takes no new work and hands its locks to the peers. A single node has no peers to take over; restart it in a quiet window. 2. Stop the process (SIGTERM, `docker stop`): every context stops with its own graceful-stop timeout for in-flight exchanges. 3. Start it again and wait for `GET /api/health/ready` to answer `200`. The node loads the current module versions only, so `OrphanedModuleContexts` is `0` again. 4. Uncordon it, then go on with the next node. If the count grows again after every release, the modules are swapped faster than nodes restart: let the pipeline ask for the deploy advice below before each release, or try `Collectible=true` on a test node and watch whether the old versions go. When a release is due anyway, do not restart first and hot swap after: deploy it cold (next section), the restart and the new packages in one step. ### Deploy advice in a pipeline `GET /api/health/deploy` tells a pipeline how to deploy a new package on a node; `GET /api/health/deploy/cluster` asks every alive node in one call. Both are open like the probes, and the status code is the whole answer (API_GUIDE.md, "Deploy advice"): - `200`, `hot-swap`: copy the `.tpkg` into `modules/` of the running node. - `409`, `cold-deploy`: cordon the node, stop it, replace the packages in `modules/` while it is down, start it, wait for `/api/health/ready`, uncordon. A restart with the old packages and a hot swap after it would leave one more old version in memory for nothing. The endpoint only advises: the pipeline does the deploy. `tsak system deploy-advice [--cluster]` asks the same from a script and exits `0` for hot-swap, `3` for cold-deploy, `1` or `2` on an error, so a step can branch on the exit code; `--output json` prints the advice and nothing else. #### Kubernetes The packages reach the pod either through a writable volume mounted at `modules/` (hot swap possible) or inside the image or a volume filled at pod start (every deploy is a rollout). With a writable volume: 1. Ask: `curl -s -o advice.json -w '%{http_code}' http://tsak:9090/api/health/deploy/cluster` from a Job or a pipeline step inside the cluster (or `kubectl exec` into one pod). `200` → step 2, `409` → step 3. 2. Hot swap: copy the package into each pod's `modules/`, through a temporary name and a rename so the worker never reads a half-written file (`kubectl cp app.tpkg tsak-0:/app/modules/app.tpkg.part`, then `kubectl exec tsak-0 -- mv /app/modules/app.tpkg.part /app/modules/app.tpkg`). Check the new version with `tsak module list`. 3. Cold deploy, one pod at a time (`maxUnavailable: 1`): 1. Put the new package where the pods take it from (a new image tag, a new ConfigMap or volume version). 2. Cordon the node: `POST /api/cluster/nodes/{nodeId}/cordon` with an admin key from a Secret. A `preStop` hook that sends the same call cordons each pod the rollout stops, without a step of its own. Give the pod a `terminationGracePeriodSeconds` above the contexts' graceful-stop timeout. 3. `kubectl rollout restart statefulset/tsak` (or `kubectl set image`): Kubernetes stops the pod, the new one starts with the new packages, and the readiness probe `/api/health/ready` holds the rollout until it serves. 4. Uncordon the node once it is ready: `POST /api/cluster/nodes/{nodeId}/uncordon`. With a StatefulSet the node id stays the same across the restart, so the registry still has it cordoned until this call. #### Compose with TeamCity One worker per host, `modules/` a bind mount on the host. A build configuration with these steps, run host by host: 1. Ask (command line step): ```sh tsak system deploy-advice --url http://$HOST:9090 --output json > advice.json code=$? if [ $code -eq 0 ]; then echo "##teamcity[setParameter name='deploy.mode' value='hot']" elif [ $code -eq 3 ]; then echo "##teamcity[setParameter name='deploy.mode' value='cold']" else exit $code; fi ``` 2. Hot swap (runs when `deploy.mode` is `hot`): copy under a temporary name and rename, so the worker never reads a half-written file: ```sh scp app.tpkg deploy@$HOST:/srv/tsak/modules/app.tpkg.part ssh deploy@$HOST 'mv /srv/tsak/modules/app.tpkg.part /srv/tsak/modules/app.tpkg' ``` 3. Cold deploy (runs when `deploy.mode` is `cold`): ```sh curl -fsS -X POST -H "X-Api-Key: $TSAK_ADMIN_KEY" http://$HOST:9090/api/cluster/nodes/$NODE_ID/cordon # cluster only ssh deploy@$HOST 'cd /srv/tsak && docker compose stop tsak' scp app.tpkg deploy@$HOST:/srv/tsak/modules/app.tpkg ssh deploy@$HOST 'cd /srv/tsak && docker compose start tsak' for i in $(seq 60); do # up to 5 minutes [ "$(curl -s -o /dev/null -w '%{http_code}' http://$HOST:9090/api/health/ready)" = 200 ] && break [ $i -eq 60 ] && { echo "worker not ready"; exit 1; } sleep 5 done curl -fsS -X POST -H "X-Api-Key: $TSAK_ADMIN_KEY" http://$HOST:9090/api/cluster/nodes/$NODE_ID/uncordon # cluster only ``` A single node without a cluster has nobody to take its work while it is down: run the cold deploy in a quiet window, and leave out the two cordon calls. --- ## 8. Compose examples **Stack (worker + dashboard), embedded SQLite, persistent:** ```yaml services: tsak: image: ghcr.io/redbase-app/redb-tsak-stack: ports: - "9090:9090" # management / REST API - "8085:8085" # dashboard environment: - Tsak__Web__AdminPassword=CHANGE_ME volumes: - tsak_data:/app/worker # persists redb.db (SQLite) - ./modules:/app/worker/modules:ro # your .tpkg modules (optional, §7) restart: unless-stopped volumes: tsak_data: ``` **Worker + Postgres (multi-node-ready store):** ```yaml services: worker: image: ghcr.io/redbase-app/redb-tsak-worker: ports: ["9090:9090"] environment: - Tsak__Redb__Provider=postgres - ConnectionStrings__Postgres=Host=pg;Username=tsak;Password=secret;Database=redb depends_on: [pg] restart: unless-stopped pg: image: postgres:16 environment: [POSTGRES_USER=tsak, POSTGRES_PASSWORD=secret, POSTGRES_DB=redb] volumes: ["pg_data:/var/lib/postgresql/data"] volumes: pg_data: ``` ```bash docker compose up -d ``` --- ## 9. Pro is free of charge Pro is free of charge and needs no key: `redb.*.Pro`, `redb.Tsak.Core.Pro`, the dashboard and clustering run unrestricted, in production, with no node cap and no request limit. There is nothing to activate. Pro packages are proprietary (closed source) but free of charge. **Larger companies that need the Pro sources — for audit, escrow, or to build in-house — can request them; we hand them over.** Write to . --- ## 10. Verifying signatures All images and release archives are [cosign](https://docs.sigstore.dev/cosign/)-signed. The cosign **public key** (`cosign.pub`) is attached to each [GitHub Release](https://github.com/redbase-app/redb-tsak/releases). ```bash # grab cosign.pub from the release assets, then: cosign verify --key cosign.pub ghcr.io/redbase-app/redb-tsak-worker: ``` --- ## Troubleshooting | Symptom | Cause | Fix | |---------|-------|-----| | Dashboard login button does nothing | Blazor WebSocket not proxied | §5 — add `Upgrade`/`Connection` headers; use the `ASPNETCORE_PATHBASE` path | | `failed to ensure schema` / Npgsql connection refused | worker pointed at a Postgres that isn't reachable | check `ConnectionStrings`, or use SQLite (§3) | | Connectors missing after mounting a volume | bind-mounted `Libs/` and hid `Libs/shared` | §7 — mount `modules/`, never `Libs/` | | `REDB.PRO TRIAL MODE` / 1024 req/day | a build that is not a released redb package (a local or modified build) | use the released packages and images, which run Pro without a key (§9) | Path: redb-tsak/Directory.Build.props Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/Directory.Build.props ---- net10.0;net11.0 enable enable true $(NoWarn);1591 4.8.0 4.8.0 RedBase RedBase redb.Tsak Runtime container for redb.Route contexts with management API Copyright (c) 2024-2026 RedBase https://redbase.app https://github.com/redbase-app/redb-tsak git Apache-2.0 LICENSE-PRO.txt Path: redb-tsak/Directory.Build.targets Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/Directory.Build.targets ---- true <_RedbCentral>true <_RedbNetMajor>$([System.Version]::Parse('$(TargetFrameworkVersion.TrimStart(`v`))').Major) 3.1.12 4.18.1 10.0.15 11.0.0 $(RedbSecAspNetCoreVersion) 10.0.15 11.0.0 10.0.15 true $(WarningsAsErrors);NU1506 true all moderate $(WarningsAsErrors);NU1902;NU1903;NU1904 Path: redb-tsak/Directory.Packages.props Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/Directory.Packages.props ---- true Path: redb-tsak/LICENSE Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/LICENSE ---- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may accept and charge a fee in exchange for, or offer support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024-2026 RedBase Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Path: redb-tsak/MODULE_DEPLOYMENT.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/MODULE_DEPLOYMENT.md ---- # redb.Tsak — Module Deployment & Signing Deploying a module means shipping **code that Tsak loads and runs in-process**. This document explains the trust model, because the pieces are easy to confuse: there are two verification boundaries, two separate "require signature" switches, and a signing step that happens somewhere else entirely (your build pipeline, not the node). Read this once before turning on remote upload. > See also: [CONFIG_GUIDE.md](CONFIG_GUIDE.md) for the config layers, [API_GUIDE.md](API_GUIDE.md) > for the endpoints, [SECURITY.md](SECURITY.md) for the overall posture. --- ## 1. The one-paragraph version A module is a `.tpkg` (a ZIP with a manifest + DLLs). It reaches a node one of two ways: an **operator drops the file** into the module directory, or someone **uploads it via the API**. Both paths end at the same place — the hot-reload scanner loads the package. The *trust anchor* is a **signing key pair**: your CI signs the `.tpkg` with the **private** key; the node verifies it with the **public** key before running any of its code. Remote upload is **off by default**; signature enforcement is **off by default**. Turn both on together for a node that accepts remote deploys. --- ## 2. Two paths in, one gate ``` ┌─────────────────────────────┐ operator drops │ │ file into dir ───►│ module directory │ │ (Tsak:Modules:AssemblyPaths) POST /api/modules │ │ /upload ───►│ {name}.tpkg {name}.tpkg.sig └──────────────┬──────────────┘ │ ▼ ┌─────────────────────────────┐ │ HotReloadService — LOAD GATE│ ← the authoritative check │ Tsak:Modules:Signature │ │ .Required ? verify(.sig) │ └──────────────┬──────────────┘ pass ─────┼───── fail → refused, logged, NOT loaded ▼ loaded & running ``` The **load gate** is the check that matters: it runs before any code from the package executes, and it applies to **every** `.tpkg` regardless of how it arrived. So the public key — not "who has write access to the directory" — decides what may run. The API upload *also* verifies the signature early (fail-fast, before the file is written), but that's a convenience so a bad upload is rejected with a clear message. The load gate is what actually protects you. --- ## 3. The two "require signature" switches — do not confuse them There are two, at different boundaries, and they answer different questions. | Switch | Boundary | Question it answers | Default | |---|---|---|---| | `Tsak:Modules:Signature:Required` | **load** (HotReloadService) | "May this `.tpkg` run at all?" — applies to operator drops AND uploads | `false` | | `Tsak:Modules:Upload:RequireSignatureForUpload` | **upload** (API only) | "May this upload proceed when no key is configured?" | `true` | - `Signature:Required = true` is the strong one. With a public key configured, **nothing** loads without a valid signature — an operator who drops an unsigned file gets it refused too. This is the setting that makes a leaked admin API key harmless (the attacker still lacks the private key). - `Upload:RequireSignatureForUpload` only governs the *upload endpoint when no public key is set*. With it `true` (default) and no key, uploads are refused outright — you cannot accidentally stand up an unauthenticated code-push endpoint. Set it `false` only to deliberately allow unsigned uploads (dev boxes), which logs a loud warning on every upload. **Rule of thumb:** for production, configure a public key and set `Signature:Required = true`. Then both switches are satisfied and both boundaries are protected. --- ## 4. Who signs, and how Signing happens in your **build / release pipeline**, by whoever holds the **private** key — never on the node. The node only ever sees the public key. ### Generate a key pair (once) ```bash tsak module keygen --out tsak-module # tsak-module.key → PRIVATE key. Keep it in your CI secret store. Never deploy it. # tsak-module.pub → PUBLIC key. Configure it on every node. ``` `--out` is required: the command creates a secret, so where it goes is always your choice, and it prints the full paths of both files. It never replaces an existing key pair with that prefix; pass `--force` to do so on purpose, and remember that packages signed with the old key no longer verify once the nodes carry the new public key. (ECDSA P-256 by default. RSA keys work too — the verifier accepts either.) ### Sign a package (in CI, after building the .tpkg) ```bash tsak module sign MyModule.tpkg --key tsak-module.key # → MyModule.tpkg.sig (base64 detached signature over the .tpkg bytes) ``` Equivalent with OpenSSL, if your CI doesn't have the `tsak` CLI: ```bash openssl dgst -sha256 -sign tsak-module.key -out MyModule.tpkg.sig.raw MyModule.tpkg base64 -w0 MyModule.tpkg.sig.raw > MyModule.tpkg.sig ``` Ship the `.tpkg` **and** the `.tpkg.sig` together. --- ## 5. Configure a node to verify ```jsonc { "Tsak": { "Modules": { "AssemblyPaths": [ "modules" ], "Signature": { "Required": true, // refuse unsigned/tampered .tpkg at load "PublicKeyPath": "keys/tsak-module.pub" // or PublicKeyPem: "-----BEGIN PUBLIC KEY----- …" }, "Upload": { "Enabled": true, // turn ON the remote upload endpoint "MaxSizeMB": 100, "KeepVersions": 3 // previous .tpkg kept on disk for rollback } } } } ``` - Leave `Upload:Enabled = false` (the default) on any node that doesn't need remote deploys — it removes the upload surface entirely. - With `Signature:Required = true` and a `PublicKeyPath`, even a file dropped straight into `modules/` must have a valid `modules/{name}.tpkg.sig` or it won't load. --- ## 6. Deploy and roll back ```bash # Upload (the CLI sends the .tpkg body + the .tpkg.sig as the X-Tsak-Signature header) tsak module deploy MyModule.tpkg # auto-picks MyModule.tpkg.sig if present tsak module deploy MyModule.tpkg --sig other.sig # Roll back to the previous on-disk version tsak module rollback MyModule ``` Both require the **admin** role and are recorded in the [audit trail](API_GUIDE.md#audit). The node keeps `KeepVersions` previous packages as `{name}.tpkg.v0001`, `…v0002`, …; `rollback` restores the most recent archived one and triggers a hot-reload. Raw API (for non-CLI CI): ``` POST /api/modules/upload Header: X-Tsak-Signature: (omit only if unsigned uploads are allowed) Body: POST /api/modules/{name}/rollback ``` --- ## 7. What each guard defends against | Guard | Stops | |---|---| | `Upload:Enabled = false` (default) | the entire remote code-push surface — no endpoint, no risk | | `admin` role on upload/rollback | a low-privilege key deploying code | | Signature at the **load gate** | running any package not signed by your private key — even a file dropped on the box | | Fail-fast signature at upload | a bad upload landing on disk at all | | Size ceiling | a memory/disk DoS via a huge body | | Valid-ZIP + manifest check | garbage or malformed packages | | Name taken from the **manifest**, sanitized (no `/`, `\`, `..`) | path traversal / zip-slip — the file can only land inside the module directory | | Atomic install (temp → move) | a half-written package being loaded | | Audit on every upload/rollback | "who deployed what, when" being unanswerable | --- ## 8. How this compares to WSO2 MI WSO2 Micro Integrator deploys CApps (`.car`, also a ZIP that can carry class-mediator JARs) by dropping them into `repository/deployment/server/carbonapps/` — a filesystem hot-deploy, exactly like Tsak's module directory. WSO2 MI does **not** verify artifact signatures at runtime; its trust anchor is "who can write to the folder / who can call the authenticated management API." Tsak's optional load-boundary signature check is therefore **stricter** than the WSO2 MI default: with it on, filesystem access alone is not enough to run code. Path: redb-tsak/NOTICE Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/NOTICE ---- redb — Entity Database for .NET Copyright 2024-2026 RedBase This product includes software developed by RedBase (https://redbase.app). Licensed under the Apache License, Version 2.0 (the "License"); you may not use the open-source components of this product except in compliance with the License. You may obtain a copy of the License in the LICENSE file in the root of this distribution or at: http://www.apache.org/licenses/LICENSE-2.0 ------------------------------------------------------------------------ Components and licenses ------------------------------------------------------------------------ * Open-source projects (Apache License 2.0): redb.Core, redb.Postgres, redb.MSSql, redb.Tsak.Core, redb.Tsak.Web, redb.Tsak.CLI, redb.Tsak.Worker, redb.Tsak.Client, redb.Tsak.Contracts, redb.Identity, redb.Route, redb.CLI, redb.PropsEditor, redb.Templates, redb.Examples, and other non-".Pro" projects. * Commercial / Pro projects (REDBASE Commercial License — see LICENSE-PRO.txt): redb.Core.Pro, redb.Postgres.Pro, redb.MSSql.Pro, redb.Tsak.Core.Pro, redb.Tsak.Web.Pro, redb.Licensing (the licensing library is distributed alongside Pro components). * Third-party components: see project files (.csproj) for transitive package references and their respective licenses. Path: redb-tsak/PARAMETERS.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/PARAMETERS.md ---- # redb.Tsak parameter reference Every setting the worker reads, what it defaults to, and the ones that will bite you. This is the **what**. For the **how** — the five layers, how `context.json` merges over `appsettings.json`, and which key wins when two disagree — see [CONFIG_GUIDE.md](CONFIG_GUIDE.md). Read that one first if a value you set is not taking effect; nine times out of ten a higher layer is overwriting it. Every key below is written in colon form (`Tsak:Api:Port`). In a container the same key is an environment variable with `__` for the separator: ``` Tsak__Api__Port=9090 ``` --- ## Start here: three defaults that are not what you would guess | Key | Default | Why it matters | |---|---|---| | `Tsak:Api:Host` | `127.0.0.1` | The management API is **loopback-only** out of the box. A container that publishes port 9090 still answers nothing from outside until you set this to `0.0.0.0`. That is deliberate — see [SECURITY.md](SECURITY.md). | | `Tsak:Auth:Enabled` | `false` | Authentication is **off** by default. Combined with the line above that is safe on a laptop and wrong on a network. Turn it on before you change `Host`. | | `Tsak:Storage:Type` | `InMemory` | State does not survive a restart until you point this at `Redb`. | --- ## `Tsak:Redb` — the database This section configures the redb service the worker hosts. | Key | Default | Notes | |---|---|---| | `Tsak:Redb:Provider` | `auto` | `postgres`, `mssql`, `sqlite`, or `auto` to infer from the connection string. | | `Tsak:Redb:ConnectionString` | — | Required unless the provider resolves one itself. | | `Tsak:Redb:UsePro` | `true` | Pro is free and needs no key, so the default is Pro. Set `false` for the Free tier. | | `Tsak:Redb:PropsSaveStrategy` | `ChangeTracking` | How property rows are written. **Requires Pro.** The Free provider implements only `DeleteInsert`: its batch path throws `NotSupportedException`, and since the cluster bootstrap saves in a batch on startup, the host stops. Setting `UsePro=false` means setting this to `DeleteInsert` too. | ### Every `RedbServiceConfiguration` property is settable here `Tsak:Redb:` binds directly onto redb's own configuration object — all 37 public properties, by their exact property names. Some worth knowing: | Key | Default | What it does | |---|---|---| | `Tsak:Redb:StringCollation` | `null` | Collation for case-insensitive string search, e.g. `und-x-icu`. **On PostgreSQL, check the database ctype first** (`SELECT datctype FROM pg_database WHERE datname = current_database()`). With a UTF-8 ctype (`en_US.utf8`, `ru_RU.utf8`) plain `ILIKE` already folds every script: leave this unset, and the stock trigram index keeps serving the search. With ctype `C` or `POSIX` the setting gives correct folding, but pg_trgm builds no trigram from non-ASCII text under that ctype, so a non-ASCII substring search reads every row whatever the index. With the setting on, Pro (planner on, the default) stops reading `IX__values__String_pattern` for ignore-case searches and needs a trigram index over the same collation; the index must match this value exactly, so it differs per project: `CREATE INDEX CONCURRENTLY "IX__values__String_pattern_und_x_icu" ON _values USING gin ((_String COLLATE "und-x-icu") gin_trgm_ops) WHERE _String IS NOT NULL;`. Start-up logs a Warning while it is missing, and `redb.Postgres/sql/maintenance/string_collation_index.sql` builds it for any collation. The free provider reads no trigram index for a substring search, with or without the setting. SQLite folds ASCII only without it. Details: ../COLLATION.md. | | `Tsak:Redb:CreateStringCollationIndex` | `false` | PostgreSQL Pro with the planner on: build the trigram index of `StringCollation` at start-up (`CREATE INDEX CONCURRENTLY`, minutes on a large `_values`) when the database has none. Under ctype `C` it serves ASCII patterns only. Does nothing without `AutoApplyDatabaseUpgrades` or on the free provider: one Warning. | | `Tsak:Redb:EnablePvtPrefilter` | `true` | Pro only, on all three providers (PostgreSQL, SQL Server, SQLite). Adds a cutting step before the pivot aggregate. It deliberately declines some query shapes — a nested `OR` under an `AND` is skipped because taking it would drop rows, not merely run slower. Tsak sets nothing here; the default is the one of `RedbServiceConfiguration`. | | `Tsak:Redb:EnsureCreated` | `true` for the unnamed instance, `false` for named ones | Create the schema at startup. Named instances assume the schema exists. | | `Tsak:Redb:DefaultCheckPermissionsOnQuery` | `false` | Also `…OnLoad`, `…OnSave`, `…OnDelete`. Access control, not tuning. | | `Tsak:Redb:SystemUserId` | `0` | The user id attributed to system writes. | | `Tsak:Redb:AutoSyncSchemesOnSave` | `true` | Sync a scheme when an object of it is saved. | | `Tsak:Redb:EnableLazyReferences` | `false` | V4: a `virtual` reference is a stub at any depth; its `Props` load on first access. | > **Before 3.7.2 most of these did nothing.** Both configuration paths copied properties across one > hand-written line at a time and the lists had gone stale — the named path carried 15 of 37, the > unnamed one 12, and the two sets were not even subsets of each other, so the same key behaved > differently depending on whether the instance had a name. Worse, an unrecognised key produced no > diagnostic at all, so a typo and a missing feature looked identical. Both paths now bind by > reflection and report unknown keys. If you are on an older build, check the source before trusting > a setting from this table. ### `Tsak:Redb:Cache` — a subsection with its own vocabulary This one predates the binder and uses **short names**, not property names. Both spellings work; these are the ones to use inside `Cache`: | Key | Maps to | Default | |---|---|---| | `Tsak:Redb:Cache:EnableProps` | `EnablePropsCache` | `false` | | `Tsak:Redb:Cache:PropsMaxSize` | `PropsCacheMaxSize` | redb default | | `Tsak:Redb:Cache:PropsTtlMinutes` | `PropsCacheTtl` | redb default | | `Tsak:Redb:Cache:EnableList` | `EnableListCache` | `true` | | `Tsak:Redb:Cache:ListTtlMinutes` | `ListCacheTtl` | redb default | | `Tsak:Redb:Cache:EnableMetadata` | `EnableMetadataCache` | `true` | | `Tsak:Redb:Cache:MetadataTtlMinutes` | `MetadataCacheLifetimeMinutes` | redb default | | `Tsak:Redb:Cache:AutoRecomputeHash` | `AutoRecomputeHash` | `true` | | `Tsak:Redb:Cache:CacheDomain` | `CacheDomain` | — | | `Tsak:Redb:Cache:SkipHashValidationOnCacheCheck` | same | `false` | > **`SkipHashValidationOnCacheCheck` + clustering is a stale-read hazard.** Skipping the hash check > trusts the in-process cache without asking the database, which is only correct for a single writer. > With `Tsak:Cluster:Enabled=true` the worker warns about this at startup; heed it. --- ## `Tsak:Api` — the management API | Key | Default | Notes | |---|---|---| | `Tsak:Api:Enabled` | `true` | | | `Tsak:Api:Host` | `127.0.0.1` | Loopback by default. See the table at the top. | | `Tsak:Api:Port` | `9090` | | | `Tsak:Api:Echo:Path` | `/api/echo` | | | `Tsak:Api:AuthExempt` | — | Paths that skip authentication. Every entry is a hole you are opening on purpose. | | `Tsak:Api:AuthThrottle:Limit` | `10` | Failed attempts before lockout. | | `Tsak:Api:AuthThrottle:WindowSeconds` | `60` | | | `Tsak:Api:AuthThrottle:LockoutSeconds` | `120` | | | `Tsak:Http:TrustedProxies` | — | Addresses or CIDR networks of the reverse proxies in front of the worker, e.g. `["10.0.0.5", "10.1.0.0/16"]`. Set on the shared Kestrel host, so every HTTP listener in the process (the management API, module routes over Http / Soap / As2 / gRPC) sees the client's address and scheme instead of the proxy's. `X-Forwarded-For` is walked right to left past every listed proxy to the first address that is not one, so a chain of proxies resolves correctly; a header from a peer that is not listed is ignored. Keep the list to the proxies you operate: a range an attacker can send from lets them pick their own throttle bucket. A value that does not parse fails the start. | | `Tsak:Api:AuthThrottle:TrustProxyHeaders` | `false` | **Deprecated, use `Tsak:Http:TrustedProxies`.** Takes the right-most `X-Forwarded-For` hop as the client, which is right behind exactly one proxy and wrong behind a chain (the hop is then the next proxy, and every caller shares one bucket). Ignored, with a log line, whenever `Tsak:Http:TrustedProxies` is set. | ## `Tsak:Auth` — API keys | Key | Default | Notes | |---|---|---| | `Tsak:Auth:Enabled` | `false` | | | `Tsak:Auth:Secret` | — | | | `Tsak:Auth:Keys` | — | The key list. | | `Tsak:Auth:EnforceRoles` | `true` | | | `Tsak:Auth:RolelessKeysAreAdmin` | `false` | A key with no roles is denied rather than treated as admin. Fail-closed on purpose. | | `Tsak:Auth:CacheTtlSeconds` | `300` | | | `Tsak:Auth:RevocationCheckSeconds` | `30` | How quickly a revoked key stops working across the cluster. | ## `Tsak:Web` — the dashboard | Key | Default | Notes | |---|---|---| | `Tsak:Web:Mode` | `standalone` | | | `Tsak:Web:StandaloneUrl` | `http://localhost:9090` | | | `Tsak:Web:Nodes` | — | Node list in cluster mode. | | `Tsak:Web:SchemaWaitSeconds` | `300` | Cluster mode: how long the dashboard waits at start for the redb schema, which the worker creates. Past the limit the start fails with a message naming the cause. `0` = no wait. | | `Tsak:Web:AdminLogin` | — | | | `Tsak:Web:AdminPasswordHash` | — | **Prefer this over `AdminPassword`.** A BCrypt hash (`$2a$`, `$2b$`, `$2y$`), verified in constant time. In cluster mode it is stored as the admin's password when the admin has none; wins over `AdminPassword`. | | `Tsak:Web:AdminPassword` | — | Plaintext. Accepted, but it ends up in whatever holds your config. | | `Tsak:Web:ServiceApiKey` | — | | | `Tsak:Web:Lockout:MaxAttempts` | `5` | | | `Tsak:Web:Lockout:WindowSeconds` | `300` | | | `Tsak:Web:Lockout:DurationSeconds` | `60` | | ## `Tsak:Modules` — package loading | Key | Default | Notes | |---|---|---| | `Tsak:Modules:AssemblyPaths` | — | Where `.tpkg` packages are looked for. **Must be `["modules"]` in anything you ship** — a development tree tends to leave an absolute path here, and on another machine that resolves to nothing and the worker loads zero modules without complaining. | | `Tsak:Modules:Signature:Required` | `false` | | | `Tsak:Modules:Signature:PublicKeyPath` | — | | | `Tsak:Modules:Signature:PublicKeyPem` | — | Inline alternative to the path. | | `Tsak:Modules:Upload:Enabled` | `false` | Upload over the API is off by default. | | `Tsak:Modules:Upload:MaxSizeMB` | `100` | | | `Tsak:Modules:Upload:TargetPath` | — | | | `Tsak:Modules:Upload:KeepVersions` | `3` | | | `Tsak:Modules:Upload:RequireSignatureForUpload` | `true` | | ## `Tsak:HotReload` | Key | Default | Notes | |---|---|---| | `Tsak:HotReload:Enabled` | `true` | | | `Tsak:HotReload:ScanIntervalSeconds` | `30` | | | `Tsak:HotReload:Collectible` | `false` | With `false` a replaced or removed module version stays in memory until the process restarts. With `true` it is unloaded once nothing outside the module refers to it; a version that stays is logged and counted. See [README, "Module contexts in memory"](README.md#module-contexts-in-memory). | | `Tsak:HotReload:KeepVersions` | `2` | Old versions of a bare-DLL module kept for rollback. | | `Tsak:HotReload:MaxOrphanedContexts` | `KeepVersions + 3` | Module contexts that may stay in memory after their modules went before the `hotreload` health check turns Degraded ("restart the node to reclaim memory"). | ## `Tsak:Cluster` | Key | Default | Notes | |---|---|---| | `Tsak:Cluster:Enabled` | `false` | | | `Tsak:Cluster:ClusterName` | `default` | | | `Tsak:Cluster:GroupName` | `default` | | | `Tsak:Cluster:Strategy` | `round-robin` | | ## `Tsak:Storage` | Key | Default | Notes | |---|---|---| | `Tsak:Storage:Type` | `InMemory` | `Redb` to persist. | ## `Tsak:Audit` and `Tsak:Dlq` | Key | Default | |---|---| | `Tsak:Audit:Enabled` | `true` | | `Tsak:Audit:RetentionDays` | `90` | | `Tsak:Dlq:Enabled` | `true` | | `Tsak:Dlq:RetentionDays` | `30` | Both retention sweeps run as cluster singletons, so enabling them on every node does not multiply the work. ## `Tsak:Metrics` and `Tsak:Tracing` | Key | Default | Notes | |---|---|---| | `Tsak:Metrics:Prometheus:Enabled` | `false` | | | `Tsak:Metrics:Prometheus:Port` | `9464` | | | `Tsak:Metrics:Prometheus:RequireAuth` | `false` | The scrape endpoint is open unless you say otherwise. | | `Tsak:Metrics:Prometheus:AdditionalMeters` | — | Extra meters to export. | | `Tsak:Metrics:Prometheus:AdditionalSources` | — | Extra activity sources. | | `Tsak:Tracing:ServiceName` | — | | | `Tsak:Tracing:Otlp:Enabled` | `false` | | | `Tsak:Tracing:Otlp:Endpoint` | `http://localhost:4317` | | | `Tsak:Tracing:Otlp:Protocol` | — | `grpc` or `http/protobuf`. | ## `Tsak:Health`, `Tsak:Logs`, `Tsak:Alerts` | Key | Default | Notes | |---|---|---| | `Tsak:Health:DegradedNotReady` | `false` | Whether a degraded node reports itself not-ready. | | `Tsak:Logs:BufferSize` | `2000` | In-memory log ring for the dashboard. | | `Tsak:Alerts:Webhook:Url` | — | | | `Tsak:Watchdog:Alerts` | — | | ## `RedbRoute` — the route engine of every module context The worker binds redb.Route's `RouteEngineOptions` from this section for each module context it creates; the REST API's own context keeps the defaults. Every key of the redb.Route README, "Engine options", works here. An invalid value (a zero `Delay`, say) fails the creation of the context with the option's name in the error. | Key | Default | Notes | |---|---|---| | `RedbRoute:ConsumerStartRetry:Enabled` | `true` | Start a consumer that failed with its context again in the background. | | `RedbRoute:ConsumerStartRetry:Delay` / `MaxDelay` / `Multiplier` | `00:00:02` / `00:01:00` / `2` | The back-off. | | `RedbRoute:ConsumerStartRetry:MaxAttempts` | `0` | `0` retries until the context stops. | | `RedbRoute:ConsumerStartRetry:UnhealthyOnRestarting` | `true` | An `Errored` route waiting for a retry makes the `routes` check Unhealthy (readiness `503`); `false`: Degraded. | | `RedbRoute:ConsumerStartRetry:UnhealthyOnExhausted` | `true` | The same for an `Errored` route no retry waits for. | | `RedbRoute:ThreadPoolProfiles:{name}:*`, `RedbRoute:DefaultThreadPoolProfile:*` | 20 / 1000 / CallerRuns | Pools of Wire Tap and asynchronous OnCompletion. | | `RedbRoute:Attachments:MaxReplayableBytes` | see redb.Route | Also the limit of the checkpoint DLQ. | ## `Tsak:Contexts` — per-context settings Layers 1, 2 and 5 of the model in [CONFIG_GUIDE.md](CONFIG_GUIDE.md): | Key | Purpose | |---|---| | `Tsak:Contexts:default:*` | Base settings inherited by every context. | | `Tsak:Contexts:{name}:*` | Overrides for one context. | | `Tsak:Contexts:{name}:AutoStart` | Start the context with the worker. | | `Tsak:Contexts:{name}:Dependencies` | Contexts that must start first. Added to what the modules declare: `ITsakModule.Dependencies` and the `Dependencies` of the package manifest, which name modules and packages. | | `Tsak:Contexts:{name}:Override:*` | Wins over everything, including `context.json`. Intended for deployment-time secrets. | --- ## If a setting is not taking effect 1. **Check a higher layer is not overwriting it.** `Tsak:Contexts:{name}:Override` beats everything. [CONFIG_GUIDE.md](CONFIG_GUIDE.md) has the full order. 2. **Read the startup log.** The worker prints which redb settings it applied and warns about keys it did not recognise. A warning naming your key means the spelling is wrong; silence about a key you set means it never arrived. 3. **Check the environment-variable spelling.** `__` is the separator, not `:` and not `.`. 4. **For a named instance, check you are editing the right block.** Named instances take their settings from their own entry, not from `Tsak:Redb`. Path: redb-tsak/README.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/README.md ---- # redb.Tsak > **The runtime container for [redb.Route](https://github.com/redbase-app/redb-route) integration pipelines.** > Deploy DLLs into a folder. Start, stop, reload them at runtime. Scale across nodes with leader election. Watch every message, every error, every restart — from a built-in REST API, the `tsak` CLI, or a Blazor dashboard. Zero downtime. Production-tested. > **LLMs / coding agents:** canonical training contract for the whole redb ecosystem → [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue)](LICENSE) [![.NET](https://img.shields.io/badge/.NET-10%20%7C%2011-purple)](https://dotnet.microsoft.com) [![Website](https://img.shields.io/badge/docs-redbase.app-orange)](https://redbase.app) [![Status](https://img.shields.io/badge/status-production-green)](#) [![REST API](https://img.shields.io/badge/REST_API-JSON-blue)](#rest-api) [![CLI](https://img.shields.io/badge/CLI-tsak-blue)](#cli) [![Web UI](https://img.shields.io/badge/Web_UI-Blazor_Server-512BD4)](#web-dashboard) [![Cluster](https://img.shields.io/badge/cluster-leader_election-orange)](#cluster-mode) --- ## Table of Contents - [What you get out of the box](#what-you-get-out-of-the-box) · [Why redb.Tsak exists](#why-redbtsak-exists) · [For redb.Route users](#for-redbroute-users) - [Architecture](#architecture) · [Project structure](#project-structure) - [Quick start](#quick-start): Docker images, standalone archive, build from source - [Module workflow](#module-workflow) · [5-layer configuration](#5-layer-configuration) - [REST API](#rest-api) · [CLI](#cli) · [Web dashboard](#web-dashboard) - [Cluster mode](#cluster-mode) · [Watchdog](#watchdog) · [Lifecycle & graceful shutdown](#lifecycle--graceful-shutdown) · [Storage modes](#storage-modes) - [Security](#security) · [Observability](#observability) (health probes, logs, tracing) · [Quartz scheduler](#quartz-scheduler) - [Three deployment recipes](#three-deployment-recipes) · [Docker](#docker) · [Kubernetes deployment](#kubernetes-deployment) - [Testing](#testing) · [Frequently asked questions](#frequently-asked-questions) · [Roadmap](#roadmap) - [Upgrading](#upgrading): [UPGRADING.md](UPGRADING.md), [CHANGELOG.md](CHANGELOG.md) Guides: [DEPLOYMENT.md](DEPLOYMENT.md) · [MODULE_DEPLOYMENT.md](MODULE_DEPLOYMENT.md) · [CONFIG_GUIDE.md](CONFIG_GUIDE.md) · [PARAMETERS.md](PARAMETERS.md) · [API_GUIDE.md](API_GUIDE.md) --- ## What you get out of the box | | | |---|---| | **Module-based deployment** | Drop a package or a `.dll` into `modules/` — Tsak loads it, builds an `IRouteContext`, starts the routes. Update the DLL — Tsak hot-swaps it without dropping a single in-flight message in other contexts. | | **Three deployment modes** | `Standalone` (in-memory, no DB) · `Single-node + redb` (durable RTTI-storage state) · `Cluster` (leader election + automatic context redistribution across nodes). | | **Two API modes** | `Full` (REST API + management) · `Headless` (`Tsak:Api:Enabled=false`: no port, embedded use). For read-only access issue a key with the `viewer` role: such a key can call `GET` endpoints only. | | **5-layer configuration** | Module ships defaults. DevOps overrides. Config hot-reloads. No code changes, no restarts. | | **Built-in observability** | Per-process metrics (CPU/RAM/threads/GC, 12h history), per-route metrics (count/error rate/latency), ring-buffer logs, OpenTelemetry traces, optional Prometheus scrape. | | **Watchdog** | Detects suspected and hung routes. Optionally auto-restarts them. | | **Quartz scheduler** | A scheduler per context, as Apache Camel has one per CamelContext — modules never collide on job names. `RAMJobStore` standalone, `AdoJobStore` cluster-safe — schema auto-created on first start. | | **Security** | API Key + HMAC-SHA256 + roles + expiry + revocation. Constant-time comparison. redb-backed key store. Optional user binding (disabled user → key dies). | | **Module isolation** | Per-module `AssemblyLoadContext` — dependencies don't conflict between modules. | | **Clients ready to ship** | Typed C# `ITsakApiClient`, the `tsak` CLI with profiles and JSON output, Blazor Server dashboard. | --- "redb.Tsak — .NET analogue of Apache Camel K". ## Why redb.Tsak exists Most .NET teams either: 1. **Bake their integration code into a Worker Service** — every change means redeploy the entire process. Multiple unrelated pipelines fight in the same `Program.cs`. 2. **Buy a heavyweight enterprise ESB** — pay six figures for a UI, a runtime, a management API, and a deployment workflow they barely use. 3. **Roll their own management plane** — and re-invent metrics, hot-reload, leader election, and an admin API for the third time this decade. Tsak is the missing piece between "a Worker Service" and "an enterprise ESB": | | Hand-rolled Worker | Tsak | Heavy ESB | |---|---|---|---| | Deploy a new pipeline | Redeploy whole process | `cp module.tpkg modules/` (hot-reload) | Vendor wizard, hours | | Stop one pipeline without affecting others | Custom code | `tsak context stop orders` | Vendor UI | | Distribute pipelines across nodes | Custom coordinator | Built-in leader election + auto-rebalance | Vendor cluster | | REST API for ops/CI | Build it yourself | 75 endpoints in 17 controllers, typed client | Yes, vendor-locked | | CLI for CI/CD | Build it yourself | `tsak` CLI, profiles, JSON output | Maybe | | Web dashboard | Build it yourself | Blazor Server dashboard | Yes, vendor-locked | | Cost | Engineering time | Apache 2.0, free | $$$$ + lock-in | | Routing engine | DIY or MassTransit | **redb.Route** — 30 transports, 30+ EIP patterns, fluent C# DSL and XML routes | Vendor's DSL | --- ## For redb.Route users If you already write `RouteBuilder` classes for [redb.Route](https://github.com/redbase-app/redb-route), Tsak is what runs them in production. You do not change a single line of route code. ``` ┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐ │ Your routes │ ---> │ class library │ ---> │ Tsak picks it up │ │ (RouteBuilder) │ publish │ (Orders.dll) │ cp │ hot-reload + run │ └──────────────────────┘ └──────────────────────┘ └──────────────────────┘ ``` What Tsak adds **on top** of a plain `redb.Route` worker: | Pure `redb.Route` worker (`Host.CreateApplicationBuilder`) | `redb.Route` inside Tsak | |---|---| | One `Program.cs` wires every `RouteBuilder` at compile time. | Drop the package into `modules/`, Tsak loads it. | | Add a route → redeploy the whole process. | Hot-reload one module without touching the others. | | One process = one bag of routes. | Multiple **named contexts**, each with its own properties, lifecycle and assembly load context. | | Stop one route = stop the process. | `tsak route stop ` or `POST /api/routes/{id}/stop`. | | Distribute across nodes = roll your own coordinator. | Built-in leader election + per-context assignment across cluster nodes. | | Schedule a job = wire Quartz yourself in `Program.cs`. | Every context gets its own scheduler with its first `cron:` route, schema auto-bootstrapped. | | Operate it = parse logs, build a dashboard, expose metrics yourself. | REST + CLI + Blazor + Prometheus + OTel out of the box. | A `RouteBuilder` you wrote against `redb.Route`'s plain `IHostedService` runs unchanged inside a Tsak module — the same `Configure()` is called, the same `IExchange` flows through, the same `OnException` and `.Transacted()` semantics apply. Tsak only owns **how** the routes are loaded, scheduled, observed and torn down. ```csharp // MyRoutes/InitRoute.cs — the only Tsak-specific piece public static class InitRoute { public static IRouteContext main(IRouteContext context) { // Plain redb.Route — exactly what you would write outside Tsak ((RouteContext)context).AddRoutes(new OrderRoutes()); ((RouteContext)context).AddRoutes(new ShipmentRoutes()); return context; } } ``` For the routing DSL itself (transports, EIP patterns, expressions, transactional pipelines, OnException, error handling), see the [redb.Route README](https://github.com/redbase-app/redb-route). Everything below in this document is about the **container**. redb.Route now includes an Amazon **SQS + SNS** connector (`redb.Route.Sqs`) and a **Telegram Bot** connector (`redb.Route.Telegram`) — both bundled into the Tsak distribution at release. --- ## Architecture ### Process layout ``` ┌────────────────────────────────────────────────────────────────────┐ │ redb.Tsak.Worker │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ _system context (protected, cannot be stopped or removed) │ │ │ │ ────────────────────────────────────────────────────────── │ │ │ │ HTTP listener → AuthMiddleware → ControllerDispatcher │ │ │ │ /api/auth Bearer / X-Api-Key AuthController │ │ │ │ /api/contexts role check ContextsController │ │ │ │ /api/modules ModulesController │ │ │ │ /api/cluster ClusterController │ │ │ │ /api/system SystemController │ │ │ │ /api/scheduler SchedulerController │ │ │ │ /api/logs LogsController │ │ │ │ /api/users UsersController │ │ │ │ /api/watchdog /api/diagnostics /api/lifecycle /api/routes │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ │ │ Context A │ │ Context B │ │ Context C │ │ │ │ "orders" │ │ "payments" │ │ "analytics" │ │ │ │ ────────────── │ │ ────────────── │ │ ────────────── │ │ │ │ Module: │ │ Module: │ │ Modules: │ │ │ │ Api.Orders │ │ Pay.Stripe │ │ Etl.Loader │ │ │ │ Route 1: Kafka │ │ Route 1: HTTP │ │ Etl.Reports │ │ │ │ Route 2: Cron │ │ Route 2: AMQP │ │ Route 1..N │ │ │ │ Route N: HTTP │ │ Route N: Mail │ │ │ │ │ │ ALC: isolated │ │ ALC: isolated │ │ ALC: isolated │ │ │ └────────────────┘ └────────────────┘ └────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Infrastructure services │ │ │ │ ────────────────────────────────────────────────────────── │ │ │ │ HotReloadService ClusterCoordinator QuartzScheduler │ │ │ │ ModuleRegistry LeaderElection WatchdogService │ │ │ │ ContextManager NodeRegistry MetricsService │ │ │ │ ConfigMerger AssignmentManager LogRingBuffer │ │ │ │ HealthCheckService │ │ │ └──────────────────────────────────────────────────────────────┘ │ └────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────┐ │ redb (Postgres or MSSQL) │ │ - API keys (RedbApiKeyStore) │ │ - Cluster topology (Tree) │ │ - Lifecycle events │ │ - Idempotent state │ │ - Quartz QRTZ_* tables │ └─────────────────────────────────┘ ``` ### Anatomy of a request ``` External call: curl -H "Authorization: Bearer $KEY" http://node:9090/api/contexts/orders/start │ ▼ HTTP listener (Kestrel) inside _system context — port 9090 │ ▼ HeaderBridge processor → normalizes route.path = "contexts/orders/start", route.method = "POST" │ ▼ AuthorizeProcessor → resolves API key (5min cache) → validates role → enriches Exchange with claims │ ▼ ControllerDispatcher → looks up [Route("contexts/{name}/start")] on ContextsController │ ▼ ContextsController.Start → ITsakContextManager.StartAsync("orders") │ ▼ → graceful start: load assemblies → wire routes → connect transports → mark Running │ ▼ JSON response → { "name": "orders", "status": "Running", "startedAt": "..." } ``` The same `ContextsController` can also be invoked over **RabbitMQ RPC**, **gRPC**, **SignalR**, or any other `redb.Route` `InOut` transport — the dispatcher is transport-agnostic. This is how Tsak avoids tying its management API to HTTP-only. --- ## Project structure ``` redb.Tsak/ ├── src/ │ ├── redb.Tsak.Core/ Kernel: contracts, controllers, services, │ │ security, cluster, hot-reload, monitoring │ ├── redb.Tsak.Core.Pro/ Pro extensions (cluster, hooks, monitoring) │ ├── redb.Tsak.Worker/ Hosted process: DI wiring, Serilog, │ │ Quartz, appsettings.json, Dockerfile │ ├── redb.Tsak.Contracts/ Wire DTOs (System.Text.Json only) shared │ │ between Core, Client, Web, CLI │ ├── redb.Tsak.Client/ ITsakApiClient + TsakApiClient (HTTP) │ ├── redb.Tsak.CLI/ tsak CLI, profiles, JSON output │ ├── redb.Tsak.Web/ Blazor Server dashboard, custom design system │ └── redb.Tsak.Web.Pro/ Pro web extensions (auth, node providers) ├── tests/ │ ├── redb.Tsak.Tests/ Unit and HTTP integration tests (no database server) │ ├── redb.Tsak.Tests.Integration/ Tests against PostgreSQL and SQL Server │ ├── redb.Tsak.Web.Tests/ Dashboard tests │ └── redb.Tsak.CLI.Tests/ CLI command tests ├── docs/ │ ├── PLAN.md Architecture reference │ ├── CONFIG_GUIDE.md 5-layer configuration deep-dive │ ├── LT_TSAK_ANALYSIS.md Analysis of the original lt.tsak │ ├── ENTERPRISE_AUDIT.md │ └── phases/ Per-phase implementation notes (0..8B) ├── README.md This file ├── API_GUIDE.md REST API: endpoint map, pipeline, auth, probes ├── MODULE_DEPLOYMENT.md Module upload/rollback trust model & signing ├── CONFIG_GUIDE.md 5-layer configuration model ├── PARAMETERS.md Every Tsak:* setting, defaults, and the traps ├── DEPLOYMENT.md Running the published images ├── CHANGELOG.md Per-version changes ├── CONTRIBUTING.md Contribution guide ├── SECURITY.md Security policy └── LICENSE Apache 2.0 ``` --- ## Quick start ### Option A — Docker (fastest) Pre-built images are published to GitHub Container Registry — no build step, no .NET SDK required: ```bash # Worker only (REST API + cluster, no UI) docker run -d --name tsak \ -p 9090:9090 \ -v $PWD/modules:/app/modules \ ghcr.io/redbase-app/redb-tsak-worker:latest # Stack (Worker + Web UI in one container, like rabbitmq:management) docker run -d --name tsak \ -p 9090:9090 -p 8085:8085 \ -e Tsak__Modules__AssemblyPaths__0=/app/worker/modules \ -v $PWD/modules:/app/worker/modules \ ghcr.io/redbase-app/redb-tsak-stack:latest # UI: http://localhost:8085 · REST: http://localhost:9090 ``` Mount your modules into the dedicated `modules/` directory, never over `Libs/`: `Libs/shared` holds the image's own redb and connector libraries, and a mount over it hides them. | Image | Contains | Size | Ports | |---|---|---|---| | `ghcr.io/redbase-app/redb-tsak-worker` | Worker (REST + cluster) | ~360 MB | `9090` | | `ghcr.io/redbase-app/redb-tsak-web` | Standalone Web UI | ~250 MB | `8085` | | `ghcr.io/redbase-app/redb-tsak-stack` | Worker + Web (supervisord) | ~430 MB | `9090`, `8085` | Tags: `latest`, ``, `-net10`. **With PostgreSQL (durable RTTI-storage state, multi-node, cluster):** ```bash docker run -d --name tsak \ -p 9090:9090 -p 8085:8085 \ -e Tsak__Modules__AssemblyPaths__0=/app/worker/modules \ -v $PWD/modules:/app/worker/modules \ -e ConnectionStrings__Postgres="Host=pg;Port=5432;Database=redb;Username=postgres;Password=postgres" \ ghcr.io/redbase-app/redb-tsak-stack:latest ``` A compose file for the stack image is in [Docker → docker compose](#docker-compose); the full deployment guide is [DEPLOYMENT.md](DEPLOYMENT.md). ### Option B — Standalone archive (no Docker) Self-contained archives (no .NET runtime required on host) are attached to every [GitHub Release](https://github.com/redbase-app/redb-tsak/releases): | File | Platform | |---|---| | `redb-tsak--linux-x64.tar.gz` | Linux x64 | | `redb-tsak--win-x64.zip` | Windows x64 | Each archive bundles `worker/`, `web/`, `cli/`, the Route connectors **and the redb.\* framework** in `worker/Libs/shared/`, and startup scripts (`start-worker.sh`/`.bat`/`.ps1`, same for web and stack). #### Shared runtime layer — swappable redb.\* libraries The Tsak binary is deliberately thin: only `redb.Tsak.*` (+ `redb.Licensing`) live in the app bin. The **redb.\* framework and providers** (`redb.Core(.Pro)`, `redb.Route.*`, `redb.Postgres/MSSql/SQLite (.Pro)`) and every Route connector live in **`worker/Libs/shared/`**, byte-loaded at startup before any redb type is touched. - **Patch a library without rebuilding Tsak.** A binary-compatible fix of a redb leaf/provider/connector — or a new beta connector — is delivered by dropping its DLL into `worker/Libs/shared/`. No host rebuild, no archive re-spin. Use [`scripts/refresh-shared.ps1`](scripts/refresh-shared.ps1) `-Lib -SharedDir /worker/Libs/shared`, then re-zip / re-cosign the archive. - **Fail-fast + compat-gate.** A missing/corrupt framework DLL aborts startup with a precise message rather than failing later under load; the shared redb.\* **minor** must match the archive's Tsak minor (patches may differ) or startup is refused. - **What's loaded, really.** `GET /api/system/assemblies` (admin) reports every loaded assembly with its version and origin (shared / bin / runtime). ```bash VERSION= # the release to install, as on the releases page curl -LO https://github.com/redbase-app/redb-tsak/releases/download/v$VERSION/redb-tsak-$VERSION-linux-x64.tar.gz tar xzf redb-tsak-$VERSION-linux-x64.tar.gz cd redb-tsak-$VERSION-linux-x64 ./scripts/start-stack.sh # worker on :9090, web on :8085 ``` ### Verifying signatures (recommended) All images and archives are signed with [cosign](https://docs.sigstore.dev/cosign/installation/). The public key, `cosign.pub`, is attached to every [release](https://github.com/redbase-app/redb-tsak/releases). ```bash # Image cosign verify --key cosign.pub ghcr.io/redbase-app/redb-tsak-worker:$VERSION # Archive cosign verify-blob --key cosign.pub \ --bundle redb-tsak-$VERSION-linux-x64.tar.gz.bundle \ redb-tsak-$VERSION-linux-x64.tar.gz ``` SHA256 sums for every artifact are in `checksums.txt` on the release page. ### Option C — Build from source ```bash git clone https://github.com/redbase-app/redb-tsak cd redb-tsak/src/redb.Tsak.Worker dotnet run ``` ### 1. Run a Tsak worker (no database, in-memory) Any option above starts a worker with in-memory storage and no cluster. Its REST API answers on port 9090, and it scans the `modules/` directory for module packages (`Tsak:Modules:AssemblyPaths`): ```bash curl http://localhost:9090/api/health/live # {"status":"ok"} ``` ### 2. Deploy your first module A Tsak module is a plain .NET class library exposing one of two well-defined entry-point shapes: a `public static class InitRoute` with `public static IRouteContext main(IRouteContext ctx)` or its async form `public static async Task main(IRouteContext ctx)` (Apache Camel-style convention, shown below), or a concrete public type implementing `ITsakModule`. An async `main` is awaited, and the context starts only after it completes. An `InitRoute` whose `main` fits neither form is reported as an error when the assembly is scanned, not skipped. Inside the entry point you wire up your `RouteBuilder` subclasses against the supplied `IRouteContext`. ```csharp // MyRoutes/InitRoute.cs public static class InitRoute { public static IRouteContext main(IRouteContext context) { ((RouteContext)context).AddRoutes(new OrderRoutes()); return context; } } // MyRoutes/OrderRoutes.cs public class OrderRoutes : RouteBuilder { protected override void Configure() { From("kafka://orders?brokers=localhost:9092&groupId=svc") .Filter(e => e.In.GetHeader("type") == "new") .Process(async (e, ct) => await ProcessAsync(e, ct)) .To("rabbitmq://processed?host=localhost"); } } ``` ```bash # Build and deploy dotnet publish MyRoutes -c Release -o /opt/tsak/modules/ # straight into the module directory # Tsak picks it up within HotReload:ScanIntervalSeconds (default 10s) ``` ```bash tsak context list # Name Status Routes Endpoints Modules # _system Running 11 1 (system) # MyRoutes Running 1 2 MyRoutes ``` ### 3. Manage from the CLI ```bash tsak profile add --name local --url http://localhost:9090 --key $TSAK_KEY tsak profile use local tsak system health tsak context restart MyRoutes tsak log get --level Error --limit 50 tsak system metrics tsak scheduler jobs tsak cluster status ``` ### 4. Open the dashboard ```bash cd redb-tsak/src/redb.Tsak.Web dotnet run # Browse to http://localhost:5180 (the stack image serves it on 8085) ``` --- ## Module workflow Tsak supports **two equivalent deployment formats** in its module directory (`modules/`, set by `Tsak:Modules:AssemblyPaths`). Both are scanned by `HotReloadService`, hot-reloaded on file change, gracefully unloaded on file removal — pick whichever fits your workflow. | Format | What it is | When to pick it | |---|---|---| | **Bare directory** | A folder of loose `*.dll` files (+ optional config) | Local dev, fast inner loop, atomic file replace via `cp -r` | | **`.tpkg` package** | A single ZIP archive bundling manifest + DLLs + config | CI/CD, immutable artifacts, one-file deploys, atomic rollback | ### What Tsak actually loads Tsak does **not** load arbitrary .NET DLLs. Each candidate assembly is scanned for one of two well-defined module shapes: 1. A concrete public type implementing `ITsakModule`. 2. A public static class named `InitRoute` exposing a `static IRouteContext main(IRouteContext ctx)` method, or its async form `static Task main(IRouteContext ctx)` (Apache Camel-style entry point convention). Any other signature of `main`, or both forms at once, fails the scan of that assembly with a message naming the type and the two supported forms. If neither shape is found, the assembly is **classified as a dependency, not a module**: - It is registered in `LoadedAssemblyTracker` so that other modules in the process can resolve it as a transitive dependency (same `Assembly` instance everywhere — no type-identity drift across ALCs). - Its file timestamp is recorded in an internal "ignored" set; subsequent scans skip it unless the file is replaced with a newer version (which triggers a re-scan in case the new bits *do* contain a module). So the rule is: **random DLLs are not loaded as modules — but DLLs that other modules depend on are loaded and made available, just not started as routes.** This keeps the runtime predictable and prevents random vendor SDKs sitting in `modules/` from being treated as deployable units. ### Format 1 — Bare directory layout A directory of `Tsak:Modules:AssemblyPaths` is scanned at its top level, so a bare module's files sit right in it. To keep one folder per module, list each folder in `AssemblyPaths`. ``` modules/ ├── Orders.dll ← module entry point (contains ITsakModule or InitRoute.main) ├── Orders.deps.json ← dependency graph (from dotnet publish) ├── Orders.Domain.dll ← companion dependency (no module → loaded as dep only) ├── Newtonsoft.Json.dll ← any third-party dep that isn't already in the host ├── context.json ← infrastructure defaults (Layer 3) — optional, for the modules of this directory └── Orders.config.json ← module business settings (Layer 4) — optional ``` How the loader treats each file: | File | Role | |---|---| | `Orders.dll` | Loaded into a per-module isolated `ModuleAssemblyLoadContext`, scanned for `ITsakModule`/`InitRoute.main`, registered as a module | | `Orders.Domain.dll` | Scanned, no module shape found → kept as a shared dependency (resolvable by other ALCs) | | `*.deps.json` | Used by `dotnet publish` to record the full dep graph (Tsak does not parse it directly, but it is what makes `CopyLocalLockFileAssemblies=true` work) | | `context.json` | Layer 3 of the [5-layer config merge](#5-layer-configuration) | | `{Module}.config.json` | Layer 4 of the same merge | ### Format 2 — `.tpkg` package (atomic, immutable, isolated) A `.tpkg` is a plain ZIP archive bundling everything a module needs into a single file. Drop one file into `modules/`, Tsak picks it up and loads it as one atomic unit. Replace or delete that one file, the whole bundle reloads or shuts down together — no half-state in the middle. ``` Orders.tpkg (ZIP archive, flat structure) ├── manifest.json ← REQUIRED — package metadata ├── Orders.dll ← entry point (declared in manifest.EntryPoints) ├── Orders.config.json ← optional Layer 4 config ├── Orders.Domain.dll ← companion dependency (loaded into shared tracker) ├── Orders.Models.dll ← companion dependency └── Newtonsoft.Json.dll ← any other transitive dep not provided by the host ``` `manifest.json` schema (matches `redb.Tsak.Core.Modules.ModuleManifest`): ```json { "Name": "Orders", "Version": "1.0.0", "EntryPoints": [ "Orders.dll" ], "Dependencies": [] } ``` | Field | Meaning | |---|---| | `Name` | Logical package name. Must be unique across all packages loaded in the process. | | `Version` | Informational version string used in logs and diagnostics. | | `EntryPoints` | List of DLL filenames inside the archive that contain `ITsakModule` or `InitRoute.main`. Each entry is loaded into the **package's isolated ALC** and scanned for modules. | | `Dependencies` | Other packages this one depends on, by their `Name`. The contexts that run modules of those packages start first, both when the worker starts and on a hot reload. A name no package of the batch carries changes nothing: that package is already running or not deployed. Not a loading constraint. | A single `.tpkg` may declare **multiple entry points** — for example a `Core` module and an `Api` module that ship together and share a private dependency tree: ```json { "Name": "shop", "Version": "1.0.0", "EntryPoints": [ "shop.Core.dll", "shop.Api.dll" ], "Dependencies": [] } ``` Both entry-point DLLs land in the same isolated ALC, so they share static state and can pass non-public types between each other without serialization. ### Isolation model — what is shared, what is not Tsak runs many modules in one .NET process without letting them collide. The isolation model has three layers: | Layer | What lives here | Sharing semantics | |---|---|---| | **Default ALC** (host) | Tsak Worker, redb.Core, redb.Route abstractions, all NuGet deps the host ships with | Singleton — all modules see the same `IRouteContext`, `IRedbService`, etc. type identity. This is what makes interfaces work across the boundary. | | **`LoadedAssemblyTracker`** (shared dependency layer in Default ALC) | Companion DLLs from `.tpkg` files, bare-DLL non-module dependencies | One `Assembly` instance per assembly name across the whole process. If two packages each ship `MyCommon.dll` v1.5, the second one **reuses** the first load (last-loaded-wins on `forceReload=true` for hot updates). | | **Per-package `ModuleAssemblyLoadContext`** | Entry-point DLLs declared in a package's `manifest.json` | **Isolated.** Each package gets its own ALC. Two packages can ship two different versions of the same entry-point assembly without conflict. Resolving a missing reference falls through: package ALC → tracker → host Default ALC. | Concretely, this means: - **Host contracts (`IRouteContext`, `ITsakModule`, `IRedbService`, …) always resolve to the host's Default ALC.** A module never accidentally rebinds them to a private copy. - **Companion DLLs are de-duplicated.** If your package ships `Microsoft.Extensions.Logging.Abstractions.dll` and the host already has it, the host wins. If the host doesn't have it, the first package to ship it wins for the whole process. - **Entry-point code is fully isolated per package.** Module A cannot reach into Module B's static fields, even if they both extend the same base class — different ALC, different `Type` instance. - **One bad package does not poison the host.** A type-load failure in `Orders.tpkg` is logged and `Orders.tpkg` is skipped; every other package keeps running. ### How Tsak loads a module 1. `HotReloadService` scans every directory under `Tsak:Modules:AssemblyPaths` for `*.dll` and `*.tpkg`. 2. For each file the loader checks `LastWriteTimeUtc` against its known snapshot — unchanged files are skipped instantly. 3. **For a `.tpkg`**: the manifest is read, **companion DLLs load first** (so dependency resolution works), then **entry-point DLLs load into a fresh per-package ALC**. 4. **For a bare `.dll`**: the file loads into a fresh per-module ALC. If `ITsakModule`/`InitRoute.main` is found → it becomes a module; otherwise it is registered as a shared dependency and remembered as "not a module". 5. `ConfigMerger` deep-merges all 5 config layers into a single `IDictionary` and exposes it as the context's property bag. 6. `TsakContextManager` creates an `IRouteContext`, hands it the Quartz scheduler options and the `tsak-dlq:` endpoint, and awaits the module's `InitializeAsync` — which runs `InitRoute.main(ctx)` in either form, or the `ITsakModule`'s own initialization — before the context starts. 7. The context starts (if `AutoStart = true`): transports connect, consumers begin reading, routes go live. ### Hot-swap Replace the artifact on disk — that is the whole API. ```bash # Bare directory: atomic rsync over existing files rsync -a ./publish/ /opt/tsak/modules/ # .tpkg: replace the single file cp ./output/Orders.tpkg /opt/tsak/modules/ ``` `HotReloadService` detects the timestamp change, performs a **graceful swap** (start new ALC → wait for it to settle → drain old context's in-flight exchanges → stop old context → optionally unload old ALC). In a cluster each node performs this swap independently on its own scan schedule — to stagger an update, deploy the package to nodes sequentially yourself. (`HotReload:RollingUpdate` is reserved and not implemented yet.) ### Graceful shutdown when an artifact is removed Deleting a file from `modules/` is a first-class deployment operation, not an error condition. The runtime treats it as an explicit "stop and unload" command: | You do this | Tsak does this | |---|---| | `rm modules/Orders.tpkg` | After `RemovalDebounceScans` confirm the file is gone, **all modules from that package are unloaded atomically**: each context stops gracefully (drain in-flight, close transports, close DB connections), the package's isolated ALC is disposed. Other packages keep running. | | `rm modules/Orders.dll` | Same flow scoped to one bare-DLL module: graceful context stop → unregister module → dispose its ALC. | The debounce (`HotReload:RemovalDebounceScans`, default `2` scans) protects against false positives during atomic file replacements where a deployment briefly removes the file before writing the new one. ### Hot-reload knobs | Key | Default | Behavior | |---|---|---| | `Tsak:Modules:AssemblyPaths` | `["modules"]` | Directories to scan for `*.dll` and `*.tpkg` files, at their top level. Never point it at `Libs/`, which holds the shared layer. | | `HotReload:ScanIntervalSeconds` | `10` | How often to scan the configured paths. | | `HotReload:KeepVersions` | `2` | Old versions kept in memory for one-command rollback (bare-DLL flow). | | `HotReload:StartupTimeoutSeconds` | `60` | Wait time for the new version to settle before retiring the old one. | | `HotReload:RollingUpdate` | `false` | RESERVED — not implemented; nodes reload independently. | | `HotReload:Collectible` | `false` | Enable `AssemblyLoadContext.Unload()` for full GC reclamation: an old module version is collected once nothing of the host refers to it (see "What does an unload release?" below). After each scan that let a context go, Tsak runs a few full collections in the background; a context still in memory after them is logged as a warning (`module context {Name} still alive after 10 collections`). With `false` (default) old contexts stay in memory until process restart. Either way the count is in `GET /api/system/info` (see "Module contexts in memory" below). | | `HotReload:MaxOrphanedContexts` | `KeepVersions + 3` | How many module contexts may stay in memory after their modules were replaced or removed before the `hotreload` health check turns Degraded with "restart the node to reclaim memory". The versions rollback keeps on purpose (`KeepVersions`) are not counted. The default leaves room for a few releases on top of the rollback history: a planned release swaps a module once or twice, so more than `KeepVersions + 3` left-over versions on one node means a series of swaps without a restart (a dev loop, or a module whose old version does not unload), and the memory they hold only grows from there. | | `HotReload:MaxWorkingSetMb` | none | A working set (MB) above which `GET /api/health/deploy` advises a cold deploy. Unset: the advice looks at the module contexts only. | | `HotReload:RemovalDebounceScans` | `2` | Number of consecutive scan cycles a missing file must persist before its module is unloaded — protects against false positives during atomic file replacement. | ### Module contexts in memory Each module version runs in its own load context. A hot swap, a package reload or a removal lets the old context go; whether it then leaves memory depends on `HotReload:Collectible`. Two numbers say where a node stands: | Number | Meaning | |---|---| | `ModuleContextsAlive` | Module contexts in memory: the live modules, the rollback history, the orphaned ones and the ones still unloading. | | `OrphanedModuleContexts` | Contexts Tsak let go that are still in memory. With `Collectible: false` that is every context let go; with `true`, the ones still alive after the unload check. A context that leaves memory later stops being counted. | They are in `GET /api/system/info` (with `MaxOrphanedModuleContexts` and `ModuleContextsNotice`), in the system metrics of `GET /api/diagnostics/dump` and `GET /api/dashboard`, on the node page of the dashboard, and in `tsak system info`, `tsak diagnostics dump` and `tsak diagnostics dashboard`. `HotReloadService.LeakedAlcCount` is the same number as `OrphanedModuleContexts`. Above `HotReload:MaxOrphanedContexts` the `hotreload` health check is Degraded and says "restart the node to reclaim memory"; with `Tsak:Health:DegradedNotReady` that also takes the node out of readiness. What to do then: [DEPLOYMENT.md, "After a series of hot swaps"](DEPLOYMENT.md#after-a-series-of-hot-swaps). A pipeline asks before it deploys: `GET /api/health/deploy` answers `200` with `hot-swap` (copy the package into `modules/` of the running node) or `409` with `cold-deploy` and the reason codes (cordon, stop, replace the packages, start, wait for ready, uncordon); `GET /api/health/deploy/cluster` asks every alive node in one call, and `tsak system deploy-advice [--cluster]` exits `0` or `3`. Like the probes it needs no API key: the body holds the node id, the verdict, the reason codes and the counts behind them, nothing about configuration, connections, routes or modules. Details: [API_GUIDE.md, "Deploy advice"](API_GUIDE.md#deploy-advice--apihealthdeploy); the Kubernetes and compose with TeamCity steps: [DEPLOYMENT.md, "Deploy advice in a pipeline"](DEPLOYMENT.md#deploy-advice-in-a-pipeline). ### Building a `.tpkg` Two production-tested approaches ship with the repo. Pick whichever matches your build pipeline. #### Option A — MSBuild target inside the `.csproj` Put packing inside the build itself. After every `dotnet build` the module is repackaged and dropped into the local Tsak `modules/` for instant hot-reload. This is the pattern used by [redb.Route.Demo](https://github.com/redbase-app/redb-route/tree/main/demo/redb.Route.Demo): ```xml true Orders $(MSBuildThisFileDirectory)..\redb.Tsak\src\redb.Tsak.Worker\modules <_TpkgStaging>$(IntermediateOutputPath)tpkg <_TpkgFile>$(MSBuildThisFileDirectory)output\$(TsakModuleName).tpkg ``` The `true` line is critical for class-library SDK projects — without it, NuGet `PackageReference` assemblies are not copied to `bin/` and your `.tpkg` ships with missing transitive dependencies. The final `` updates `LastWriteTimeUtc` on the copy, which guarantees `HotReloadService` notices the change even when the new file's content hash matches a recently-loaded version. #### Option B — Standalone PowerShell script Best when you want to package multiple projects together as one `.tpkg` (e.g. a `Core` + `Api` pair sharing private dependencies), or when you want fine-grained control over which DLLs to include. A module that bundles two entry-point projects plus three companions into one `shop.tpkg`: ```powershell param( [ValidateSet("Debug","Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $tfm = "net10.0" $pkgName = "shop" $staging = Join-Path $env:TEMP "${pkgName}_tpkg_staging" $tpkg = Join-Path $PSScriptRoot "output\$pkgName.tpkg" $modules = "..\redb.Tsak\src\redb.Tsak.Worker\modules" # 1. Build every project that contributes to the package dotnet build .\shop.Core\shop.Core.csproj -c $Configuration --nologo dotnet build .\shop.Api\shop.Api.csproj -c $Configuration --nologo # 2. Stage manifest, entry points, companion DLLs, configs if (Test-Path $staging) { Remove-Item -Recurse -Force $staging } New-Item -ItemType Directory -Path $staging | Out-Null Copy-Item .\shop.Core\manifest.json $staging Copy-Item ".\shop.Core\bin\$Configuration\$tfm\shop.Core.dll" $staging # entry point Copy-Item ".\shop.Api\bin\$Configuration\$tfm\shop.Api.dll" $staging # entry point Copy-Item ".\shop.Core\bin\$Configuration\$tfm\shop.Models.dll" $staging # companion Copy-Item ".\shop.Core\bin\$Configuration\$tfm\shop.Domain.dll" $staging # companion Copy-Item ".\shop.Core\shop.Core.config.json" $staging -ErrorAction SilentlyContinue Copy-Item ".\shop.Api\shop.Api.config.json" $staging -ErrorAction SilentlyContinue # 3. Zip and deploy if (Test-Path $tpkg) { Remove-Item $tpkg -Force } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $tpkg) Copy-Item $tpkg $modules -Force (Get-Item (Join-Path $modules "$pkgName.tpkg")).LastWriteTime = Get-Date # trigger hot-reload Remove-Item -Recurse -Force $staging ``` The corresponding `manifest.json` declares both entry points so Tsak loads each one as a separately-managed module inside the shared package ALC: ```json { "Name": "shop", "Version": "1.0.0", "EntryPoints": [ "shop.Core.dll", "shop.Api.dll" ], "Dependencies": [] } ``` #### Option C — Plain ZIP (any tool, any pipeline) A `.tpkg` is just a ZIP. Any tool that can write a ZIP can produce one: ```powershell Compress-Archive -Path manifest.json,Orders.dll,Orders.Domain.dll,Orders.config.json ` -DestinationPath Orders.zip -Force Move-Item Orders.zip Orders.tpkg -Force ``` Or `zip -j Orders.tpkg manifest.json *.dll *.config.json` on Linux. #### Excluding host-provided DLLs (recommended for shipping) Tsak Worker already loads dozens of assemblies (`redb.Core`, `redb.Route.*`, every transport it ships, Quartz, Serilog, ASP.NET Core). Repacking those into every `.tpkg` wastes disk, bloats the archive, and occasionally causes version skew if your module references a different version than the host. The recommended pattern is: build an exclude set from `redb.Tsak.Worker\bin\\*.dll` and skip any DLL in that set when staging — except for a small force-include list of packages you know are version-incompatible with the host's copy. ```powershell $hostBin = "..\redb.Tsak\src\redb.Tsak.Worker\bin\$Configuration\$tfm" $exclude = New-Object 'System.Collections.Generic.HashSet[string]' ( [System.StringComparer]::OrdinalIgnoreCase) Get-ChildItem "$hostBin\*.dll" | ForEach-Object { [void]$exclude.Add($_.Name) } # Always include these even if the host ships an older copy (binary-incompatible) $forceInclude = @( 'Microsoft.IdentityModel.*.dll' ) Get-ChildItem ".\bin\$Configuration\$tfm\*.dll" | ForEach-Object { $force = $false foreach ($pat in $forceInclude) { if ($_.Name -like $pat) { $force = $true; break } } if ($force -or -not $exclude.Contains($_.Name)) { Copy-Item $_.FullName $staging } } ``` The module's per-package ALC then resolves a force-included DLL from the package itself before falling through to the host's older copy in the Default ALC. --- ## 5-layer configuration The most powerful feature in Tsak's configuration model: deep merge across five layers, with predictable precedence. ``` Layer 1: Tsak:Contexts:default ← base for all contexts (lowest priority) Layer 2: Tsak:Contexts:{name} ← named context overrides Layer 3: modules/context.json ← module infrastructure defaults, next to the package or DLL Layer 4: modules/{Module}.config.json ← module business settings (or inside the .tpkg) Layer 5: Tsak:Contexts:{name}:Override ← DevOps final word (highest priority) ``` Later layers **deep-merge** over earlier layers. Nested objects merge recursively — they do not replace each other wholesale. ### Worked example ```json // appsettings.json { "Tsak": { "Contexts": { "default": { "AutoStart": true, "RabbitMQ": { "Host": "localhost", "Port": 5672 } }, "orders": { "Modules": ["Orders"], "RabbitMQ": { "Host": "rabbit-orders.local" }, "Override": { "RabbitMQ": { "Password": "from-secret-manager" } } } } } } ``` ```json // modules/context.json { "RabbitMQ": { "Vhost": "/orders", "Username": "orders-svc" } } ``` ```json // modules/Orders.config.json { "MaxRetries": 10 } ``` **Effective configuration for the `orders` context:** ```json { "AutoStart": true, "MaxRetries": 10, "RabbitMQ": { "Host": "rabbit-orders.local", // from Layer 2 (overrode Layer 1 "localhost") "Port": 5672, // from Layer 1 (preserved through merge) "Vhost": "/orders", // from Layer 3 (module ships default) "Username": "orders-svc", // from Layer 3 "Password": "from-secret-manager" // from Layer 5 (DevOps wins) } } ``` ### Hot-reload of config Edit `context.json` or `{Module}.config.json` while Tsak is running. The hot-reload scan re-merges all five layers and restarts the affected context with the new properties. **No worker restart required.** ### Named vs anonymous contexts - **Named** — explicitly defined in `Tsak:Contexts:{name}` with a `Modules` array. Multiple modules share one `IRouteContext`. - **Anonymous** — for any module not assigned to a named context. One module = one context, named after the module. ```json { "Tsak": { "Contexts": { "api": { "Modules": ["Api.Orders", "Api.Catalog"], "AutoStart": true } }} } ``` `Api.Orders` and `Api.Catalog` share the `api` context (and its property bag). Any other module gets its own anonymous context. ### A module's database A module reaches redb in two ways, and they are two different databases. **The worker's own redb.** `context.GetServiceProvider().GetRequiredService()` and an unnamed `context.GetRedbService()` return the database Tsak itself runs on. It is chosen by `Tsak:Redb:Provider` (`sqlite` by default) together with that provider's connection string: `ConnectionStrings:Postgres`, `ConnectionStrings:MSSql` or `ConnectionStrings:Sqlite`. Setting `ConnectionStrings:MSSql` alone does not move it to SQL Server: set `Tsak:Redb:Provider` to `mssql` as well, or SQL written for SQL Server runs against SQLite. The database must exist beforehand: redb creates its tables, not the database. ```bash Tsak__Redb__Provider=mssql ConnectionStrings__MSSql="Server=sql;Database=Orders;User Id=sa;Password=...;TrustServerCertificate=true" ``` **A named instance** is a database of the module's own, declared in the context configuration under `Redb:{name}`, in any of the five layers (usually the module's config file or `Tsak:Contexts:{name}`): ```json { "RedbInstanceName": "orders", "Redb": { "orders": { "Provider": "mssql", "ConnectionString": "Server=sql;Database=Orders;...", "UsePro": true, "EnsureCreated": true } } } ``` `Provider` and `ConnectionString` are required. Only the instance named by `RedbInstanceName` creates its schema on start (`EnsureCreated`); the others are registered without it. In a route, resolve the instance per exchange, `context.GetRedbService("orders", exchange)`, so that concurrent exchanges never share a connection. In `main` and other one-shot setup code, `context.GetRedbService("orders")` returns the shared instance. Full reference: [CONFIG_GUIDE.md](CONFIG_GUIDE.md). **Plain SQL through redb.Route.Sql.** The worker registers the ADO providers it ships under their invariant names, so a module, including one written in XML only, names the provider and does not register it: `Npgsql` (PostgreSQL), `Microsoft.Data.SqlClient` (SQL Server), `Microsoft.Data.Sqlite` (SQLite), as `ProviderName` of a `SqlConnectionFactory` bean or `provider=` of a `sql:` endpoint. **Plain SQL on redb's own connection.** Every context has the data source `redb`: a `sql:` step with `dataSource=redb` runs its statement on the connection the worker's redb works on for the exchange, and `dataSource=redb:orders` on the connection of the named instance `orders`. Inside a transacted block the statement commits or rolls back together with the block's redb steps on that database, on one connection. A name no instance of the context carries is refused when the context starts the endpoint, and again at the first exchange. A module that registers its own object under `redb` replaces the data source for its context. The limits (no `StreamList`, no polling consumer and others) are in the redb.Route.Sql README. ### A module's save interceptors A module cannot reach the worker's DI, so it subscribes a redb `IRedbSaveInterceptor` through its context, in `InitializeAsync` or `main`: ```csharp public async Task InitializeAsync(IRouteContext context) { context.GetService()?.Add(new NotifyFrontInterceptor()); // routes... return context; } ``` The subscription lives as long as the context. When Tsak removes the context (the module is unloaded, or reloaded and its context built anew) it removes every interceptor the context added, before the module's load context unloads; the module needs no cleanup. Stopping the context keeps them, as it keeps the routes. `Add` returns a handle that removes one interceptor earlier. Without a worker database (`Tsak:Redb:Provider` unset) the service is absent and `GetService` returns null. What such an interceptor sees and can do: - **Every save and delete of the worker**, not only the module's own: those of other modules, made through the worker's redb service or through the named instances of any context. Filter by scheme or object type inside the interceptor when only some objects matter. - **Veto over all of them.** An exception thrown from `SavingAsync` or `DeletingAsync` cancels the save or delete it was called for, whichever module made it. Throw only to stop a save that must not happen. - The semantics of `IRedbSaveInterceptor`: `SavedAsync` runs after the commit, or inside the transaction within `ExecuteAtomicAsync`; under `PropsSaveStrategy=ChangeTracking` `RedbSavedContext.Changes` lists the changed values. - A subscription reaches the next save or delete, scopes already open included; a save already running finishes with the interceptors it started with. --- ## REST API Every endpoint speaks JSON. Auth is opt-in (`Tsak:Auth:Enabled`) — when enabled, all endpoints require an API key except the auth-exempt health probes under `/api/health/*` (configurable via `Tsak:Api:AuthExempt`) and the [echo probe](#echo-probe). The API is itself a route context (`_system`): one catch-all HTTP listener whose pipeline is *header bridge → auth → controller dispatch*, with controllers discovered by assembly scan. **[API_GUIDE.md](API_GUIDE.md)** documents the full endpoint map, the request pipeline, the auth model, and the extension points. ### Controllers | Group | Endpoints | Purpose | |---|---:|---| | `/api/health` | 5 | Kubernetes probes startup / live / ready, deploy advice for the node and the cluster (auth-exempt) | | `/api/system` | 6 | Health / metrics / metrics-history / info / config / assemblies | | `/api/storage` | 3 | redb storage instances / stats / analyze | | `/api/contexts` | 8 | List / get / start / stop / restart / reset-route-states / endpoints / remove | | `/api/contexts/{ctx}/routes` | 8 | List / get / start / stop / force-stop / inflight / context-wide inflight / metrics | | `/api/modules` | 6 | List / get / remove / upload / validate / rollback (signed; upload off by default) | | `/api/watchdog` | 6 | Status / alerts / enable / disable / alert-status / test-alert | | `/api/diagnostics` | 2 | Dump (cluster-wide) / route-level diagnostics | | `/api/lifecycle` | 1 | Recent lifecycle events (filtered) | | `/api/audit` | 1 | Persisted admin-action trail (filtered, paged; `admin` role) | | `/api/exchanges` | 3 | Dead-letter queue: list / replay / discard failed exchanges | | `/api/logs` | 3 | Tail (incremental) / list-files / download-file | | `/api/scheduler` | 8 | Status / scheduled / running / start / standby / pause-job / resume-job / fire-job | | `/api/cluster` | 6 | Status / nodes / rebalance / remove-node / cordon / uncordon (Pro) | | `/api/auth` | 3 | Create / list / revoke API keys | | `/api/users` | 5 | User CRUD (redb-backed storage required) | | `/api/dashboard` | 1 | Aggregated snapshot for the UI (one round-trip) | ### Sample calls ```bash # Authenticate KEY="$(tsak auth create --name ci --roles admin --output json | jq -r .Key)" # Health curl -s http://localhost:9090/api/system/health | jq # { # "status": "Healthy", # "description": "All checks passed", # "checks": { "contexts": "Healthy", "metrics": "Healthy", "control-plane": "Healthy", "redb": "Healthy", "cluster": "Healthy" }, # "details": {}, # "timestamp": "2026-10-22T09:00:00Z" # } # Start a context curl -s -X POST -H "Authorization: Bearer $KEY" \ http://localhost:9090/api/contexts/orders/start | jq # Live in-flight exchanges in a route (debugging stuck routes) curl -s -H "Authorization: Bearer $KEY" \ http://localhost:9090/api/contexts/orders/routes/route-1/inflight | jq # Force-stop a hung route curl -s -X POST -H "Authorization: Bearer $KEY" \ http://localhost:9090/api/contexts/orders/routes/route-1/force-stop # Recent lifecycle events curl -s -H "Authorization: Bearer $KEY" \ "http://localhost:9090/api/lifecycle?contextName=orders&limit=20" | jq # Diagnostic dump (CPU profiles, GC info, thread states) curl -s -H "Authorization: Bearer $KEY" \ http://localhost:9090/api/diagnostics/dump > tsak-dump.json ``` ### Echo probe `/api/echo` (path: `Tsak:Api:Echo:Path`) reflects the request back as JSON: a liveness probe that also shows what the host received. It needs **no API key**, but it **ships stopped**. Start the route `system-echo` of the `_system` context from the dashboard (Routes) or with the API: ```bash curl -s -X POST -H "Authorization: Bearer $KEY" \ http://localhost:9090/api/contexts/_system/routes/system-echo/start ``` While the route is stopped, `/api/echo` answers `503` with the name of the route to start. ### Typed C# client ```csharp // redb.Tsak.Client has no DI extension: register the client yourself. The key goes out as the X-API-Key header. builder.Services.AddSingleton(_ => new TsakApiClient("http://tsak-prod:9090", builder.Configuration["TsakKey"])); public class MyService(ITsakApiClient tsak) { public async Task RestartAllAsync(CancellationToken ct) { var contexts = await tsak.ListContextsAsync(ct); foreach (var c in contexts.Where(c => c.Status == "Failed")) await tsak.RestartContextAsync(c.Name, ct); } } ``` --- ## CLI `tsak` is a single binary that talks to any Tsak worker. It supports multiple connection profiles, JSON output for CI, and rich tabular output for humans. ```bash # Profile management tsak profile add --name prod --url http://prod-1:9090 --key $PROD_KEY tsak profile add --name staging --url http://stg-1:9090 --key $STG_KEY tsak profile use prod tsak profile list # Per-call override tsak --url http://other:9090 --key $OTHER_KEY context list # Output format tsak context list # table (default) tsak context list --output json # JSON, for scripts and CI tsak context list --output quiet # nothing but the exit code ``` ### Command groups | Group | Commands | |---|---| | **system** | `system health`, `system metrics`, `system info`, `system config`, `system deploy-advice` | | **profile** | `profile list`, `profile add`, `profile remove`, `profile use` | | **auth** | `auth list`, `auth create`, `auth revoke` | | **context** | `context list`, `context get`, `context start`, `context stop`, `context restart`, `context remove` | | **route** | `route list`, `route get`, `route start`, `route stop`, `route inflight`, `route force-stop` | | **module** | `module list`, `module get`, `module remove`, `module keygen`, `module sign`, `module deploy`, `module validate`, `module rollback` | | **scheduler** | `scheduler status`, `scheduler jobs`, `scheduler running`, `scheduler start`, `scheduler standby`, `scheduler pause`, `scheduler resume`, `scheduler fire` | | **cluster** | `cluster status`, `cluster nodes`, `cluster rebalance`, `cluster cordon`, `cluster uncordon` | | **watchdog** | `watchdog status`, `watchdog alerts`, `watchdog enable`, `watchdog disable` | | **diagnostics** | `diagnostics lifecycle`, `diagnostics dump`, `diagnostics route`, `diagnostics dashboard` | | **dlq** | `dlq list`, `dlq replay`, `dlq discard` | | **log**, **audit** | `log get`, `audit` | `tsak --help` shows the arguments and options of a command. A required argument left out is named in the error (`Required argument '' is missing for command 'route get'.`), followed by the command's help. `module keygen` writes a signing key pair: `--out` is required, an existing pair is never replaced without `--force`, and the full paths of both files are printed ([MODULE_DEPLOYMENT.md](MODULE_DEPLOYMENT.md)). --- ## Web dashboard A separate Blazor Server process (`redb.Tsak.Web`) — works in two modes: | Mode | Storage | Node discovery | |---|---|---| | **Standalone** | None | Static node list in `appsettings.json` | | **Cluster** | Required (Postgres / MSSQL) | Discovered dynamically from redb cluster topology | ### Pages | Page | Highlights | |---|---| | **Dashboard** | Cluster overview, status donut chart, sparkline metrics, node list grid (sortable, filterable, paginated). | | **Cluster** | 3-level topology tree (cluster → group → node), module assignment, per-node health, click-through to NodeDetail. | | **NodeDetail** | 5 tabs: Contexts · Scheduler · Modules · Monitoring · Logs. Live Chart.js graphs (CPU, GC, memory, threads), 10s auto-refresh. | | **Routes** | All routes across all contexts. Status, message count, error rate, click-through to route detail. | | **RouteView** | Per-route deep-dive: definition, current state, in-flight exchanges, recent diagnostics. | | **Endpoints** | Consumer / producer endpoints per route. | | **Watchdog** | Suspected and hung route alerts with manual stop/restart actions. | | **Logs** | Searchable ring-buffer log viewer with level filter and tail mode. | | **Auth** | API key management UI — create, revoke (with confirmation). | | **Login** | Credential-based dashboard access (cluster mode = redb users; standalone = config). | ### Custom design system The dashboard uses a custom CSS design system — **no Bootstrap, no MUI, no Tailwind**. Built on CSS variables, supports dark/light theme, system fonts, inline SVG icons. Reusable components: `TsakGrid`, `TsakChart`, `TsakCard`, `TsakBadge`, `TsakIcon`, `TsakConfirmDialog`, `TsakToast`, `TsakPageHeader`, `TsakErrorBoundary`. --- ## Cluster mode Enable with `Tsak:Cluster:Enabled = true` and a Postgres/MSSQL connection string. Tsak handles the rest. ### What you get - **Leader election** — distributed lock in redb with TTL and epoch fencing. A new leader is elected automatically when the current one dies or loses its lock. - **Node registry** — each worker registers itself with periodic heartbeats. Dead nodes are evicted after `DeadNodeTimeoutSeconds`. - **Automatic module assignment** — the leader distributes modules across live nodes, one node per module (`Tsak:Cluster:Strategy`: `round-robin` or `least-loaded`). Modules are reassigned automatically when nodes join or leave. - **Hot-reload per node** — each node swaps a changed module on its own scan; Tsak does not sequence an update across nodes. To roll one out node by node, ask `GET /api/health/deploy/cluster` and cordon / uncordon each node in turn ([Deploy advice in a pipeline](DEPLOYMENT.md#deploy-advice-in-a-pipeline)). - **Cluster-wide diagnostics** — `tsak cluster overview` aggregates state from every node. ### Topology in redb Stored as a polymorphic 3-level tree using `redb.Tree` (so it shows up nicely in any redb-aware tool): ``` cluster:default ← scheme: _tsak_clusters └── group:default:default ← scheme: _tsak_groups ├── node:default:default:worker-1 ← scheme: _tsak_nodes ├── node:default:default:worker-2 ← scheme: _tsak_nodes └── node:default:default:worker-3 ← scheme: _tsak_nodes ``` Cluster operations (assignment, leader change, rebalance) mutate this tree atomically. Every operation is fenced by the leader's epoch token — a stale leader cannot corrupt state after losing election. Coordination records (nodes, locks, module assignments) are keyed and looked up by cluster **and** group, so several clusters on one database elect their own leaders and keep their own nodes and assignments, even with equal group names or node ids. ### Cluster configuration ```json { "Tsak": { "Cluster": { "Enabled": true, "ClusterName": "default", "GroupName": "default", "NodeId": "", "ApiEndpoint": "http://node-1.local:9090", "HeartbeatIntervalSeconds": 15, "DeadNodeTimeoutSeconds": 60, "LeaderLockTtlSeconds": 30, "Strategy": "round-robin" } } } ``` ### Node identity and Quartz instance `NodeId` names the node: its record, its locks, and, with `Quartz:quartz.scheduler.instanceId = NODE` (the shipped value), the Quartz instance of every context scheduler of the worker. Left empty it is the host name. - **`NODE`**: the schedulers take the node id. It stays across restarts, so a node that crashed takes its own fired triggers back at its first Quartz check-in instead of waiting until the cluster counts its old record as failed (about 15 s by default), and a preferred-node pin names a node that comes back. Every context's scheduler of the node carries the same id; each context is a Quartz cluster of its own (one scheduler name), so that is correct. - **`AUTO`**: Quartz draws a new id at every start. Nothing to configure; after a crash the old record waits out the check-in timeout. - **An explicit id** is used as written, for every context scheduler; give each worker its own. Every worker needs a node id of its own. A worker that finds its node id held by a record that is still alive watches it until its heartbeat would expire (`DeadNodeTimeoutSeconds`): a previous process of the node, killed and restarted at once, goes quiet and the start goes on; a second process with the same node id keeps beating and the start is refused with the host and the last heartbeat of the other. A record left by a clean stop is no conflict. Replicas: - **Kubernetes StatefulSet**: leave `NodeId` empty; the pod name (`tsak-0`, `tsak-1`) is the host name and stays across restarts. - **Docker Compose `deploy.replicas`**: leave `NodeId` empty; each container has a host name of its own, unique, but a re-created container gets a new one, which then behaves as `AUTO`. For a stable id run the workers as separate services with `hostname:` set, or set `Tsak__Cluster__NodeId` per service. - Never set one `NodeId` (or one explicit Quartz `instanceId`) in a configuration all replicas share. ### Pluggable cluster backends All cluster coordination is hidden behind interfaces in `redb.Tsak.Core.Pro`: | Interface | Shipped implementation (redb) | |---|---| | `ILeaderElection` | `RedbLeaderElection` (epoch-fenced lock in redb) | | `IDistributedLock` | `RedbDistributedLock` (TTL row in redb) | | `INodeRegistry` | `RedbNodeRegistry` (heartbeat rows) | | `IClusterCoordinator` | `ClusterCoordinator` (background loop; computes the assignments) | | `IClusterBootstrap` | `RedbClusterBootstrap` | | `IAssignmentManager` | `RedbAssignmentManager` (module-to-node records, one node per module, epoch-fenced) | The assignment strategy is `Tsak:Cluster:Strategy`: `round-robin` (default) or `least-loaded`. These are interfaces you can implement. `AddTsakCluster()` registers the redb implementations, so register your own **after** that call: the last registration of a service is the one resolved. The `ClusterCoordinator` only talks to these interfaces. ```csharp builder.Services .AddTsakCluster(builder.Configuration) // the redb implementations .AddSingleton(); // your own replaces RedbLeaderElection ``` --- ## Watchdog `WatchdogService` continuously inspects every route and classifies it into one of three states: ``` (no progress for SuspectedThresholdMinutes) ┌────────────┐ │ │ Healthy │ ─────────────────────────────────────► ┌─────────────┐ └────────────┘ │ Suspected │ ▲ └─────────────┘ │ │ │ (progress resumes) (no progress for HungThresholdMinutes) │ │ │ ▼ │ ┌─────────────┐ └─────────────────────────────────────────────── │ Hung │ └─────────────┘ │ (AutoRestartHungRoutes = true) │ ▼ Force-stop + restart route ``` Configurable: ```json { "Tsak": { "Watchdog": { "Enabled": true, "CheckIntervalSeconds": 10, "SuspectedThresholdMinutes": 0.5, "HungThresholdMinutes": 1.5, "AutoRestartHungRoutes": false } } } ``` Alerts surface in `/api/watchdog/alerts`, in the CLI (`tsak watchdog alerts`), and in the Web dashboard's Watchdog page. --- ## Lifecycle & graceful shutdown Tsak's startup and shutdown sequences are **deterministic** — `LifecycleHookOrdering` enforces the order so operators can rely on what is up before what depends on it, and what drains before what stops. ### Startup order (Worker DI) 1. **`QuartzSchemaInitializer`** — applies Quartz DDL (Postgres / MSSQL) idempotently via raw ADO.NET. No redb dependency at this stage to avoid bootstrap deadlocks. 2. **`MetricsCollectionService`** — periodic process / GC sampling into the circular buffer. 3. **`TsakHostedService`** — main coordinator: shared assembly loader → module discovery → context start → cluster register. 5. **`RouteWatchdogService`** — hung-exchange detector. ### Shutdown sequence (`TsakHostedService.StopAsync`) 1. Logs `"Tsak graceful shutdown, stopping all contexts..."`. 2. Runs every `ITsakLifecycleHook.OnStoppingAsync()` **in reverse registration order** — last hook to start is first to stop. **Cluster deregistration is a hook**, so leadership is released *before* contexts begin draining. 3. For each context, calls `ITsakContextManager.StopContextAsync(ctx, CancellationToken.None)` — deliberately **not** the host shutdown token. One slow context cannot cancel the drain of the others. The contexts stop one after another, and each gets one drain window for its in-flight exchanges: `RedbRoute:ShutdownTimeout` (default 30 s) for a module context, the engine default of 30 s for `_system`. 4. `base.StopAsync()` releases hosted-service resources. 5. Quartz scheduler stops, Serilog sinks flush. Stop / restart REST responses include `DrainTimeMs` and `InflightAfter` — operators see exactly how long the drain took and whether anything was force-killed. SIGTERM handling is delegated to the standard .NET `IHostApplicationLifetime`. ### Lifecycle hooks ```csharp public class MyHook : ITsakLifecycleHook { public int Order => 10; // lower starts earlier and stops later public Task OnStartingAsync(CancellationToken ct) => /* before module discovery */; public Task OnStoppingAsync(CancellationToken ct) => /* before context drain (reverse order) */; } builder.Services.AddSingleton(); ``` Every start / stop / error event is also persisted by `LifecycleAuditService` and queryable through `/api/lifecycle`. --- ## Storage modes | Mode | API keys | Modules | Cluster | State | Use case | |---|---|---|---|---|---| | **InMemory** | `ConfigApiKeyStore` (read-only, from `appsettings`) | In-process registry | Not supported | Lost on restart | Dev, CI, embedded scenarios | | **Redb (Postgres)** | `RedbApiKeyStore` (redb, runtime CRUD) | Persistent | Supported | Survives restart | Single-node production, lightweight clusters | | **Redb (MSSQL)** | `RedbApiKeyStore` (redb, runtime CRUD) | Persistent | Supported | Survives restart | Single-node production, MSSQL shops | Switch modes with one config setting: ```json { "Tsak": { "Storage": { "Type": "Redb" }, "Redb": { "Provider": "postgres" } } } ``` When `UsePro = true`, [redb.Core.Pro](https://github.com/redbase-app/redb) is enabled — gives you redb change tracking (faster writes), distributed locking primitives, and the cluster topology features. --- ## Security | Layer | Mechanism | |---|---| | **Wire** | API Key in `Authorization: Bearer` or `X-Api-Key` header | | **Storage** | SHA-256 hash, raw key never persisted | | **Comparison** | `CryptographicOperations.FixedTimeEquals` (timing-attack safe) | | **Authorization** | Per-endpoint role checks on the ladder `viewer` < `operator` < `admin` (synonyms `reader`/`read`, `ops`, `administrator`); a higher role satisfies a lower one, a custom role matches by exact name only | | **Lifecycle** | Optional expiry per key, runtime revocation, immediate cache invalidation | | **User binding** | Optional `UserId` link — when the user is disabled or deleted, the key dies (via `IUserProvider`) | | **Cache** | 5-minute TTL key lookup cache, invalidated on revoke | | **Cluster trust** | Inter-node calls use the same API key auth — no implicit trust between nodes | | **Protected resources** | The `_system` context cannot be stopped or removed by any caller, including admins | Full policy: [SECURITY.md](SECURITY.md). Production secrets — which keys exist, what ships empty in the image, and how to inject connection strings, the dashboard login and the management-API secret through env vars — are covered in [DEPLOYMENT.md](DEPLOYMENT.md#5-dashboard--passwords). --- ## Observability ### Metrics - `MetricsService` — circular buffer with CPU, working set, managed memory, threads, GC pressure. Default window: **12 hours × 10s sample = 4320 points**. - `ContextMetricsCollector` — per-context aggregation: messages/sec, error rate, in-flight count. - Per-route metrics from `redb.Route`'s `.Metered()` step. - Cluster-wide periodic state report: `ClusterReportIntervalSeconds`. ### OpenTelemetry & Prometheus First-class OTel integration via the standard NuGet packages: - `OpenTelemetry.Extensions.Hosting` - `OpenTelemetry.Exporter.Prometheus.HttpListener` - `OpenTelemetry.Instrumentation.Process` - `OpenTelemetry.Instrumentation.Runtime` When `Tsak:Metrics:Prometheus:Enabled = true`, Tsak exposes a Prometheus-format endpoint at **`http://:9090/metrics`** — served straight from the facade's Kestrel server (the API port), auth-exempt. The OTel scrape listener itself binds **loopback** (`localhost:`, default 9464) and the `/metrics` route proxies it out. That means **no separate exposed port and no Windows URL ACL** — Kestrel binds sockets directly, so a wildcard `HttpListener` is never needed. `Tsak:Metrics:Prometheus:Port` only changes the internal loopback port. The OTel pipeline registers the redb.Route `ActivitySource` (`RouteActivitySource.SourceName`) so any tracing emitted by route processors is collected automatically — point an OTLP collector / Jaeger / Tempo at the activity source (see [Tracing](#tracing)), or scrape `:9090/metrics` from Prometheus. ```jsonc "Tsak": { "Metrics": { "Prometheus": { "Enabled": true, "Port": 9464 } // Port = internal loopback only }, "Tracing": { "ServiceName": "redb-tsak-worker", // OTel resource service.name (Jaeger/collector) "Otlp": { "Enabled": true, "Endpoint": "http://localhost:4317", "Protocol": "grpc" } } } ``` > The exporter is **pre-flighted**: if the loopback bind ever fails, Tsak logs a warning and > runs **without** metrics rather than crashing the host — an optional exporter must never take > the Worker down. Ready-to-use Kubernetes manifests, a Grafana dashboard and a local Prometheus + Grafana + Jaeger `docker compose` stack live under [`deploy/`](deploy/README.md). ### Health probes — Kubernetes-ready Distinct probes for the three K8s lifecycle phases. All three are **auth-exempt** by default (`Tsak:Api:AuthExempt`): | Endpoint | Probe type | Returns 200 when | |---|---|---| | `GET /api/health/startup` | startup | process is up | | `GET /api/health/live` | liveness | process is not deadlocked | | `GET /api/health/ready` | **readiness** | contexts are running **and** healthy (stricter than liveness) | > The probe endpoints live under **`/api/health/*`** (the auth-exempt prefix). The rich > aggregate at `GET /api/system/health` is a separate, auth-gated endpoint for CLI/Web. `HealthCheckService` aggregates probes (worst status wins: Unhealthy > Degraded > Healthy) and never throws — exceptions inside a probe become Unhealthy, never a 500. Modules can contribute custom probes by implementing `IModuleHealthContributor`. Pro ships `ClusterHealthContributor` reporting leader / member health. The `redb` check is **Degraded** while a redb database of the worker (the host's own or a named instance of a context) has schema problems that need a person, such as a root field of a scheme written twice by nodes of an older redb. The worker keeps serving and redb logs the problem as an error at every start; the check puts it where monitoring looks, with the problem and a link to redb's UPGRADING.md in `details`, the dashboard's node page and `tsak system health`. It reads what the last start found and queries no database on a poll. Readiness stays `200` on Degraded unless `Tsak:Health:DegradedNotReady=true`. Full breakdown of both health endpoints and the contributor SPI: [API_GUIDE.md](API_GUIDE.md#6-health-two-endpoints-two-audiences). The `routes` check is **Unhealthy** while a started context has an `Errored` route: its consumer failed to start (a broker not up yet) and waits for redb.Route's start retry, or the retries ran out. Its `details` name up to ten routes as `context/routeId`, so readiness answers `503` with them. As in Apache Camel since 4.7, `RedbRoute:ConsumerStartRetry:UnhealthyOnRestarting` and `UnhealthyOnExhausted` set to `false` report those phases Degraded instead, for a deployment where one broker that is down must not take the node out of the load balancer. Liveness does not read the check, and the watchdog leaves `Errored` routes to the start retry. ### Logs - `LogRingBuffer` — Serilog in-memory sink, default 2000 entries, queryable via REST and Web UI. - File logs via Serilog (rolling files, configurable path). - `MemoryUsageEnricher` — every log event carries `{MemoryUsage}` for cheap memory pressure correlation. ### Tracing - OpenTelemetry traces via `redb.Route`'s `.Traced()` step — per-route, per-step spans (route/transport spans like `route:identity-discovery` are captured automatically). - OTLP exporter — opt-in via `Tsak:Tracing:Otlp:Enabled` (+ `Endpoint`, `Protocol`). Ships traces to any OTLP collector or directly to **Jaeger** (native OTLP ingest on `:4317` gRPC / `:4318` http). Off by default. - Service identity via `Tsak:Tracing:ServiceName` (default `redb-tsak-worker`) — the `service.name` shown in Jaeger / the collector. ### Diagnostics - Per-route diagnostic dumps via `/api/contexts/{ctx}/routes/{id}/diagnostics`. - Cluster-wide dumps via `/api/diagnostics/dump`. - Lifecycle events feed (route start/stop/restart, hot-swap, cluster reassignment, watchdog alerts). - In-flight exchange tracking — see exactly which messages are sitting where right now. --- ## Quartz scheduler Every Tsak context runs its own Quartz scheduler — `{instanceName}-{context}`, as Apache Camel runs one per CamelContext — built with the context's first `cron:` / `qtimer:` route from the host's `Quartz` section. A job key is unique within a context, so two modules that both schedule `cron://nightly` never collide. On a clustered `AdoJobStore` a job fires on one of the nodes that run its context; don't add `.Cluster(true)` to such a route. Modules use it via `redb.Route.Quartz`: ```csharp From("cron:0 */5 * * * ?") // every 5 minutes .SetBody(() => DateTime.UtcNow) .To("rabbitmq://heartbeats"); ``` | Mode | Storage | Cluster-safe | Use | |---|---|---|---| | `RAMJobStore` | In-memory | No | Standalone, dev | | `AdoJobStore` | Postgres / MSSQL `QRTZ_*` tables | Yes | Production | Schema is auto-created on first start by `QuartzSchemaInitializer` — embedded SQL scripts for both Postgres and MSSQL, idempotent, runs **before** Quartz initializes its own connection pool. No DBA action required. REST endpoints under `/api/scheduler` cover: status (per context and for the node), listing scheduled jobs, listing currently-running jobs, start/standby, pause/resume/fire-now per job key — each with an optional `context`. --- ## Three deployment recipes ### Recipe A — Standalone, single binary For development, demos, embedded use. ```json { "Tsak": { "Storage": { "Type": "InMemory" }, "Cluster": { "Enabled": false }, "Auth": { "Enabled": false } } } ``` Just `dotnet run`. No DB, no auth, no cluster. Fastest path to running a Tsak module locally. ### Recipe B — Single node + redb (Postgres) For production single-node deployments where state must survive restarts. ```json { "ConnectionStrings": { "Postgres": "Host=db;Database=redb;Username=tsak;Password=$$" }, "Tsak": { "Storage": { "Type": "Redb" }, "Redb": { "Provider": "postgres", "UsePro": true }, "Cluster": { "Enabled": false }, "Auth": { "Enabled": true, "Secret": "$$" } } } ``` API keys persist. Quartz jobs persist. Lifecycle events persist. Module assignments persist. One node, durable state. ### Recipe C — Cluster For HA and horizontal scaling. Same `appsettings` on every node, only `NodeId` and `ApiEndpoint` differ: ```json { "ConnectionStrings": { "Postgres": "Host=db.cluster;Database=redb;Username=tsak;Password=$$" }, "Tsak": { "Storage": { "Type": "Redb" }, "Redb": { "Provider": "postgres", "UsePro": true }, "Cluster": { "Enabled": true, "ClusterName": "production", "GroupName": "default", "ApiEndpoint": "http://node-1.local:9090", "Strategy": "round-robin" }, "HotReload": { "RollingUpdate": false }, "Auth": { "Enabled": true, "Secret": "$$" } } } ``` Start three workers. They'll discover each other through the shared redb store, elect a leader and distribute your modules. Each node hot-swaps a changed package on its own; to update without downtime, deploy node by node as [Deploy advice in a pipeline](DEPLOYMENT.md#deploy-advice-in-a-pipeline) describes. --- ## Docker Pre-built images are published to GitHub Container Registry for every release — no build step required. See [Quick start → Option A](#option-a--docker-fastest) for the basic flow. This section covers production deployment. ### Image variants | Image | Best for | Default ports | |---|---|---| | `ghcr.io/redbase-app/redb-tsak-worker` | Headless workers (k8s `Deployment`/`StatefulSet`), one process per pod | `9090` (REST) | | `ghcr.io/redbase-app/redb-tsak-web` | Separate management UI pod talking to a worker cluster | `8085` | | `ghcr.io/redbase-app/redb-tsak-stack` | Single-host install (Worker + Web in one container, like `rabbitmq:management`) | `9090`, `8085` | Available tags: - `latest`, `` — net10 build (default). - `-net10` — Worker tag with an explicit TFM; pick one that matches your shared connector ABI. - Web and Stack ship on net10 only. ### Production run (Worker + external Postgres) ```bash docker run -d --name tsak \ -p 9090:9090 \ -v /opt/tsak/modules:/app/modules \ -e ConnectionStrings__Postgres="$PG_CONN" \ -e Tsak__Auth__Secret="$TSAK_SECRET" \ -e Tsak__Metrics__Prometheus__Enabled=true \ ghcr.io/redbase-app/redb-tsak-worker: ``` Mount `modules/` from the host (or a shared volume) so module updates can be deployed without rebuilding the image; never mount over `Libs/`, which holds the image's `Libs/shared` layer. `appsettings.json` overrides flow through environment variables in the standard ASP.NET pattern (`__` for nesting). ### docker compose ```yaml services: tsak: image: ghcr.io/redbase-app/redb-tsak-stack:latest ports: ["9090:9090", "8085:8085"] environment: - Tsak__Modules__AssemblyPaths__0=/app/worker/modules - ConnectionStrings__Postgres=Host=pg;Database=redb;Username=redb;Password=${PG_PASSWORD} volumes: - ./modules:/app/worker/modules:ro # your .tpkg packages (+ context.json) ``` Settings, secrets, a PostgreSQL service next to it and the cluster setup: [DEPLOYMENT.md](DEPLOYMENT.md). The module templates (`dotnet new redb-app`, `redb-worker`, ...) ship a `deploy/docker-compose.tsak.yml` of their own. ### Verifying images ```bash cosign verify --key cosign.pub ghcr.io/redbase-app/redb-tsak-worker: ``` The public key `cosign.pub` is attached to every [release](https://github.com/redbase-app/redb-tsak/releases). ### Building images yourself If you need a custom build (e.g. proprietary connectors baked in), build from [`src/redb.Tsak.Worker/Dockerfile`](src/redb.Tsak.Worker/Dockerfile) — a plain multi-stage `dotnet publish`, no private tooling involved. The template host ships its own [`Dockerfile`](templates/templates/tsak-worker/Dockerfile) for the same purpose. --- ## Kubernetes deployment Tsak is built from the ground up for container deployment — distinct K8s probes, OTel/Prometheus exporter, env-var configuration, and pluggable cluster backends are all in the box. ### Probes Map the three health endpoints to the matching K8s probe types: ```yaml startupProbe: httpGet: { path: /api/health/startup, port: 9090 } failureThreshold: 30 periodSeconds: 4 # up to 120s to boot livenessProbe: httpGet: { path: /api/health/live, port: 9090 } periodSeconds: 10 failureThreshold: 3 # 30s before pod restart readinessProbe: httpGet: { path: /api/health/ready, port: 9090 } periodSeconds: 5 failureThreshold: 2 # 10s before removal from load balancer ``` **Liveness** intentionally does *not* check module health — that avoids restart loops during rolling updates. **Readiness** is stricter: any context in a non-running state → pod is removed from service endpoints (no restart). ### Graceful termination Kubernetes sends SIGTERM, then SIGKILL after `terminationGracePeriodSeconds`. The drain of a context is bounded by `RedbRoute:ShutdownTimeout` (a `TimeSpan`, default `00:00:30`), and the worker stops its contexts **one after another**, so the stop can take up to: ``` cluster deregistration + one ShutdownTimeout per module context, in turn + up to 30 s for the _system context (the API keeps the engine default) ``` `terminationGracePeriodSeconds` must exceed that sum, or SIGKILL ends the drain of the contexts still waiting. A context whose exchanges finish early stops early; the sum is the worst case. The shutdown sequence: ``` SIGTERM → cluster deregister (lifecycle hook, reverse-order) → context drain (one context at a time, each up to its ShutdownTimeout) → Quartz shutdown → log flush ``` Example: a worker with two module contexts, a 20 s drain window each: ```yaml spec: terminationGracePeriodSeconds: 90 # > 2 × 20 s + 30 s (_system) + deregistration containers: - name: tsak env: - name: RedbRoute__ShutdownTimeout value: "00:00:20" ``` `Tsak:Shutdown:TimeoutSeconds` is read by no code: a manifest that sets it changes nothing, so set `RedbRoute:ShutdownTimeout` instead. ### Pod identity in cluster mode StableNode IDs across pod restarts matter for assignment continuity. Inject pod metadata via the downward API and bind `NodeId` to `metadata.name`: ```yaml env: - name: POD_NAME valueFrom: { fieldRef: { fieldPath: metadata.name } } - name: POD_NAMESPACE valueFrom: { fieldRef: { fieldPath: metadata.namespace } } - name: POD_IP valueFrom: { fieldRef: { fieldPath: status.podIP } } - name: Tsak__Cluster__NodeId valueFrom: { fieldRef: { fieldPath: metadata.name } } - name: Tsak__Cluster__ApiEndpoint value: http://$(POD_IP):9090 ``` Use a **StatefulSet** (or a Deployment + headless service) for predictable pod names. Tsak treats `Tsak:Cluster:NodeId` as the cluster identity — mapping it to `metadata.name` keeps assignment stable across restarts. ### Prometheus scraping ```yaml metadata: annotations: prometheus.io/scrape: "true" prometheus.io/port: "9090" prometheus.io/path: "/metrics" ``` Set `Tsak:Metrics:Prometheus:Enabled = true` to expose `/metrics` on the facade (port 9090). The OTel listener binds loopback only and is proxied out by the facade route — no separate metrics port and no Windows URL ACL. Ready-to-use manifests are under [`deploy/k8s/`](deploy/k8s). ### Native cluster integration All coordination interfaces (`ILeaderElection`, `IDistributedLock`, `INodeRegistry`, `IClusterCoordinator`, `IClusterBootstrap`, `IAssignmentManager`) are interfaces you can implement — see [Pluggable cluster backends](#pluggable-cluster-backends). The shipped implementations coordinate through redb. --- ## Testing Every release runs these suites (they live in the development repository, not in this one): | Suite | What's covered | |---|---| | `redb.Tsak.Tests` | Module loading, context lifecycle, config merge, security, controllers, monitoring and health, scheduler, cluster (leader election, heartbeat, rebalance, epoch fencing), hot-reload (ALC isolation, rollback, removal debounce), in-memory and redb stores, host startup, full API integration | | `redb.Tsak.CLI.Tests` | CLI commands: output format (table/JSON/quiet), parse errors, error handling, auth failure, profile resolution, module signing keys | | `redb.Tsak.Web.Tests` | Dashboard sign-in and throttling, page authorization, node views, cluster client selection | | `redb.Tsak.Tests.Integration` | The worker against a real redb database (PostgreSQL) | --- ## Frequently asked questions **Is Tsak a routing engine?** No. Routing is [redb.Route](https://github.com/redbase-app/redb-route). Tsak is the runtime container that hosts route contexts, manages their lifecycle, and exposes a management surface. **Can Tsak load any .NET DLL?** Tsak loads class libraries that follow its module convention: a public static class `InitRoute` with a `main(IRouteContext)` method (or its async form), or a concrete public type implementing `ITsakModule`. A `RouteBuilder` subclass alone is not a module: register it from `main` with `ctx.AddRoutes(...)`. Other DLLs are loaded only as dependencies, never started as modules. **Is module isolation a sandbox?** No. It is a dependency isolation boundary (separate `AssemblyLoadContext` per module). A malicious module runs with the same OS privileges as the Tsak process. Restrict write access to `modules/` and `Libs/` accordingly. See [SECURITY.md](SECURITY.md). **Why is `Collectible: false` the default for hot-reload?** Because a collectible `AssemblyLoadContext` unloads only when nothing outside it refers to the module any more, and code the host does not control can: a library with a static cache of the types it handled, Emit-generated code kept outside the module's context. Default is the safe choice; with `true` Tsak checks after each scan that the old versions really go, and logs and counts the ones that stay (`OrphanedModuleContexts`, see "Module contexts in memory"). **What does an unload release?** (with `Collectible: true`) Everything the host and the framework hold of the module: - the context's routes, services, registry, the module's type resolver (`bean:`, ``, `outputClass`), its `${prefix.}` resolvers (`context.RegisterPrefixResolver`) and its save interceptors (`ITsakSaveInterceptors`): they are removed with the context; - the caches of redb.Route keyed by type (XML and SOAP serializers, Protobuf parsers, batch POCO properties, endpoint options): they hold the module's types weakly; - the caches the .NET libraries keep over the types they handled, System.Text.Json above all: redb and redb.Route empty them when a collectible context unloads (System.Text.Json does not let such a context go otherwise, [dotnet/runtime#65323](https://github.com/dotnet/runtime/issues/65323)), at the cost of cold caches in those libraries once per unload; - XmlSerializer generates its serializer into the module's own context, so it goes with it; a compiled `Regex` emits a matcher that is collected on its own. - the services a bean or component of the module takes in its constructor: redb.Route builds them without asking the host's DI container about the module's own types (`ILogger` comes from the host's `ILoggerFactory`, `IOptions` and the other options services hold the default instance, any other service over a module type is absent; redb.Route README, "Services of a collectible module's beans"), since that container keeps every type it was asked for as long as the process lives. What stays is what a module puts beyond the host's reach: a static of a library it ships, a thread or timer it starts and does not stop, a handler it subscribes to a process-wide event, and a service its own code asks the host's container for when the type is the module's own (`context.GetServiceProvider().GetService>()`; take `ILoggerFactory` and call `CreateLogger()` instead). **What happens to in-flight messages during hot-swap?** The old context drains (existing exchanges complete). The new context starts in parallel. Once the new context is healthy and `StartupTimeoutSeconds` elapses, the old context is retired. Zero message loss for transports that support graceful shutdown. **Can I write my own assignment strategy?** Two strategies ship, chosen with `Tsak:Cluster:Strategy`: `round-robin` (default) and `least-loaded`. `ClusterCoordinator` computes the assignments and `IAssignmentManager` stores them; for a placement of your own, implement `IClusterCoordinator` (see [Pluggable cluster backends](#pluggable-cluster-backends)). **Does Tsak support multi-region clusters?** Out of the box, no. The cluster coordination assumes low-latency access to the shared redb database. For multi-region, run one cluster per region and federate above the Tsak layer (e.g. via `redb.Route.RabbitMQ` shovels). **Why a custom design system instead of Bootstrap or MUI?** The dashboard is small and focused. Custom CSS keeps the bundle tiny, eliminates a major source of UI churn (vendor breaking changes), and gives full control over theming. CSS variables enable dark/light themes with no JS. **Is there an OpenAPI spec?** Not yet. The API is documented in [API_GUIDE.md](API_GUIDE.md) and exposed via the typed `ITsakApiClient`. OpenAPI / Swagger generation is on the roadmap. --- ## Roadmap - OpenAPI / Swagger generation for the REST API - Weighted cluster assignment strategies (CPU + memory composite) - Batch operations (`POST /api/contexts/batch/start`) - Webhook subscriptions for lifecycle events (push instead of poll) - Live config editor in the dashboard - Multi-region federation primitives --- ## Upgrading What changes from one version to the next, and what to do about it: [UPGRADING.md](UPGRADING.md) for the steps a breaking change needs, [CHANGELOG.md](CHANGELOG.md) for every release. --- ## Part of - [redb.Route](https://github.com/redbase-app/redb-route) — ESB & EIP framework for .NET (the routing engine Tsak hosts) - [redb.Core / redb.Core.Pro](https://github.com/redbase-app/redb) — RTTI storage backend (the persistence layer Tsak uses) - [RedBase](https://github.com/redbase-app) — full ecosystem --- ## License Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE). Copyright © 2024–2026 RedBase. Path: redb-tsak/SECURITY.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/SECURITY.md ---- # Security Policy — redb.Tsak ## Supported Versions | Version | Supported | |---------|-----------| | 1.0.0-preview.1 | Yes | Older versions do not receive security fixes. Upgrade to the latest release. --- ## Reporting a Vulnerability **Do not open a public GitHub issue for security vulnerabilities.** Report privately to: **support@redbase.app** Include in your report: - Package and version (`tsak --version`) - Deployment mode: `InMemory`, `Redb:Postgres`, `Redb:MSSql`, Cluster - Detailed description of the vulnerability - Steps to reproduce - Potential impact assessment - Your suggested fix (optional but appreciated) You will receive an acknowledgment within 2 business days. We aim to publish a fix and disclose the issue within 30 days. --- ## Scope This policy covers the following packages and components: | Project | Area | |---------|------| | `redb.Tsak.Core` | Authentication, API key store, cluster coordination, module isolation | | `redb.Tsak.Worker` | REST API, config handling, hosted service startup | | `redb.Tsak.Contracts` | Wire DTOs, input validation | | `redb.Tsak.Client` | HTTP client, credential handling | | `redb.Tsak.CLI` | CLI credential storage, `--key` flag handling | | `redb.Tsak.Web` | Web dashboard authentication, session management | --- ## Security Architecture ### API Authentication Tsak uses API Key authentication with HMAC-SHA256 hashing. - Raw keys are **never stored** — only `SHA-256(key)` is persisted - Key comparison uses `CryptographicOperations.FixedTimeEquals` to prevent timing attacks - Keys are transmitted via `Authorization: Bearer ` or `X-Api-Key: ` header - The `_system` context exposes the REST API and cannot be stopped or removed by any key, including admin keys ### Key Store - **InMemory mode**: keys are loaded from `Tsak:Auth:Keys` in `appsettings.json` at startup and are read-only at runtime - **Redb mode**: `RedbApiKeyStore` stores keys in the redb store — supports create, list, and revoke at runtime - 5-minute TTL cache reduces DB reads without significantly widening the revocation window ### Cluster Security - Leader election uses a distributed lock with epoch fencing — stale leaders cannot issue commands after losing election - Heartbeat-based dead-node detection prevents zombie nodes from holding locks indefinitely - Inter-node communication uses the same API Key authentication as external clients - Cluster state (topology, assignments) is stored in the redb store — access requires DB credentials ### Module Isolation - Each module is loaded in its own `AssemblyLoadContext` — a compromised module cannot directly access another module's types - `Collectible` ALC mode is **disabled by default**: an unload releases a module only when nothing outside it refers to it, and a library with a static cache of the module's types can keep it in memory. Tsak checks the unload and counts what stays (README, "Module contexts in memory"); unloading is a memory matter, not an isolation boundary - Modules are loaded from the `Tsak:Modules:AssemblyPaths` directories — **restrict write access** to these directories in production - Tsak does not sandbox module code — a module with malicious code runs with the same OS privileges as the Tsak process ### Configuration and Secrets - `Tsak:Auth:Secret` (JWT signing key) and connection strings must never be committed to source control - Use environment variable overrides or a secrets manager in production - See DEPLOYMENT_SECRETS.md for the complete secrets management guide --- ## Security Notes for Operators ### What the published image ships with The image starts with one command and therefore with no secrets of its own: packaging strips the development secret, and **`Tsak:Auth:Enabled` is off** — with authentication on and no secret the worker refuses to start. Until you change it, the management API on `9090` answers **without a key** (stop contexts, upload modules, issue keys, dump config), and it binds every interface of the container. The node says so at every start: ``` SECURITY: the Tsak management API is bound to a non-loopback address (0.0.0.0:9090) with authentication DISABLED. Anyone who can reach this port gets full unauthenticated admin ... ``` That is fine on a laptop and wrong on a network. Before the port faces anyone else: turn authentication on with your own secret (below), publish the port to `127.0.0.1` or a private network, and change the dashboard's `admin` / `admin`. A worker you run yourself, outside a container, binds loopback by default and is not exposed until you set `Tsak:Api:Host`. ### Harden the REST API in Production ```json { "Tsak": { "Auth": { "Enabled": true, "Secret": "", "Keys": [] } } } ``` - Always set `Tsak:Auth:Enabled = true` in production - Use a randomly generated `Secret` of at least 32 characters - Pre-seed keys via config only for bootstrap — manage keys at runtime via API - Assign minimal roles — `viewer` for monitoring systems, `operator` for day-to-day operations, `admin` only where keys, users, module removal or the cluster are managed ### Protect the Module Directory ```bash # Linux: restrict Libs/ to the tsak service account chown -R tsak:tsak /opt/tsak/Libs chmod -R 750 /opt/tsak/Libs ``` Unauthorized writes to `Libs/` can result in arbitrary code execution inside the Tsak process. ### TLS Tsak Worker's built-in API (`port 9090`) is HTTP only. In production: - Place a reverse proxy (nginx, Caddy, Traefik) in front and terminate TLS there - OR configure Kestrel TLS directly: ```json { "Kestrel": { "Endpoints": { "Https": { "Url": "https://0.0.0.0:9443", "Certificate": { "Path": "/certs/tsak.pfx", "Password": "..." } } } } } ``` ### Cluster Communication - All inter-node calls go through the REST API — secure it with API keys and TLS - Do not expose `port 9090` to the public internet — use a private network or VPN for cluster node communication - Rotate the `NodeId` if a node is decommissioned to prevent stale node resurrection ### Web Dashboard (`redb.Tsak.Web`) - The dashboard uses in-memory session authentication — sessions do not survive a server restart - Set strong `AdminLogin` / `AdminPassword` credentials; do not use defaults in production - In cluster mode, dashboard credentials are validated against the redb-backed user store — manage users via the Auth page - The dashboard communicates with worker nodes over HTTP — secure that channel with TLS ### Dependency Modules - Tsak executes module code with the same OS privileges as the host process — audit third-party modules before deployment - Pin module versions in `manifest.json` — Tsak's hot-reload will apply any updated DLL found in `Libs/` - Monitor the `WatchdogService` — unexpected module restarts may indicate a module crash-looping on bad input Path: redb-tsak/UPGRADING.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/UPGRADING.md ---- # Upgrading redb.Tsak What to check and change when moving to a new version. Each section lists the changes that need action; [CHANGELOG.md](CHANGELOG.md) has the full list of what changed. ## 4.8.0 ### An `Errored` route makes the node not ready A route whose consumer failed to start with its context (a broker, database or server not up yet, a listener port taken) is `Errored`; redb.Route starts its consumer again in the background (`RedbRoute:ConsumerStartRetry`). Tsak's health used to look only at whether each context had started, so `/api/health/ready` answered `200` while such a route took no messages. Health now has a `routes` check: it is Unhealthy while a started context has an `Errored` route, both while the route waits for a retry and after the retries ran out, as Apache Camel reports such a route DOWN since 4.7. Its details name up to ten routes as `context/routeId`, so the `503` of readiness and `tsak system health` say which. `/api/health/live` does not read it: a broker that is down does not restart the node. Action, for a deployment where one broker that is down must not take every node out of the load balancer (the old readiness): set the Camel switches to `false` in the worker's configuration. The route is then Degraded, which readiness passes unless `Tsak:Health:DegradedNotReady=true`: ```json "RedbRoute": { "ConsumerStartRetry": { "UnhealthyOnRestarting": false, "UnhealthyOnExhausted": false } } ``` `UnhealthyOnRestarting` covers a route waiting for its next retry, `UnhealthyOnExhausted` one no retry waits for any more (`MaxAttempts` ran out, `Enabled` is `false`, or a route policy refused the start). The watchdog does not restart `Errored` routes: the context's own start retry owns them. ### .NET 10 and .NET 11 only The redb.Tsak libraries (`redb.Tsak.Core`, `redb.Tsak.Contracts`, `redb.Tsak.Client` and the Pro parts) target `net10.0` and `net11.0`. The `net8.0` and `net9.0` builds are gone: .NET 8 and .NET 9 reached end of support on 10 November 2026. The worker and the dashboard, their images and archives stay .NET 10 applications. Action: a host or a module (`.tpkg`) built for .NET 8 or .NET 9 either stays on 4.7.x or moves its target framework to `net10.0` before taking this version. Nothing changes in the API. ### `ITsakApiClient` has `GetLogsBeforeAsync` `ITsakApiClient` gains `GetLogsBeforeAsync(long beforeId, int? limit, string? level, CancellationToken ct)`, the client side of `GET /api/logs?beforeId=`: the buffered log entries older than an id, newest first. `TsakApiClient` implements it. The interface has no default for it, as for its other members. Action: only a class of your own that implements `ITsakApiClient` (a test double, a wrapper) needs a change. Add the member: a wrapper forwards it to the client it wraps, a test double returns what the test needs. Code that only calls the client needs nothing. ### No licence code any more Pro is free of charge and needs no key, so Tsak no longer carries any licence code. Nothing reads a licence, nothing counts nodes against one, and nothing stops a node for one. Removed public types and members: - `redb.Tsak.Core.Extensions.LicenseConfigReader`; - `redb.Tsak.Core.Pro.Licensing.ITsakLicenseManager`, `TsakLicenseManager` and `TsakLicenseNodeLimitException` (the whole `redb.Tsak.Core.Pro.Licensing` namespace); - `ClusterOptions.LicenseCheckIntervalIterations` (`Tsak:Cluster:LicenseCheckIntervalIterations`). Constructors that change: - `ClusterCoordinator` loses its `ITsakLicenseManager licenseManager` parameter and its optional `IHostApplicationLifetime? appLifetime` parameter, which only the licence check used. - `RedbNodeRegistry` loses its `ITsakLicenseManager licenseManager` parameter. What a cluster sees: - Any number of nodes joins a group; no node is refused or stopped over a node count. - The periodic check in the coordinator's work loop that could stop a node (every `LicenseCheckIntervalIterations` heartbeats) is gone. - The node registration lock stays: a starting node still takes it, and still refuses to register when it cannot get it in 10 seconds, because the protocol check of the alive peers and the removal of records left by 4.0.x run under it. - The start-up log has no licence banner. What to do: - A host that builds the cluster through `AddTsakCluster` (the Worker does): nothing. - Code that constructs `ClusterCoordinator` or `RedbNodeRegistry` by hand, or substitutes `ITsakLicenseManager` in tests: drop that argument (and `appLifetime` for `ClusterCoordinator`). - Code that referenced the removed types: delete it. There is nothing to replace it with. - A configuration that still sets `Tsak:Redb:License` (or `Tsak__Redb__License`, `Tsak__Redb__License__0`, ...), a `License` key of a named `Redb` instance, or `Tsak:Cluster:LicenseCheckIntervalIterations`: nothing breaks. The `License` keys are ignored silently and the cluster option is no longer bound; remove them when convenient. ## 4.5.0 ### Package config beside a .tpkg **A `{Module}.config.json` on disk beside a `.tpkg` now overrides the one inside the package** (it was the other way round). Layer 4 is read as: the package's own `{Module}.config.json` first, then the file beside the package, so a deployment can change a value of a package without repacking it. The module's context name is looked up in the same order. Whom it concerns: only a folder that holds both a `.tpkg` and a `{Module}.config.json` of the same module with different values for one key (or a different `ContextName`): the file on disk now wins. Projects made from the redb.Templates templates keep only `ContextName` and `AutoStart` inside the package and `context.json` beside it, and work as before. To keep the package's value, remove the key from the file beside it, or the file itself. ## 4.4 ### Node id and Quartz instance id **One node id, one live worker.** A worker that finds its node id (`Tsak:Cluster:NodeId`, or the host name) held by a record that is still alive watches it until its heartbeat would expire (`DeadNodeTimeoutSeconds`, 60 s by default): a previous process of the node goes quiet and the start goes on; a second live process keeps beating and this start is refused, naming the other's host and last heartbeat. Workers that today run with one shared `NodeId` (a value in a configuration all replicas read) stop starting: leave `NodeId` empty so each takes its host name, or give each its own. A worker restarted right after a crash may now wait up to `DeadNodeTimeoutSeconds` before it registers; after a clean stop it does not wait. **`Quartz:quartz.scheduler.instanceId` is `NODE` in the shipped configuration** (was `AUTO`): every context scheduler of the worker takes the node id, which stays across restarts, so a crashed node takes its own fired triggers back at its first check-in. A configuration of your own that sets `AUTO` or an explicit id keeps it. The records the earlier `AUTO` ids left in `qrtz_scheduler_state` are harmless, no live scheduler reads them; delete them by hand if you like, with the rows of every `qrtz_` table under scheduler names no worker uses any more. ### Quartz tables The scheduler of every route context runs on Quartz 3.22 (was 3.16). Its corrections change when or whether a job fires: a job with `[DisallowConcurrentExecution]` (a stateful cron route) is held to one run at a time across the whole cluster, where it used to be held per node only; day-of-month `L`, `LW` and `W` expressions, fire times in the repeated hour of a DST fall-back and day-based calendars near DST changes are corrected; pausing or resuming groups by prefix covers every matching group. The trigger of a running job that does not run concurrently reads `Blocked`, not `Complete`, in `GET /scheduled`, `tsak scheduler jobs` and the dashboard. With a clustered job store the worker brings the Quartz tables up to 3.22 at start: - `QRTZ_TRIGGERS.MISFIRE_ORIG_FIRE_TIME` (3.17): the time a misfired trigger was due, so a route's `CamelQuartzScheduledFireTime` is that time after a misfire under the fire-now policies; - `EXECUTION_GROUP` on `QRTZ_TRIGGERS` and `QRTZ_FIRED_TRIGGERS` (3.18); - `QRTZ_TRIGGERS.PREFERRED_NODE` and `PREFERRED_NODE_AUTO` (3.19): node affinity, which needs both. New installations get them from the create scripts. On an existing one the worker adds the missing columns under a lock (`pg_advisory_lock` on PostgreSQL, `sp_getapplock` on SQL Server, an immediate transaction on SQLite), so nodes starting together add each column once; existing triggers keep their state. **A database role that may not alter the Quartz tables** gets a warning naming the missing columns, and the worker goes on without them, as before. Run the administrator's script once: it ships beside the worker in `sql/quartz/quartz_3.22_{postgres,sqlServer,sqlite}.sql` (in the image and the archive). The script also carries the Quartz 3.20 index alignment, which drops and creates indexes and which the worker never runs on its own. The PostgreSQL and SQL Server scripts may run more than once; the SQLite one once, after checking `PRAGMA table_info`. Path: redb-tsak/redb.Tsak.slnx Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/redb.Tsak.slnx ----