Bundle: redb-tsak / src/redb.Tsak.Core (src.redb.Tsak.Core.txt), 153 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/src/redb.Tsak.Core/Audit/AuditQueryService.cs
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/src/redb.Tsak.Core/Audit/AuditQueryService.cs
----
using System.Data.Common;
using System.Globalization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using redb.Tsak.Contracts;
using redb.Tsak.Core.Services.Storage;
namespace redb.Tsak.Core.Audit;
///
/// Reads and prunes tsak_audit_log. Raw ADO.NET on purpose — the table is flat,
/// append-only and provider-specific, so going through redb would buy nothing and cost the
/// PVT round-trip on every filter.
///
/// All filtering and paging happens server-side; nothing is materialised and filtered in
/// memory. Every parameter is bound through with an explicit
/// type: timestamps as the column's own type per provider, and null filters as typed nulls, which
/// is what keeps the (@x IS NULL OR col = @x) shape parseable on PostgreSQL.
///
///
/// Several Tsak clusters may share the database: reads and the retention sweep see this node's
/// cluster (Tsak:Cluster:ClusterName) plus the entries written before cluster isolation.
///
///
public sealed class AuditQueryService
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
private readonly string _clusterName;
public AuditQueryService(IConfiguration configuration, ILogger logger)
{
_configuration = configuration;
_logger = logger;
_clusterName = TsakStorageScope.ClusterName(configuration);
}
/// Provider Tsak is configured with; means no database.
public AuditProvider Provider => AuditStorage.ResolveProvider(_configuration);
/// True when the audit table exists and can be queried.
public bool IsAvailable =>
_configuration.GetValue("Tsak:Audit:Enabled", true)
&& Provider != AuditProvider.None
&& !string.IsNullOrEmpty(AuditStorage.ResolveConnectionString(_configuration, Provider));
/// Newest-first page of audit entries matching the (all optional) filters.
public async Task QueryAsync(
string? actor = null,
string? action = null,
string? target = null,
DateTimeOffset? since = null,
DateTimeOffset? until = null,
int limit = 100,
int offset = 0,
CancellationToken ct = default)
{
if (!IsAvailable)
return new AuditQueryResult { Available = false, Entries = [] };
limit = Math.Clamp(limit, 1, 1000);
offset = Math.Max(offset, 0);
var provider = Provider;
var connStr = AuditStorage.ResolveConnectionString(_configuration, provider)!;
try
{
await using var conn = AuditStorage.CreateConnection(provider, connStr);
await conn.OpenAsync(ct);
await using var cmd = conn.CreateCommand();
cmd.CommandText = AuditStorage.SelectSql(provider);
BindQueryParameters(cmd, provider, actor, action, target, since, until, limit, offset);
ClusterColumn.BindScope(cmd, _clusterName);
var entries = new List();
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
entries.Add(Map(reader));
return new AuditQueryResult
{
Available = true,
Count = entries.Count,
Limit = limit,
Offset = offset,
Entries = entries.ToArray()
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Audit query failed ({Provider})", provider);
return new AuditQueryResult { Available = false, Error = ex.Message, Entries = [] };
}
}
/// Deletes entries older than the cutoff. Returns the number of rows removed.
public async Task PruneAsync(DateTimeOffset cutoff, CancellationToken ct = default)
{
if (!IsAvailable) return 0;
var provider = Provider;
var connStr = AuditStorage.ResolveConnectionString(_configuration, provider)!;
await using var conn = AuditStorage.CreateConnection(provider, connStr);
await conn.OpenAsync(ct);
await using var cmd = conn.CreateCommand();
cmd.CommandText = AuditStorage.DeleteOlderThanSql();
DbParameterBinding.AddTimestamp(cmd, provider, "cutoff", cutoff);
ClusterColumn.BindScope(cmd, _clusterName);
return await cmd.ExecuteNonQueryAsync(ct);
}
///
/// Binds the filter and paging parameters of , in the order and
/// with the types the statement needs; the cluster scope is bound next to it by the caller. Separate
/// from so the binding can be checked without a database: the shape of the
/// bound command is the whole difference between a page that loads and PostgreSQL's 42P08.
///
internal static void BindQueryParameters(
DbCommand cmd, AuditProvider provider,
string? actor, string? action, string? target,
DateTimeOffset? since, DateTimeOffset? until,
int limit, int offset)
{
DbParameterBinding.AddString(cmd, "actor", actor);
DbParameterBinding.AddString(cmd, "action", action);
DbParameterBinding.AddString(cmd, "target", target);
DbParameterBinding.AddTimestamp(cmd, provider, "since", since);
DbParameterBinding.AddTimestamp(cmd, provider, "until", until);
DbParameterBinding.AddInt32(cmd, "limit", limit);
DbParameterBinding.AddInt32(cmd, "offset", offset);
}
private static AuditEntry Map(DbDataReader r) => new()
{
EventId = GetString(r, "event_id") ?? "",
Timestamp = ParseTimestamp(r, "ts"),
Action = GetString(r, "action") ?? "",
ControllerType = GetString(r, "controller_type"),
ActorPrincipal = GetString(r, "actor_principal"),
ActorKeyId = GetString(r, "actor_key_id"),
RemoteIp = GetString(r, "remote_ip"),
UserAgent = GetString(r, "user_agent"),
HttpMethod = GetString(r, "http_method"),
RequestPath = GetString(r, "request_path"),
TargetResource = GetString(r, "target_resource"),
StatusCode = r.GetInt32(r.GetOrdinal("status_code")),
DurationMs = r.GetDouble(r.GetOrdinal("duration_ms")),
ExceptionType = GetString(r, "exception_type"),
ExceptionMessage = GetString(r, "exception_message"),
Payload = GetString(r, "payload")
};
private static string? GetString(DbDataReader r, string column)
{
var i = r.GetOrdinal(column);
if (r.IsDBNull(i)) return null;
// uuid (PG) and uniqueidentifier (MSSQL) come back as Guid, not string.
var value = r.GetValue(i);
return value as string ?? value.ToString();
}
///
/// PostgreSQL and SQL Server return a native date type; SQLite returns the ISO-8601 string
/// this code wrote.
///
private static DateTimeOffset ParseTimestamp(DbDataReader r, string column)
{
var i = r.GetOrdinal(column);
if (r.IsDBNull(i)) return default;
return r.GetValue(i) switch
{
DateTimeOffset dto => dto,
DateTime dt => new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Utc)),
string s when DateTimeOffset.TryParse(s, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var parsed) => parsed,
_ => default
};
}
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/AuditRetentionRouteBuilder.cs
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/src/redb.Tsak.Core/Audit/AuditRetentionRouteBuilder.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Tsak.Core.Audit;
///
/// Daily audit-log retention as a first-class redb.Route cron route (cron://tsak-audit-retention)
/// instead of a bare Quartz job — so it shows up in the Routes API/dashboard as well as the scheduler
/// page, and Tsak eats its own dog food (uses redb.Route + the Cron connector like any business route).
/// Prunes tsak_audit_log rows older than Tsak:Audit:RetentionDays. The cron://
/// consumer runs on the shared scheduler injected into every Tsak context, so it stays visible on the
/// scheduler dashboard. Registered by only when audit
/// persistence is active and retention is enabled.
///
public sealed class AuditRetentionRouteBuilder : RouteBuilder
{
/// Route id — how the sweep shows up in the Routes API and the dashboard.
public const string RouteIdName = "tsak-audit-retention";
/// Default retention window when the config key is absent.
public const int DefaultRetentionDays = 90;
/// Daily at 03:00 (Quartz cron). Kept off the top of the hour of nothing in particular.
public const string CronSchedule = "0 0 3 * * ?";
private readonly AuditQueryService _audit;
private readonly int _retentionDays;
private readonly ILogger? _logger;
public AuditRetentionRouteBuilder(AuditQueryService audit, int retentionDays, ILogger? logger)
{
_audit = audit;
_retentionDays = retentionDays;
_logger = logger;
}
protected override void Configure()
{
From($"cron://{RouteIdName}?schedule={CronSchedule}")
.RouteId(RouteIdName)
// No .Cluster(true): on a clustered job store Quartz fires the sweep on one node of the cluster, and the
// cluster layer does not apply a leader-only policy to a Quartz consumer. On a store that is not shared
// every node runs it; the prune is an idempotent DELETE-by-cutoff, so that is harmless.
.Process(async (IExchange exchange, CancellationToken ct) =>
{
if (!_audit.IsAvailable || _retentionDays <= 0) return;
var cutoff = DateTimeOffset.UtcNow.AddDays(-_retentionDays);
try
{
var removed = await _audit.PruneAsync(cutoff, ct);
if (removed > 0)
_logger?.LogInformation(
"Audit retention: removed {Removed} entries older than {Cutoff:o} ({Days}d)",
removed, cutoff, _retentionDays);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Audit retention sweep failed");
}
});
}
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/AuditSchemaInitializer.cs
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/src/redb.Tsak.Core/Audit/AuditSchemaInitializer.cs
----
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace redb.Tsak.Core.Audit;
///
/// Creates the tsak_audit_log table on startup for whichever provider Tsak is
/// configured with. Structured exactly like QuartzSchemaInitializer: raw ADO.NET
/// (redb may not be initialized yet), provider switch over Tsak:Redb:Provider, and an
/// embedded, idempotent DDL script per dialect.
///
/// No-ops when audit persistence is disabled or when Tsak runs without a database — in that
/// mode remains the sink.
///
///
internal sealed class AuditSchemaInitializer : IHostedService
{
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
public AuditSchemaInitializer(IConfiguration configuration, ILogger logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
if (!_configuration.GetValue("Tsak:Audit:Enabled", true))
{
_logger.LogDebug("Admin audit persistence disabled (Tsak:Audit:Enabled=false)");
return;
}
var provider = AuditStorage.ResolveProvider(_configuration);
if (provider == AuditProvider.None)
{
_logger.LogInformation(
"No redb provider configured — admin audit stays on the log sink (no {Table} table)",
AuditStorage.TableName);
return;
}
var connStr = AuditStorage.ResolveConnectionString(_configuration, provider);
if (string.IsNullOrEmpty(connStr))
{
_logger.LogWarning(
"Provider '{Provider}' is configured but its connection string is missing — " +
"admin audit stays on the log sink", provider);
return;
}
var sql = ReadEmbeddedScript(AuditStorage.ScriptResource(provider));
if (sql is null)
{
_logger.LogWarning("Audit schema script '{Resource}' not found in embedded resources",
AuditStorage.ScriptResource(provider));
return;
}
try
{
await using var conn = AuditStorage.CreateConnection(provider, connStr);
await conn.OpenAsync(cancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync(cancellationToken);
await ClusterColumn.EnsureAsync(conn, provider, AuditStorage.TableName, AuditStorage.ClusterIndexName, cancellationToken);
_logger.LogInformation("Audit table {Table} ensured ({Provider})",
AuditStorage.TableName, provider);
}
catch (Exception ex)
{
// A missing audit table must not stop the node from serving traffic: the writer
// route will fail per-event and the failure is visible in the logs.
_logger.LogError(ex, "Failed to ensure audit table {Table} ({Provider})",
AuditStorage.TableName, provider);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
private static string? ReadEmbeddedScript(string logicalName)
{
var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream(logicalName);
if (stream is null) return null;
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/AuditStorage.cs
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/src/redb.Tsak.Core/Audit/AuditStorage.cs
----
using System.Data.Common;
using Microsoft.Extensions.Configuration;
namespace redb.Tsak.Core.Audit;
///
/// The three storage backends Tsak can be configured with, plus "none" for the
/// in-memory / no-database mode where the audit trail falls back to the log sink.
///
public enum AuditProvider
{
None,
Postgres,
SqlServer,
Sqlite
}
///
/// The audit table and its statements. Everything provider-specific — connection string, ADO provider,
/// DDL script, casts, paging — comes from the provider's , so a statement is
/// written once and every provider gets its own spelling of it. The select and the retention sweep are
/// scoped to the node's cluster plus the entries written before cluster isolation
/// (, parameter @cluster).
///
public static class AuditStorage
{
/// Table name, shared by all three dialects.
public const string TableName = "tsak_audit_log";
/// Index on the cluster column, created by the schema initializer.
public const string ClusterIndexName = "ix_tsak_audit_cluster";
/// Endpoint the audit writer route consumes from.
public const string AuditEndpoint = "direct://tsak-audit";
/// Registry key under which the audit data source is published to the route context.
public const string DataSourceName = "tsak-audit-ds";
///
/// Resolves the configured provider from Tsak:Redb:Provider — the one place the setting is
/// parsed for Tsak's own tables and the Quartz job store.
///
public static AuditProvider ResolveProvider(IConfiguration configuration) =>
configuration["Tsak:Redb:Provider"]?.ToLowerInvariant() switch
{
"mssql" or "sqlserver" => AuditProvider.SqlServer,
"sqlite" => AuditProvider.Sqlite,
"postgres" or "postgresql" or "pg" or "npgsql" => AuditProvider.Postgres,
null or "" => AuditProvider.None,
// Unknown value: redb itself defaults to Postgres for anything it does not
// recognise, so stay consistent rather than silently disabling the audit.
_ => AuditProvider.Postgres
};
/// Connection string for the provider, read from the same names redb uses.
public static string? ResolveConnectionString(IConfiguration configuration, AuditProvider provider) =>
provider == AuditProvider.None
? null
: configuration.GetConnectionString(TsakSqlDialect.For(provider).ConnectionStringName);
/// Logical name of the embedded DDL script for the provider.
public static string ScriptResource(AuditProvider provider) =>
$"AuditSchema.{TsakSqlDialect.For(provider).ScriptSuffix}";
/// ADO.NET invariant name, used to register the factory for redb.Route.Sql.
public static string ProviderInvariantName(AuditProvider provider) =>
TsakSqlDialect.For(provider).InvariantName;
/// The backing .
public static DbProviderFactory ProviderFactory(AuditProvider provider) =>
TsakSqlDialect.For(provider).Factory;
/// Opens a raw connection — used by the schema initializers and the stores.
public static DbConnection CreateConnection(AuditProvider provider, string connectionString)
{
var conn = ProviderFactory(provider).CreateConnection()
?? throw new InvalidOperationException(
$"DbProviderFactory for {provider} returned null from CreateConnection().");
conn.ConnectionString = connectionString;
return conn;
}
///
/// INSERT statement. This is the one statement of the audit log that runs through the redb.Route.Sql
/// connector (the writer route), so its placeholders are written :#name, as that connector reads
/// them; @ there belongs to the database. Every other statement here and in the dead-letter store
/// runs on raw ADO.NET and keeps @name.
/// The writer route binds every value as it arrives in the audit.* headers — the event id, the
/// timestamp (ISO-8601 "o") and the payload as text — so each goes through the dialect's cast for
/// its column type: PostgreSQL refuses text for uuid / timestamptz / jsonb (42804)
/// without one.
///
public static string InsertSql(AuditProvider provider)
{
var d = TsakSqlDialect.For(provider);
return $"""
INSERT INTO {TableName}
(event_id, ts, action, controller_type, actor_principal, actor_key_id,
remote_ip, user_agent, http_method, request_path, target_resource,
status_code, duration_ms, exception_type, exception_message, payload, cluster_name)
VALUES
({d.Uuid(":#event_id")}, {d.TextTimestamp(":#ts")}, :#action, :#controller_type, :#actor_principal, :#actor_key_id,
:#remote_ip, :#user_agent, :#http_method, :#request_path, :#target_resource,
:#status_code, :#duration_ms, :#exception_type, :#exception_message, {d.Json(":#payload")}, :#cluster_name)
""";
}
///
/// Paged SELECT, newest first. Filters are all optional and expressed as
/// (@x IS NULL OR col = @x) so a single statement serves every combination.
///
public static string SelectSql(AuditProvider provider)
{
const string body = $"""
SELECT event_id, ts, action, controller_type, actor_principal, actor_key_id,
remote_ip, user_agent, http_method, request_path, target_resource,
status_code, duration_ms, exception_type, exception_message, payload
FROM {TableName}
WHERE {ClusterColumn.ScopeCondition}
AND (@actor IS NULL OR actor_key_id = @actor OR actor_principal = @actor)
AND (@action IS NULL OR action = @action)
AND (@target IS NULL OR target_resource = @target)
AND (@since IS NULL OR ts >= @since)
AND (@until IS NULL OR ts <= @until)
ORDER BY ts DESC
""";
return body + "\n" + TsakSqlDialect.For(provider).Paging("@limit", "@offset");
}
///
/// Retention sweep. Identical on all three providers: the cutoff is computed in C# and
/// passed as a parameter, so no server-side date arithmetic is involved.
///
public static string DeleteOlderThanSql() =>
$"DELETE FROM {TableName} WHERE ts < @cutoff AND {ClusterColumn.ScopeCondition}";
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/ClusterColumn.cs
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/src/redb.Tsak.Core/Audit/ClusterColumn.cs
----
using System.Data.Common;
namespace redb.Tsak.Core.Audit;
///
/// The cluster_name column of Tsak's flat tables (tsak_dlq, tsak_audit_log).
/// Several Tsak clusters may share one database, so every row carries the cluster that wrote it, and
/// every read, write and sweep of a node is scoped to its cluster plus the rows written before cluster
/// isolation (null). The DDL scripts create the column on a fresh database; on an existing one their
/// CREATE TABLE is a no-op, so adds it through the provider's dialect.
///
internal static class ClusterColumn
{
public const string Name = "cluster_name";
/// Width of the column where the provider has one (the DDL scripts declare the same).
public const int MaxLength = 200;
/// Scope condition of a node's statements; binds @cluster.
public const string ScopeCondition = "(cluster_name = @cluster OR cluster_name IS NULL)";
/// The parameter reads.
public static void BindScope(DbCommand cmd, string clusterName) =>
DbParameterBinding.AddString(cmd, "cluster", clusterName);
public static Task EnsureAsync(
DbConnection conn, AuditProvider provider, string table, string indexName, CancellationToken ct) =>
TsakSqlDialect.For(provider).EnsureNullableTextColumnAsync(conn, table, Name, MaxLength, indexName, ct);
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/DbParameterBinding.cs
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/src/redb.Tsak.Core/Audit/DbParameterBinding.cs
----
using System.Data;
using System.Data.Common;
namespace redb.Tsak.Core.Audit;
///
/// Binds parameters for the raw ADO.NET statements of the audit log and the dead-letter store with
/// an explicit on every one of them, null or not.
///
///
///
/// A parameter whose value is and whose type was never set is sent to
/// PostgreSQL as type unknown. The statements here spell every optional filter as
/// (@x IS NULL OR col = @x), and the parser fixes the type of the first @x it meets,
/// the one in IS NULL, before the comparison further right can tell it what the type is.
/// The two occurrences then disagree and PostgreSQL refuses the statement with
/// 42P08 could not determine data type of parameter $1. That is what the dashboard's Audit and
/// Dead-letter pages showed on Postgres for every request without a filter, which is every first
/// request. SQLite and SQL Server never noticed: neither infers parameter types from the statement.
///
///
/// Timestamps are bound as the type the column holds, which the provider's
/// decides: a UTC for
/// PostgreSQL (timestamptz) and SQL Server (datetimeoffset), where a text parameter has
/// no comparison operator against the column at all, and an ISO-8601 "o" string for SQLite,
/// whose column is TEXT and orders lexicographically, which is chronological for that format and is
/// how the rows were written.
///
///
internal static class DbParameterBinding
{
/// Binds a text parameter; null becomes a typed .
public static void AddString(DbCommand cmd, string name, string? value)
=> Add(cmd, name, DbType.String, value);
/// Binds a 32-bit integer.
public static void AddInt32(DbCommand cmd, string name, int value)
=> Add(cmd, name, DbType.Int32, value);
/// Binds a boolean.
public static void AddBoolean(DbCommand cmd, string name, bool value)
=> Add(cmd, name, DbType.Boolean, value);
///
/// Binds a timestamp in the form the provider's column expects. See the class remarks for why
/// the form differs per provider.
///
public static void AddTimestamp(DbCommand cmd, AuditProvider provider, string name, DateTimeOffset? value)
=> TsakSqlDialect.For(provider).BindTimestamp(cmd, name, value);
/// Binds a parameter of an explicit type; null becomes a typed .
public static void Add(DbCommand cmd, string name, DbType type, object? value)
{
var p = cmd.CreateParameter();
p.ParameterName = name;
p.DbType = type;
p.Value = value ?? DBNull.Value;
cmd.Parameters.Add(p);
}
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/Scripts/audit_postgres.sql
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/src/redb.Tsak.Core/Audit/Scripts/audit_postgres.sql
----
-- Tsak admin audit log — PostgreSQL
-- Auto-applied by AuditSchemaInitializer on startup when a redb provider is configured.
-- Idempotent: every statement is guarded by IF NOT EXISTS.
CREATE TABLE IF NOT EXISTS tsak_audit_log (
id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL,
ts TIMESTAMPTZ NOT NULL,
action VARCHAR(200) NOT NULL,
controller_type VARCHAR(200),
actor_principal VARCHAR(200),
actor_key_id VARCHAR(100),
remote_ip VARCHAR(64),
user_agent VARCHAR(500),
http_method VARCHAR(16),
request_path VARCHAR(500),
target_resource VARCHAR(300),
status_code INTEGER NOT NULL,
duration_ms DOUBLE PRECISION NOT NULL,
exception_type VARCHAR(200),
exception_message VARCHAR(2000),
payload JSONB,
cluster_name VARCHAR(200), -- NULL on entries written before cluster isolation
CONSTRAINT uq_tsak_audit_event_id UNIQUE (event_id)
);
-- ts DESC: every query and the retention sweep walk this index.
CREATE INDEX IF NOT EXISTS ix_tsak_audit_ts ON tsak_audit_log (ts DESC);
CREATE INDEX IF NOT EXISTS ix_tsak_audit_actor ON tsak_audit_log (actor_key_id);
CREATE INDEX IF NOT EXISTS ix_tsak_audit_action ON tsak_audit_log (action);
Path: redb-tsak/src/redb.Tsak.Core/Audit/Scripts/audit_sqlServer.sql
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/src/redb.Tsak.Core/Audit/Scripts/audit_sqlServer.sql
----
-- Tsak admin audit log — SQL Server / Azure SQL
-- Auto-applied by AuditSchemaInitializer on startup when a redb provider is configured.
-- Idempotent: each CREATE is guarded by an OBJECT_ID / sys.indexes check.
IF OBJECT_ID(N'[dbo].[tsak_audit_log]', N'U') IS NULL
CREATE TABLE [dbo].[tsak_audit_log] (
[id] bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
[event_id] uniqueidentifier NOT NULL,
[ts] datetimeoffset NOT NULL,
[action] nvarchar(200) NOT NULL,
[controller_type] nvarchar(200) NULL,
[actor_principal] nvarchar(200) NULL,
[actor_key_id] nvarchar(100) NULL,
[remote_ip] nvarchar(64) NULL,
[user_agent] nvarchar(500) NULL,
[http_method] nvarchar(16) NULL,
[request_path] nvarchar(500) NULL,
[target_resource] nvarchar(300) NULL,
[status_code] int NOT NULL,
[duration_ms] float NOT NULL,
[exception_type] nvarchar(200) NULL,
[exception_message] nvarchar(2000) NULL,
-- No native JSON type before SQL Server 2025; nvarchar(max) is the documented carrier
-- and JSON_VALUE / OPENJSON read it directly.
[payload] nvarchar(max) NULL,
[cluster_name] nvarchar(200) NULL,
CONSTRAINT [uq_tsak_audit_event_id] UNIQUE ([event_id])
);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_audit_ts' AND object_id = OBJECT_ID(N'[dbo].[tsak_audit_log]'))
CREATE INDEX [ix_tsak_audit_ts] ON [dbo].[tsak_audit_log] ([ts] DESC);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_audit_actor' AND object_id = OBJECT_ID(N'[dbo].[tsak_audit_log]'))
CREATE INDEX [ix_tsak_audit_actor] ON [dbo].[tsak_audit_log] ([actor_key_id]);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_audit_action' AND object_id = OBJECT_ID(N'[dbo].[tsak_audit_log]'))
CREATE INDEX [ix_tsak_audit_action] ON [dbo].[tsak_audit_log] ([action]);
Path: redb-tsak/src/redb.Tsak.Core/Audit/Scripts/audit_sqlite.sql
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/src/redb.Tsak.Core/Audit/Scripts/audit_sqlite.sql
----
-- Tsak admin audit log — SQLite
-- Auto-applied by AuditSchemaInitializer on startup when a redb provider is configured.
-- Idempotent: every statement is guarded by IF NOT EXISTS.
--
-- Timestamps are TEXT in ISO-8601 with offset ("2026-07-24T10:15:00.1234567+00:00").
-- This table is Tsak's own — not part of the redb schema — so it does NOT follow redb's
-- REAL Julian-day convention: lexicographic ordering equals chronological ordering, the
-- retention sweep compares strings, and the value is readable in any SQLite browser.
CREATE TABLE IF NOT EXISTS tsak_audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL,
ts TEXT NOT NULL,
action TEXT NOT NULL,
controller_type TEXT,
actor_principal TEXT,
actor_key_id TEXT,
remote_ip TEXT,
user_agent TEXT,
http_method TEXT,
request_path TEXT,
target_resource TEXT,
status_code INTEGER NOT NULL,
duration_ms REAL NOT NULL,
exception_type TEXT,
exception_message TEXT,
payload TEXT,
cluster_name TEXT,
CONSTRAINT uq_tsak_audit_event_id UNIQUE (event_id)
);
CREATE INDEX IF NOT EXISTS ix_tsak_audit_ts ON tsak_audit_log (ts DESC);
CREATE INDEX IF NOT EXISTS ix_tsak_audit_actor ON tsak_audit_log (actor_key_id);
CREATE INDEX IF NOT EXISTS ix_tsak_audit_action ON tsak_audit_log (action);
Path: redb-tsak/src/redb.Tsak.Core/Audit/TsakAuditRouteBuilder.cs
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/src/redb.Tsak.Core/Audit/TsakAuditRouteBuilder.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
namespace redb.Tsak.Core.Audit;
///
/// Audit writer: direct://tsak-audit → INSERT into tsak_audit_log.
/// Values arrive as audit.* headers, the sanitized argument JSON as the body.
///
/// The sink is an endpoint on purpose: pointing the same event stream at a file, a broker or
/// an HTTP collector is a configuration change, not a code change.
///
///
/// The endpoint names the statement instead of carrying it. The INSERT is a named query the writer
/// publishes on its own context, and its values travel as a map keyed by column, which the sql
/// connector binds to :#column by itself. Before, the INSERT text and seventeen param.*
/// options were the endpoint URI — printed whole in every start log and on the Endpoints page.
/// Whoever mounts the writer still publishes only the data source, as before.
///
///
public sealed class TsakAuditRouteBuilder : RouteBuilder
{
/// Route id, so the writer can be found in the Routes API and the dashboard.
public const string RouteIdName = "tsak-audit-writer";
/// Name the INSERT is published under as a named query of the writer's context.
public const string InsertQueryName = "tsak-audit-insert";
private readonly AuditProvider _provider;
private readonly string _clusterName;
/// Database provider of the audit table.
/// Cluster the written events belong to (Tsak:Cluster:ClusterName);
/// the default cluster name when omitted.
public TsakAuditRouteBuilder(AuditProvider provider, string? clusterName = null)
{
_provider = provider;
_clusterName = string.IsNullOrWhiteSpace(clusterName)
? Services.Storage.TsakStorageScope.DefaultClusterName
: clusterName;
}
protected override void Configure()
{
if (Context is not null)
PublishInsertQuery(Context, AuditStorage.InsertSql(_provider));
var clusterName = _clusterName;
From(AuditStorage.AuditEndpoint)
.RouteId(RouteIdName)
.Process(exchange => exchange.In.Body = ToColumnValues(exchange.In, clusterName))
.To(Sql.Execute(SqlNamedQueryRegistry.RefPrefix + InsertQueryName)
.DataSource(Constant(AuditStorage.DataSourceName)));
}
///
/// Publishes the INSERT on the context. A builder is configured again when its context is rebuilt, so the
/// same statement under the same name is already there and nothing is done; a different statement under
/// the name is two writers disagreeing about one table, and that is refused.
///
private static void PublishInsertQuery(IRouteContext context, string insertSql)
{
var namedQueries = context.GetService();
if (namedQueries is null)
{
namedQueries = new SqlNamedQueryRegistry();
context.AddService(typeof(ISqlNamedQueryRegistry), namedQueries);
}
if (!namedQueries.TryResolve(InsertQueryName, out var published))
{
namedQueries.Register(InsertQueryName, insertSql);
return;
}
if (!string.Equals(published, insertSql, StringComparison.Ordinal))
throw new InvalidOperationException(
$"Named query '{InsertQueryName}' is already published on this context with a different statement. "
+ "Two audit writers with different providers cannot share one context.");
}
///
/// The row to insert, keyed by column. An absent header is a present key with a null value, which the sql
/// connector binds as NULL — exactly what the per-column header expressions did.
///
internal static Dictionary ToColumnValues(IMessage message, string clusterName) => new()
{
["event_id"] = HeaderOrNull(message, AuditHeaders.EventId),
["ts"] = HeaderOrNull(message, AuditHeaders.Timestamp),
["action"] = HeaderOrNull(message, AuditHeaders.Action),
["controller_type"] = HeaderOrNull(message, AuditHeaders.ControllerType),
["actor_principal"] = HeaderOrNull(message, AuditHeaders.ActorPrincipal),
["actor_key_id"] = HeaderOrNull(message, AuditHeaders.ActorKeyId),
["remote_ip"] = HeaderOrNull(message, AuditHeaders.RemoteIp),
["user_agent"] = HeaderOrNull(message, AuditHeaders.UserAgent),
["http_method"] = HeaderOrNull(message, AuditHeaders.HttpMethod),
["request_path"] = HeaderOrNull(message, AuditHeaders.RequestPath),
["target_resource"] = HeaderOrNull(message, AuditHeaders.TargetResource),
["status_code"] = HeaderOrNull(message, AuditHeaders.StatusCode),
["duration_ms"] = HeaderOrNull(message, AuditHeaders.DurationMs),
["exception_type"] = HeaderOrNull(message, AuditHeaders.ExceptionType),
["exception_message"] = HeaderOrNull(message, AuditHeaders.ExceptionMessage),
["payload"] = message.Body,
["cluster_name"] = clusterName
};
private static object? HeaderOrNull(IMessage message, string name) =>
message.Headers.TryGetValue(name, out var value) ? value : null;
}
/// Header names carrying a single audit event from the sink to the writer route.
public static class AuditHeaders
{
public const string EventId = "audit.eventId";
public const string Timestamp = "audit.ts";
public const string Action = "audit.action";
public const string ControllerType = "audit.controllerType";
public const string ActorPrincipal = "audit.actorPrincipal";
public const string ActorKeyId = "audit.actorKeyId";
public const string RemoteIp = "audit.remoteIp";
public const string UserAgent = "audit.userAgent";
public const string HttpMethod = "audit.httpMethod";
public const string RequestPath = "audit.requestPath";
public const string TargetResource = "audit.targetResource";
public const string StatusCode = "audit.statusCode";
public const string DurationMs = "audit.durationMs";
public const string ExceptionType = "audit.exceptionType";
public const string ExceptionMessage = "audit.exceptionMessage";
}
Path: redb-tsak/src/redb.Tsak.Core/Audit/TsakSqlDialect.cs
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/src/redb.Tsak.Core/Audit/TsakSqlDialect.cs
----
using System.Data;
using System.Data.Common;
using System.Globalization;
using Microsoft.Extensions.Configuration;
namespace redb.Tsak.Core.Audit;
///
/// Everything that differs between PostgreSQL, SQL Server and SQLite for Tsak's own tables (the admin
/// audit log, the dead-letter store) and for the Quartz job-store wiring: connection string and ADO
/// provider, DDL scripts, the casts a provider needs to accept a text parameter, paging, how a timestamp
/// is bound and how a column is added to an existing table.
///
/// One sealed implementation per provider and every member abstract: a member added here does not
/// compile until all three providers implement it, so a provider cannot be left out. That is the failure
/// this type exists for — the audit insert once worked only where the column type happened to accept
/// text, and nobody noticed on PostgreSQL.
///
///
internal abstract class TsakSqlDialect
{
public static TsakSqlDialect Postgres { get; } = new PostgresDialect();
public static TsakSqlDialect SqlServer { get; } = new SqlServerDialect();
public static TsakSqlDialect Sqlite { get; } = new SqliteDialect();
/// Dialect of a configured database provider.
/// : no database, no dialect.
public static TsakSqlDialect For(AuditProvider provider) => provider switch
{
AuditProvider.Postgres => Postgres,
AuditProvider.SqlServer => SqlServer,
AuditProvider.Sqlite => Sqlite,
_ => throw new ArgumentOutOfRangeException(nameof(provider), provider,
"No database provider is configured, so there is no SQL dialect.")
};
///
/// Dialect of the Quartz job store: the configured provider, or PostgreSQL when
/// Tsak:Redb:Provider is not set — the Quartz wiring has always defaulted to it.
///
public static TsakSqlDialect ForQuartz(IConfiguration configuration)
{
var provider = AuditStorage.ResolveProvider(configuration);
return provider == AuditProvider.None ? Postgres : For(provider);
}
///
/// Registers the ADO providers the worker ships (Npgsql, Microsoft.Data.SqlClient,
/// Microsoft.Data.Sqlite) in under their invariant names, each only if the name
/// is not registered yet. A module in markup cannot register a factory, and the redb.Route.Sql connector finds its
/// provider by that name (ProviderName of a connection factory, provider= of an endpoint).
///
public static void RegisterProviderFactories()
{
foreach (var dialect in new[] { Postgres, SqlServer, Sqlite })
{
if (!DbProviderFactories.TryGetFactory(dialect.InvariantName, out _))
DbProviderFactories.RegisterFactory(dialect.InvariantName, dialect.Factory);
}
}
public abstract AuditProvider Provider { get; }
/// Name under ConnectionStrings — the same names redb uses.
public abstract string ConnectionStringName { get; }
/// Suffix of the embedded DDL scripts: AuditSchema.{suffix}, DlqSchema.{suffix}, QuartzSchema.{suffix}.
public abstract string ScriptSuffix { get; }
/// ADO.NET invariant name, used to register the factory for redb.Route.Sql.
public abstract string InvariantName { get; }
/// The backing .
public abstract DbProviderFactory Factory { get; }
/// Value of Quartz quartz.dataSource.default.provider.
public abstract string QuartzProvider { get; }
/// Value of Quartz quartz.jobStore.driverDelegateType.
public abstract string QuartzDriverDelegate { get; }
/// False where Quartz refuses a clustered AdoJobStore.
public abstract bool SupportsClusteredJobStore { get; }
/// A text parameter reference assigned to a uuid column.
public abstract string Uuid(string parameter);
/// A text (ISO-8601) parameter reference assigned to a timestamp-with-offset column.
public abstract string TextTimestamp(string parameter);
/// A text parameter reference assigned to a JSON column.
public abstract string Json(string parameter);
/// The paging clause that follows ORDER BY.
public abstract string Paging(string limitParameter, string offsetParameter);
/// Binds a timestamp in the form the provider's column holds (see ).
public abstract void BindTimestamp(DbCommand cmd, string name, DateTimeOffset? value);
///
/// Adds a nullable text column and an index on it to an existing table, idempotently. The DDL scripts
/// create the column on a fresh database, where this changes nothing.
///
public abstract Task EnsureNullableTextColumnAsync(
DbConnection conn, string table, string column, int maxLength, string indexName, CancellationToken ct);
///
/// Adds a nullable text column without a length limit and without an index to an existing table,
/// idempotently. The DDL scripts create the column on a fresh database, where this changes nothing.
///
public abstract Task EnsureNullableLongTextColumnAsync(
DbConnection conn, string table, string column, CancellationToken ct);
protected static async Task ExecuteAsync(DbConnection conn, string sql, CancellationToken ct)
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync(ct);
}
private sealed class PostgresDialect : TsakSqlDialect
{
public override AuditProvider Provider => AuditProvider.Postgres;
public override string ConnectionStringName => "Postgres";
public override string ScriptSuffix => "Postgres";
public override string InvariantName => "Npgsql";
public override DbProviderFactory Factory => Npgsql.NpgsqlFactory.Instance;
public override string QuartzProvider => "Npgsql";
public override string QuartzDriverDelegate => "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz";
public override bool SupportsClusteredJobStore => true;
// A plain string parameter cannot be assigned to uuid / timestamptz / jsonb (42804).
public override string Uuid(string parameter) => parameter + "::uuid";
public override string TextTimestamp(string parameter) => parameter + "::timestamptz";
public override string Json(string parameter) => parameter + "::jsonb";
public override string Paging(string limitParameter, string offsetParameter) =>
$"LIMIT {limitParameter} OFFSET {offsetParameter}";
public override void BindTimestamp(DbCommand cmd, string name, DateTimeOffset? value) =>
DbParameterBinding.Add(cmd, name, DbType.DateTimeOffset, value?.ToUniversalTime());
public override async Task EnsureNullableTextColumnAsync(
DbConnection conn, string table, string column, int maxLength, string indexName, CancellationToken ct)
{
await ExecuteAsync(conn, $"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} VARCHAR({maxLength})", ct);
await ExecuteAsync(conn, $"CREATE INDEX IF NOT EXISTS {indexName} ON {table} ({column})", ct);
}
public override Task EnsureNullableLongTextColumnAsync(
DbConnection conn, string table, string column, CancellationToken ct) =>
ExecuteAsync(conn, $"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} TEXT", ct);
}
private sealed class SqlServerDialect : TsakSqlDialect
{
public override AuditProvider Provider => AuditProvider.SqlServer;
public override string ConnectionStringName => "MSSql";
public override string ScriptSuffix => "SqlServer";
public override string InvariantName => "Microsoft.Data.SqlClient";
public override DbProviderFactory Factory => Microsoft.Data.SqlClient.SqlClientFactory.Instance;
public override string QuartzProvider => "SqlServer";
public override string QuartzDriverDelegate => "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
public override bool SupportsClusteredJobStore => true;
// Text converts implicitly to uniqueidentifier / datetimeoffset / nvarchar(max) JSON.
public override string Uuid(string parameter) => parameter;
public override string TextTimestamp(string parameter) => parameter;
public override string Json(string parameter) => parameter;
public override string Paging(string limitParameter, string offsetParameter) =>
$"OFFSET {offsetParameter} ROWS FETCH NEXT {limitParameter} ROWS ONLY";
public override void BindTimestamp(DbCommand cmd, string name, DateTimeOffset? value) =>
DbParameterBinding.Add(cmd, name, DbType.DateTimeOffset, value?.ToUniversalTime());
public override async Task EnsureNullableTextColumnAsync(
DbConnection conn, string table, string column, int maxLength, string indexName, CancellationToken ct)
{
await ExecuteAsync(conn,
$"IF COL_LENGTH(N'dbo.{table}', N'{column}') IS NULL "
+ $"ALTER TABLE [dbo].[{table}] ADD [{column}] nvarchar({maxLength}) NULL;", ct);
// A batch of its own: SQL Server compiles a batch as a whole, so an index on a column
// added in the same batch does not compile.
await ExecuteAsync(conn,
$"IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'{indexName}' AND object_id = OBJECT_ID(N'[dbo].[{table}]')) "
+ $"CREATE INDEX [{indexName}] ON [dbo].[{table}] ([{column}]);", ct);
}
public override Task EnsureNullableLongTextColumnAsync(
DbConnection conn, string table, string column, CancellationToken ct) =>
ExecuteAsync(conn,
$"IF COL_LENGTH(N'dbo.{table}', N'{column}') IS NULL "
+ $"ALTER TABLE [dbo].[{table}] ADD [{column}] nvarchar(max) NULL;", ct);
}
private sealed class SqliteDialect : TsakSqlDialect
{
public override AuditProvider Provider => AuditProvider.Sqlite;
public override string ConnectionStringName => "Sqlite";
public override string ScriptSuffix => "Sqlite";
public override string InvariantName => "Microsoft.Data.Sqlite";
public override DbProviderFactory Factory => Microsoft.Data.Sqlite.SqliteFactory.Instance;
public override string QuartzProvider => "SQLite-Microsoft";
public override string QuartzDriverDelegate => "Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz";
// Quartz hard-refuses SQLite + clustered: the QRTZ_LOCKS semaphore needs row locks SQLite lacks.
public override bool SupportsClusteredJobStore => false;
// Every column of Tsak's SQLite tables is TEXT-compatible.
public override string Uuid(string parameter) => parameter;
public override string TextTimestamp(string parameter) => parameter;
public override string Json(string parameter) => parameter;
public override string Paging(string limitParameter, string offsetParameter) =>
$"LIMIT {limitParameter} OFFSET {offsetParameter}";
// The timestamp columns are TEXT holding the ISO-8601 "o" form and compare lexicographically,
// which is chronological for that format — the parameter is spelled the way the rows were written.
public override void BindTimestamp(DbCommand cmd, string name, DateTimeOffset? value) =>
DbParameterBinding.Add(cmd, name, DbType.String,
value?.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture));
public override async Task EnsureNullableTextColumnAsync(
DbConnection conn, string table, string column, int maxLength, string indexName, CancellationToken ct)
{
// SQLite has no ADD COLUMN IF NOT EXISTS; TEXT has no length.
if (!await ColumnExistsAsync(conn, table, column, ct))
await ExecuteAsync(conn, $"ALTER TABLE {table} ADD COLUMN {column} TEXT", ct);
await ExecuteAsync(conn, $"CREATE INDEX IF NOT EXISTS {indexName} ON {table} ({column})", ct);
}
public override async Task EnsureNullableLongTextColumnAsync(
DbConnection conn, string table, string column, CancellationToken ct)
{
if (!await ColumnExistsAsync(conn, table, column, ct))
await ExecuteAsync(conn, $"ALTER TABLE {table} ADD COLUMN {column} TEXT", ct);
}
private static async Task ColumnExistsAsync(DbConnection conn, string table, string column, CancellationToken ct)
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{column}'";
return Convert.ToInt64(await cmd.ExecuteScalarAsync(ct)) > 0;
}
}
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/IContextCustomizer.cs
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/src/redb.Tsak.Core/Contracts/IContextCustomizer.cs
----
using redb.Route.Abstractions;
namespace redb.Tsak.Core.Contracts;
///
/// Customizes a newly created RouteContext (add policies, services, etc.).
/// Registered via DI; called by TsakContextManager after context creation.
///
public interface IContextCustomizer
{
/// Called when a new context is being initialized.
Task CustomizeAsync(IRouteContext context, IServiceProvider serviceProvider, string contextName);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/IEmbeddedConfigModule.cs
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/src/redb.Tsak.Core/Contracts/IEmbeddedConfigModule.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// A module that carries its per-module configuration ({Name}.config.json) embedded in the
/// .tpkg it was discovered from. The coordinator reads for the
/// module's ContextName (layer-4 identity) and merges it into the context configuration —
/// matching on this contract, not on a concrete module type, so every packaged module kind
/// (static-method, XML routes, future ones) gets the same treatment.
///
public interface IEmbeddedConfigModule
{
/// Raw JSON of the embedded {Name}.config.json; null when the package carries none.
string? EmbeddedConfigJson { get; }
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/IHealthContributor.cs
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/src/redb.Tsak.Core/Contracts/IHealthContributor.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Contributes additional health checks to .
/// Registered via DI; each contributor adds entries to the evaluation result.
///
public interface IHealthContributor
{
/// Adds health check entries to the evaluation result.
void Contribute(Monitoring.HealthEvaluation result);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/IStaticModuleProvider.cs
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/src/redb.Tsak.Core/Contracts/IStaticModuleProvider.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Provider of compile-time (static) modules registered via ProjectReference.
/// Equivalent of lt.tsak IStaticModuleProvider.
///
public interface IStaticModuleProvider
{
/// Provider name for identification.
string ProviderName { get; }
/// Loading priority (higher = loaded first).
int Priority { get; }
/// Returns modules provided by this provider.
IEnumerable GetStaticModules();
/// Whether this provider can be initialized.
bool CanInitialize();
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ISystemContextPlugin.cs
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/src/redb.Tsak.Core/Contracts/ISystemContextPlugin.cs
----
using System.Reflection;
using redb.Route.Abstractions;
namespace redb.Tsak.Core.Contracts;
///
/// Plugin for enriching the _system REST API context with additional controllers and services.
/// Registered via DI by Pro modules; called by .
///
public interface ISystemContextPlugin
{
/// Register additional services into the system context.
void ConfigureServices(IRouteContext context, IServiceProvider rootServiceProvider);
/// Return assemblies containing additional controllers to register.
IEnumerable GetControllerAssemblies();
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakClusterDirectory.cs
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/src/redb.Tsak.Core/Contracts/ITsakClusterDirectory.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// How many Tsak clusters share the database. Implemented by redb.Tsak.Core.Pro from the cluster
/// roots and registered with cluster mode; absent otherwise. Core stores use it to decide whether a
/// record written before cluster isolation — it carries no cluster — can be attributed to this node's
/// cluster: only while the database holds a single one.
///
public interface ITsakClusterDirectory
{
/// Number of Tsak clusters (cluster roots) in the database.
Task CountClustersAsync(CancellationToken ct = default);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakContextManager.cs
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/src/redb.Tsak.Core/Contracts/ITsakContextManager.cs
----
using redb.Route.Abstractions;
using redb.Tsak.Contracts;
namespace redb.Tsak.Core.Contracts;
///
/// Manages lifecycle of route contexts: create, start, stop, remove.
/// Supports named (config-driven) and anonymous (auto-created) contexts.
/// Equivalent of lt.tsak IRouteContextManager.
///
public interface ITsakContextManager
{
///
/// Creates a named context with the given configuration.
///
/// Unique context name.
/// DI service provider for the context.
/// Context-specific configuration values.
/// Created route context.
IRouteContext CreateContext(string contextName, IServiceProvider serviceProvider, IDictionary configuration);
/// Gets a context by name.
IRouteContext? GetContext(string contextName);
/// Returns all contexts as (name, context) pairs.
IReadOnlyList<(string Name, IRouteContext Context)> GetAllContexts();
///
/// Named redb instances as the manager actually registered them, context by context. The context registry
/// itself cannot be enumerated, and an instance whose creation failed is not listed — the storage page
/// offers to query what it lists.
///
IReadOnlyList GetNamedRedbInstances();
/// Starts a context. When ignoreAutoStart is true, skips the autoStart check (for manual API/CLI calls).
Task StartContextAsync(string contextName, bool ignoreAutoStart = false);
/// Stops a context with graceful drain. Returns drain diagnostics.
/// Context name.
/// If true, marks context to not auto-start on next boot.
/// Cancellation token for graceful shutdown timeout.
Task StopContextAsync(string contextName, bool setAutoStartFalse = true, CancellationToken ct = default);
/// Restarts a context (drain-aware stop + start). Returns drain diagnostics.
Task RestartContextAsync(string contextName, CancellationToken ct = default);
/// Removes a context (stop + dispose + unregister).
/// Context name.
/// When true, preserves autoStart state in store (for hot-reload). When false, cleans up everything.
Task RemoveContextAsync(string contextName, bool preserveState = false);
/// Returns whether the context should auto-start based on config.
bool ShouldAutoStart(string contextName);
/// Async version of — avoids sync-over-async for Redb-backed store.
Task ShouldAutoStartAsync(string contextName);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakCoordinator.cs
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/src/redb.Tsak.Core/Contracts/ITsakCoordinator.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Orchestrates module-to-context mapping.
/// Subscribes to registry events and creates/updates/removes contexts accordingly.
/// Equivalent of lt.tsak ModuleContextCoordinator.
///
public interface ITsakCoordinator
{
///
/// Initializes the coordinator and subscribes to registry events.
/// Must be called before any modules are registered.
///
/// Module registry to subscribe to.
void Initialize(ITsakModuleRegistry registry);
///
/// Handles a batch of newly added modules (e.g. from static providers).
/// Creates contexts and initializes modules according to the module mapping config.
///
/// Modules to process.
///
/// The modules that did not come up. A module's own failure never throws out of the coordinator
/// (a bad module must not crash the node); callers that must react read the report.
///
Task ProcessBatchAsync(IReadOnlyList modules);
///
/// Handles a single newly added module.
///
/// Module to process.
///
/// The modules that did not come up — for a named context, any module of that context. A module's
/// own failure never throws out of the coordinator; callers that must react read the report.
///
Task ProcessModuleAddedAsync(ITsakModule module);
///
/// Handles module removal — stops and cleans up the associated context.
///
/// Name of the removed module.
Task ProcessModuleRemovedAsync(string moduleName);
///
/// Handles module update — restarts the associated context with the new version.
///
/// Updated module.
Task ProcessModuleUpdatedAsync(ITsakModule module);
///
/// Waits until every enqueued registry-event has been processed by the background consumer.
/// Lets startup (and tests) wait for topology changes to settle instead of racing the handlers.
///
Task WaitForIdleAsync(CancellationToken ct = default);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakLifecycleHook.cs
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/src/redb.Tsak.Core/Contracts/ITsakLifecycleHook.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Generic lifecycle hook for Tsak startup/shutdown.
/// Registered via DI, called by TsakHostedService in order.
///
public interface ITsakLifecycleHook
{
/// Execution order: lower starts earlier and stops later (shutdown runs the hooks in reverse order).
int Order => 0;
/// Called during Tsak startup, before module discovery.
Task OnStartingAsync(CancellationToken ct);
/// Called during Tsak shutdown, before the contexts are stopped and drained.
Task OnStoppingAsync(CancellationToken ct);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakModule.cs
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/src/redb.Tsak.Core/Contracts/ITsakModule.cs
----
using redb.Route.Abstractions;
namespace redb.Tsak.Core.Contracts;
///
/// Status of a route module in its lifecycle.
///
public enum TsakModuleStatus
{
/// Module discovered but not yet loaded.
Discovered,
/// Module loaded into memory.
Loaded,
/// Module initialized (routes configured).
Initialized,
/// Module running (context started).
Running,
/// Module stopped.
Stopped,
/// Module failed to load or initialize.
Faulted
}
///
/// Contract for a route module that can be discovered, loaded, and initialized in a context.
/// Equivalent of lt.tsak IRouteModule, adapted for redb.Route.
///
public interface ITsakModule
{
/// Unique module name (e.g. "DAL.GPS", "Api.Mobile").
string ModuleName { get; }
/// Module version string.
string Version { get; }
/// Human-readable description.
string Description { get; }
/// Names of modules this module depends on.
IReadOnlyList Dependencies { get; }
/// Whether the module can be initialized (all deps met, no errors).
bool CanInitialize { get; }
/// Current lifecycle status.
TsakModuleStatus Status { get; }
///
/// Directory where the module's DLL was loaded from.
/// Used to locate module config files (context.json, {Module}.config.json).
/// Null for static/in-process modules.
///
string? SourceDirectory { get; }
///
/// Initializes routes in the given context, synchronously. The coordinator reaches it through the
/// default .
///
/// Route context to configure.
/// The configured context.
IRouteContext Initialize(IRouteContext context);
///
/// Initializes routes in the given context. This is the entry the coordinator awaits, and the context
/// starts only after it completes. A module whose setup awaits (schema sync, reference data) overrides
/// it; the default runs , so existing modules work unchanged, without a rebuild.
///
/// Interface mapping is fixed by the class that declares . A module that inherits
/// the interface from a base class and adds InitializeAsync must list
/// again (or the base class must declare a virtual InitializeAsync to override); otherwise this
/// default runs and its is called instead.
///
///
/// Route context to configure.
/// The configured context.
Task InitializeAsync(IRouteContext context) => Task.FromResult(Initialize(context));
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakModuleRegistry.cs
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/src/redb.Tsak.Core/Contracts/ITsakModuleRegistry.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Registry managing discovery, registration, and lifecycle of route modules.
/// Thread-safe. Fires events for coordinator subscription.
/// Equivalent of lt.tsak IRouteModuleRegistry.
///
public interface ITsakModuleRegistry
{
///
/// Registers modules from static (compile-time) providers.
/// Fires once with all registered modules.
///
/// Static module providers.
/// Number of modules registered.
Task RegisterStaticProvidersAsync(IEnumerable providers);
///
/// Discovers modules in assemblies at the specified paths.
/// Scans for ITsakModule implementations and InitRoute.main() conventions.
///
/// Directory paths to scan for DLL files.
/// Number of modules discovered.
Task DiscoverModulesAsync(IEnumerable assemblyPaths);
/// Registers a single module manually (awaits the store — no sync-over-async).
Task RegisterModuleAsync(ITsakModule module);
/// Unregisters a module by name (awaits the store).
/// True if module was found and removed.
Task UnregisterModuleAsync(string moduleName);
/// Unregisters a module without firing events (used during package reload to preserve state).
/// Touches no store, so it stays synchronous.
bool UnregisterModuleSilent(string moduleName);
/// Replaces a module in the registry without firing events (used by hot-swap; awaits the store).
Task ReplaceModuleSilentAsync(ITsakModule module);
/// Returns all registered modules.
IReadOnlyList GetAllModules();
/// Gets a module by name.
ITsakModule? GetModule(string moduleName);
/// Returns modules with the specified status.
IReadOnlyList GetModulesByStatus(TsakModuleStatus status);
/// Fired when a single module is added.
event EventHandler ModuleAdded;
/// Fired when a single module is removed.
event EventHandler ModuleRemoved;
/// Fired when a module is updated (new version detected).
event EventHandler ModuleUpdated;
/// Fired after a batch of modules is added (e.g. from static providers).
event EventHandler> ModulesBatchAdded;
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakModuleStore.cs
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/src/redb.Tsak.Core/Contracts/ITsakModuleStore.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Module metadata stored in module store.
///
public record TsakModuleRecord
{
public required string ModuleName { get; init; }
public required string Version { get; init; }
public string Description { get; init; } = string.Empty;
public IReadOnlyList Dependencies { get; init; } = [];
public TsakModuleStatus Status { get; init; } = TsakModuleStatus.Discovered;
public string? AssemblyPath { get; init; }
public DateTimeOffset RegisteredAt { get; init; } = DateTimeOffset.UtcNow;
public DateTimeOffset? LastUpdatedAt { get; init; }
}
///
/// Persistent store for module metadata.
/// InMemory implementation for Standalone mode, redb-backed for Single/Cluster modes.
///
public interface ITsakModuleStore
{
Task> GetAllAsync();
Task GetAsync(string moduleName);
Task SaveAsync(TsakModuleRecord record);
Task RemoveAsync(string moduleName);
Task SaveBatchAsync(IEnumerable records);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakSaveInterceptors.cs
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/src/redb.Tsak.Core/Contracts/ITsakSaveInterceptors.cs
----
using redb.Core.Interception;
namespace redb.Tsak.Core.Contracts;
///
/// Save interceptors a module subscribes for the life of its route context. The host keeps the redb service and its
/// DI container to itself; a module reaches this service through its context instead:
///
/// public override async Task<IRouteContext> InitializeAsync(IRouteContext context)
/// {
/// context.GetService<ITsakSaveInterceptors>()?.Add(new NotifyFrontInterceptor());
/// ...
/// }
///
/// The context holds the subscription: when Tsak removes the context (the module is unloaded, or reloaded and its
/// context created anew) every interceptor it added is removed before the module's AssemblyLoadContext unloads, so
/// the module needs no cleanup of its own. Stopping the context keeps them, as it keeps the routes.
///
/// What an interceptor added here sees: every save and delete of the worker made through the host's redb service and
/// the named redb instances of the contexts, including those of other modules. An exception thrown from
/// or therefore
/// cancels any save or delete of the worker, not only the module's own. The semantics are those of
/// : SavedAsync after the commit, inside the transaction within
/// ExecuteAtomicAsync.
///
///
/// The service is in the context only when the host runs redb (Tsak:Redb:Provider is set); without it
/// GetService returns null.
///
///
public interface ITsakSaveInterceptors
{
///
/// Subscribes until the context is removed. Dispose the result to remove it
/// earlier; disposing twice is safe. Fails once the context has been removed.
///
IDisposable Add(IRedbSaveInterceptor interceptor);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ITsakStateStore.cs
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/src/redb.Tsak.Core/Contracts/ITsakStateStore.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// Persistent key-value state store for context and coordinator state.
/// Used to persist autoStart flags, context config, last-known state on restart.
/// InMemory for Standalone, redb-backed for Single/Cluster.
///
/// CONTRACT: keys are compared ORDINALLY, case-sensitive — Get/Set/Remove
/// and alike, on every implementation. The rule lives here on the
/// interface (owner decision 2026-09-02): before that the redb store was ordinal while the
/// in-memory default folded case, so code developed standalone silently changed behavior when
/// deployed clustered (review 2026-09-02, С7). Very long keys may be stored in a normalized
/// deterministic form; round-tripping through returns the stored
/// form.
///
///
public interface ITsakStateStore
{
Task GetAsync(string key);
Task SetAsync(string key, string value);
Task RemoveAsync(string key);
Task> GetByPrefixAsync(string prefix);
}
Path: redb-tsak/src/redb.Tsak.Core/Contracts/ModuleActivationReport.cs
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/src/redb.Tsak.Core/Contracts/ModuleActivationReport.cs
----
namespace redb.Tsak.Core.Contracts;
///
/// What the coordinator could not bring up while activating modules in their contexts.
///
/// The coordinator deliberately swallows (and logs) a module's Initialize exception and a
/// context start exception, so that one bad module can never crash the node. Callers that must
/// react to a module that did not come up — a hot swap, a package reload, a cluster assignment —
/// read this report instead of waiting for an exception that never arrives.
///
///
/// default means "nothing failed", which is also what an unconfigured test double returns.
/// Endpoint start failures that redb.Route isolates inside an otherwise started context are NOT
/// reported: Tsak does not see them.
///
///
public readonly struct ModuleActivationReport
{
private readonly IReadOnlyList? _failures;
public ModuleActivationReport(IReadOnlyList failures) => _failures = failures;
/// A report with no failures.
public static ModuleActivationReport Success => default;
public IReadOnlyList Failures => _failures ?? Array.Empty();
public bool Succeeded => Failures.Count == 0;
/// The first failure recorded for , or null when that module came up.
public ModuleActivationFailure? FailureFor(string moduleName)
{
foreach (var failure in Failures)
{
if (string.Equals(failure.ModuleName, moduleName, StringComparison.OrdinalIgnoreCase))
return failure;
}
return null;
}
}
/// A module that did not come up: its Initialize threw, or its context failed to start.
public sealed record ModuleActivationFailure(string ModuleName, string ContextName, Exception Exception);
Path: redb-tsak/src/redb.Tsak.Core/Controllers/AuditController.cs
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/src/redb.Tsak.Core/Controllers/AuditController.cs
----
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
using redb.Tsak.Contracts;
using redb.Tsak.Core.Audit;
using redb.Tsak.Core.Security;
namespace redb.Tsak.Core.Controllers;
///
/// Query the persistent admin audit trail.
/// GET /api/audit — filtered, paged, newest-first.
///
/// Reading the audit is an admin operation: the trail records who did what, which is
/// exactly the information a lower-privilege caller must not be able to enumerate.
///
///
[Route("/api/audit")]
[RequiresRole(TsakRoles.Admin)]
public class AuditController : RedbController
{
///
/// Returns audit entries matching the optional filters.
///
/// Match on API key id or principal name.
/// Logical action name (e.g. RemoveContext).
/// Target resource identifier.
/// Lower time bound (inclusive), ISO-8601.
/// Upper time bound (inclusive), ISO-8601.
/// Page size, 1..1000 (default 100).
/// Rows to skip (default 0).
[HttpGet("")]
public async Task