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 Query( [FromQuery("actor")] string? actor, [FromQuery("action")] string? action, [FromQuery("target")] string? target, [FromQuery("since")] string? since, [FromQuery("until")] string? until, [FromQuery("limit")] int? limit, [FromQuery("offset")] int? offset) { var svc = Context.GetService(); if (svc is null) return new AuditQueryResult { Available = false, Error = "AuditQueryService not available", Entries = [] }; DateTimeOffset? sinceTs = DateTimeOffset.TryParse(since, out var s) ? s : null; DateTimeOffset? untilTs = DateTimeOffset.TryParse(until, out var u) ? u : null; return await svc.QueryAsync( actor: actor, action: action, target: target, since: sinceTs, until: untilTs, limit: limit ?? 100, offset: offset ?? 0); } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/AuthController.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/AuthController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// API key management: create, list, revoke keys. /// POST /api/auth/keys — create new key (returns raw key once) /// GET /api/auth/keys — list all keys (no raw keys) /// DELETE /api/auth/keys/{id} — revoke a key /// [Route("/api/auth")] [RequiresRole(TsakRoles.Admin)] // issuing and revoking keys is privilege escalation public class AuthController : RedbController { private ApiKeyService GetKeyService() => Context.GetService() ?? throw new InvalidOperationException("ApiKeyService not registered in context"); [HttpPost("/keys")] [AuditAdminAction(ActionName = "CreateApiKey")] public async Task CreateKey([FromBody] CreateKeyRequest? request) { if (request is null || string.IsNullOrWhiteSpace(request.Name)) { ApiResponse.BadRequest(Exchange, "Name is required."); Exchange.Stop(); return null!; } var svc = GetKeyService(); var (rawKey, record) = await svc.CreateKeyAsync( request.Name, request.UserId, request.Roles, request.ExpiresAt); return new ApiKeyCreatedResponse { Id = record.Id, Key = rawKey, Name = record.Name, Roles = record.Roles ?? "", UserId = record.UserId, CreatedAt = record.CreatedAt, ExpiresAt = record.ExpiresAt, Message = "Store this key securely. It will not be shown again." }; } [HttpGet("/keys")] public async Task ListKeys() { var svc = GetKeyService(); var keys = await svc.ListKeysAsync(); return keys.Select(k => new ApiKeyInfo { Id = k.Id, Name = k.Name, Roles = k.Roles ?? "", UserId = k.UserId, CreatedAt = k.CreatedAt, ExpiresAt = k.ExpiresAt, Revoked = k.Revoked, IsValid = k.IsValid }).ToList(); } [HttpDelete("/keys/{id}")] [AuditAdminAction(ActionName = "RevokeApiKey", TargetParam = "id")] public async Task RevokeKey([FromRoute("id")] string id) { var svc = GetKeyService(); var revoked = await svc.RevokeKeyAsync(id); if (!revoked) { ApiResponse.NotFound(Exchange, $"Key '{id}' not found."); Exchange.Stop(); return null; } return new ApiKeyRevokedResponse { Id = id, Revoked = true }; } } public sealed record CreateKeyRequest { public string Name { get; init; } = ""; public string? UserId { get; init; } public string? Roles { get; init; } public DateTimeOffset? ExpiresAt { get; init; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/ContextsController.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/ContextsController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Security; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Controllers; /// /// Context lifecycle management: list, start, stop, restart, remove. /// Route-level operations are in . /// [Route("/api/contexts")] public class ContextsController : RedbController { private ITsakContextManager GetManager() => Context.GetService() ?? throw new InvalidOperationException("ITsakContextManager not registered in context"); private ContextInfoCollector GetCollector() => Context.GetService() ?? new ContextInfoCollector(GetManager()); [HttpGet("")] public object ListContexts() { var mgr = GetManager(); return mgr.GetAllContexts().Select(c => { var routes = (c.Context as RouteContext)?.Routes; return new ContextSummary { Name = c.Name, Status = c.Context.IsStarted ? "Running" : "Stopped", EndpointCount = c.Context.GetEndpoints()?.Count ?? 0, IsAnonymous = c.Name.Contains("_dyn_", StringComparison.Ordinal), RouteCount = routes?.Count ?? 0 }; }).ToList(); } [HttpGet("/{name}")] public object? GetContext([FromRoute("name")] string name) { var collector = GetCollector(); var detail = collector.Collect(name); if (detail is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } return detail; } [HttpPost("/{name}/start")] [AuditAdminAction(ActionName = "StartContext", TargetParam = "name")] public async Task StartContext([FromRoute("name")] string name) { var mgr = GetManager(); if (mgr.GetContext(name) is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } await mgr.StartContextAsync(name, ignoreAutoStart: true); return new ContextActionResponse { Name = name, Status = "Running" }; } [HttpPost("/{name}/stop")] [AuditAdminAction(ActionName = "StopContext", TargetParam = "name")] public async Task StopContext( [FromRoute("name")] string name, [FromQuery("timeoutSeconds")] int? timeoutSeconds = null) { var mgr = GetManager(); if (mgr.GetContext(name) is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } using var cts = timeoutSeconds.HasValue ? new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds.Value)) : null; var result = await mgr.StopContextAsync(name, ct: cts?.Token ?? default); return result; } [HttpPost("/{name}/restart")] [AuditAdminAction(ActionName = "RestartContext", TargetParam = "name")] public async Task RestartContext( [FromRoute("name")] string name, [FromQuery("timeoutSeconds")] int? timeoutSeconds = null) { var mgr = GetManager(); if (mgr.GetContext(name) is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } using var cts = timeoutSeconds.HasValue ? new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds.Value)) : null; var result = await mgr.RestartContextAsync(name, ct: cts?.Token ?? default); return result; } [HttpDelete("/{name}")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "RemoveContext", TargetParam = "name")] public async Task RemoveContext([FromRoute("name")] string name) { var mgr = GetManager(); if (mgr.GetContext(name) is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } // Protect the _system context if (string.Equals(name, "_system", StringComparison.OrdinalIgnoreCase)) { ApiResponse.BadRequest(Exchange, "Cannot remove the _system context."); Exchange.Stop(); return null; } await mgr.RemoveContextAsync(name); return new ContextActionResponse { Name = name, Removed = true }; } [HttpPost("/{name}/reset-route-states")] [AuditAdminAction(ActionName = "ResetRouteStates", TargetParam = "name")] public async Task ResetRouteStates([FromRoute("name")] string name) { var mgr = GetManager(); if (mgr.GetContext(name) is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } var stateStore = Context.GetService(); if (stateStore is not null) { var suspendedPrefix = RoutesController.RouteSuspendedKeyPrefix + name + ":"; var startedPrefix = RoutesController.RouteStartedKeyPrefix + name + ":"; var suspended = await stateStore.GetByPrefixAsync(suspendedPrefix); var started = await stateStore.GetByPrefixAsync(startedPrefix); foreach (var key in suspended.Keys) await stateStore.RemoveAsync(key); foreach (var key in started.Keys) await stateStore.RemoveAsync(key); } var result = await mgr.RestartContextAsync(name); return result; } [HttpGet("/{name}/endpoints")] public object? GetEndpoints([FromRoute("name")] string name) { var detail = GetCollector().Collect(name); if (detail is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } return detail.Endpoints; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/DashboardController.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/DashboardController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Controllers; /// /// Aggregated dashboard snapshot endpoint for the web UI. /// Combines system metrics, context summaries, top routes, and watchdog alerts. /// [Route("/api/dashboard")] public class DashboardController : RedbController { private ITsakContextManager GetManager() => Context.GetService() ?? throw new InvalidOperationException("ITsakContextManager not registered"); private ContextInfoCollector GetCollector() => Context.GetService() ?? new ContextInfoCollector(GetManager()); [HttpGet("")] public object GetDashboard() { var mgr = GetManager(); var collector = GetCollector(); var metricsService = Context.GetService(); var watchdog = Context.GetService(); var contexts = mgr.GetAllContexts(); var allRouteMetrics = collector.CollectAllRouteMetrics(); // System metrics SystemMetricsSnapshot? sysMetrics = null; var latest = metricsService?.GetLatest(); if (latest is not null) sysMetrics = DiagnosticService.SystemMetrics(latest, Context.GetService()); // total inflight var totalInflight = 0; foreach (var (_, ctx) in contexts) { if (ctx is RouteContext routeCtx) totalInflight += routeCtx.InflightRepository.Count; } return new DashboardSnapshot { TotalContexts = contexts.Count, RunningContexts = contexts.Count(c => c.Context.IsStarted), TotalInflight = totalInflight, BusiestRoutes = allRouteMetrics .OrderByDescending(r => r.ThroughputPerSecond) .Take(5) .ToList(), ErrorProneRoutes = allRouteMetrics .Where(r => r.Errors > 0) .OrderByDescending(r => r.Errors) .Take(5) .ToList(), // Deliberately a separate list, not part of ErrorProneRoutes: a route shedding at // its concurrency ceiling with zero errors is healthy but under-provisioned. SheddingRoutes = allRouteMetrics .Where(r => r.Rejected > 0) .OrderByDescending(r => r.Rejected) .Take(5) .ToList(), // Refused requests are the caller's fault: neither errors of the route nor load it sheds. RefusingRoutes = allRouteMetrics .Where(r => r.Refused > 0) .OrderByDescending(r => r.Refused) .Take(5) .ToList(), ActiveAlerts = watchdog?.GetState()?.ActiveAlerts ?? [], SystemMetrics = sysMetrics }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/DiagnosticsController.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/DiagnosticsController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.Core; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Controllers; /// /// Diagnostic endpoints: system dump and per-route diagnostics. /// [Route("/api/diagnostics")] [RequiresRole(TsakRoles.Operator)] // dumps expose thread state and internals — not a read-only concern public class DiagnosticsController : RedbController { private ITsakContextManager GetManager() => Context.GetService() ?? throw new InvalidOperationException("ITsakContextManager not registered"); /// /// GET /api/diagnostics/dump — full system diagnostic snapshot. /// [HttpGet("/dump")] public object GetSystemDump() { var mgr = GetManager(); var diagService = new DiagnosticService(mgr); return diagService.CollectSystemDump( metricsService: Context.GetService(), watchdog: Context.GetService(), auditService: Context.GetService(), moduleContexts: Context.GetService()); } /// /// GET /api/diagnostics/{contextName}/{routeId} — per-route diagnostic dump. /// [HttpGet("/{contextName}/{routeId}")] public object? GetRouteDiagnostics( [FromRoute("contextName")] string contextName, [FromRoute("routeId")] string routeId) { var mgr = GetManager(); var diagService = new DiagnosticService(mgr); var auditService = Context.GetService(); var dump = diagService.CollectRouteDump(contextName, routeId, auditService); if (dump is null) { if (mgr.GetContext(contextName) is null) ApiResponse.NotFound(Exchange, $"Context '{contextName}' not found."); else ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{contextName}'."); Exchange.Stop(); return null; } return dump; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/ExchangesController.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/ExchangesController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Dlq; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// Dead-letter queue: browse exchanges that failed at a route checkpoint, and replay or discard them. /// GET /api/exchanges/failed — filtered, paged list. /// POST /api/exchanges/{id}/replay — re-run the entry's route tail from its snapshot. /// DELETE /api/exchanges/{id} — discard. /// /// Replay re-executes business code, so mutations require operator; discard requires admin. /// /// [Route("/api/exchanges")] public class ExchangesController : RedbController { private DlqService? GetDlq() => Context.GetService(); [HttpGet("/failed")] [RequiresRole(TsakRoles.Operator)] public async Task GetFailed( [FromQuery("context")] string? context, [FromQuery("route")] string? route, [FromQuery("status")] string? status, [FromQuery("since")] string? since, [FromQuery("until")] string? until, [FromQuery("limit")] int? limit, [FromQuery("offset")] int? offset) { var dlq = GetDlq(); if (dlq is null) return new FailedExchangeQueryResult { Available = false, Error = "DLQ not available", Entries = [] }; DateTimeOffset? sinceTs = DateTimeOffset.TryParse(since, out var s) ? s : null; DateTimeOffset? untilTs = DateTimeOffset.TryParse(until, out var u) ? u : null; return await dlq.QueryAsync( context: context, route: route, status: status, since: sinceTs, until: untilTs, limit: limit ?? 100, offset: offset ?? 0); } [HttpPost("/{id}/replay")] [RequiresRole(TsakRoles.Operator)] [AuditAdminAction(ActionName = "ReplayExchange", TargetParam = "id")] public async Task Replay([FromRoute("id")] string id) { var dlq = GetDlq(); if (dlq is null) { ApiResponse.ServiceUnavailable(Exchange, "DLQ not available"); Exchange.Stop(); return null!; } var result = await dlq.ReplayAsync(id, CancellationToken.None); if (!result.Success) { ApiResponse.BadRequest(Exchange, result.Message); Exchange.Stop(); return null!; } return result; } [HttpDelete("/{id}")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "DiscardExchange", TargetParam = "id")] public async Task Discard([FromRoute("id")] string id) { var dlq = GetDlq(); if (dlq is null) { ApiResponse.ServiceUnavailable(Exchange, "DLQ not available"); Exchange.Stop(); return null!; } var removed = await dlq.DiscardAsync(id, CancellationToken.None); if (!removed) { ApiResponse.NotFound(Exchange, $"Entry '{id}' not found."); Exchange.Stop(); return null!; } return new ExchangeReplayResult { Success = true, Message = "Discarded.", EntryId = id }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/HealthProbeController.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/HealthProbeController.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// Lightweight health probe endpoints for Kubernetes. /// Returns 200 (ok) or 503 (not ok) with minimal body. /// These endpoints bypass authentication — safe for k8s probes. /// /// GET /api/health/startup — has the process finished initialization? /// GET /api/health/live — is the process alive (not hung)? /// GET /api/health/ready — is the process ready to serve traffic? /// GET /api/health/deploy — hot swap a new package (200) or deploy it cold (409)? /// GET /api/health/deploy/cluster — the same for every alive node of the cluster. /// /// For rich health data (CLI/Web), use GET /api/system/health instead. /// [Route("/api/health")] [NoRoleRequired] // technical endpoints: kubelet and load balancers must never get a 403 public class HealthProbeController : RedbController { /// /// Startup probe: returns 200 once the process has completed initialization /// (contexts loaded, cluster coordinator synced if applicable). /// k8s uses this to know when to start liveness/readiness checks. /// [HttpGet("/startup")] public object GetStartup() { // No context manager yet, no contexts loaded, or the cluster coordinator still syncing: still starting. if (StartupProbe.Pending(Context.GetService(), Context.GetService()) is { } pending) { ApiResponse.ServiceUnavailable(Exchange, pending); Exchange.Stop(); return null!; } return new { status = "ok" }; } /// /// Deploy advice for this node: 200 with verdict "hot-swap" (drop the package into modules/ of the running node), /// 409 with "cold-deploy" (cordon, stop, replace the packages, start, wait for ready, uncordon). Advises only. /// [HttpGet("/deploy")] public object GetDeployAdvice() { var advisor = Context.GetService(); if (advisor is null) { ApiResponse.ServiceUnavailable(Exchange, "Deploy advice not available"); Exchange.Stop(); return null!; } var advice = advisor.Advise(); return Answer(advice, advice.Verdict); } /// /// Deploy advice for every alive node of the cluster, asked from any node: 200 only when every node says "hot-swap", /// 409 otherwise. Outside a cluster it lists this node alone. /// [HttpGet("/deploy/cluster")] public async Task GetClusterDeployAdvice() { var advisor = Context.GetService(); if (advisor is null) { ApiResponse.ServiceUnavailable(Exchange, "Deploy advice not available"); Exchange.Stop(); return null!; } var self = advisor.Advise(); IReadOnlyList nodes = Context.GetService() is { } cluster ? await cluster.AdviseAllAsync(self).ConfigureAwait(false) : [self]; var verdict = nodes.All(n => n.Verdict == DeployVerdicts.HotSwap) ? DeployVerdicts.HotSwap : DeployVerdicts.ColdDeploy; return Answer(new ClusterDeployAdviceResponse { Verdict = verdict, AnsweredBy = self.NodeId, Nodes = nodes }, verdict); } /// 200 for a hot swap; 409 with the same body for a cold deploy, so the status code alone carries the verdict. private object Answer(object body, string verdict) { if (verdict == DeployVerdicts.HotSwap) return body; ApiResponse.Respond(Exchange, 409, body); Exchange.Stop(); return null!; } /// /// Liveness probe: returns 200 if the process is alive and not deadlocked. /// Does NOT check module/context state — a degraded context is alive. /// k8s restarts the pod only if this probe fails repeatedly. /// [HttpGet("/live")] public object GetLive() { // The fact that we can reach this code means the event loop is responsive. // Check for fatal conditions only. var watchdog = Context.GetService(); if (watchdog is not null && watchdog.IsEnabled) { var state = watchdog.GetState(); if (state.HungExchanges > 0) { ApiResponse.ServiceUnavailable(Exchange, "Hung exchanges detected"); Exchange.Stop(); return null!; } } return new { status = "ok" }; } /// /// Readiness probe: returns 200 if the process is ready to accept traffic. /// Stricter than liveness — checks that contexts are running and healthy. /// k8s removes pod from service endpoints if this fails (no restart). /// [HttpGet("/ready")] public async Task GetReady() { var healthSvc = Context.GetService(); if (healthSvc is null) { ApiResponse.ServiceUnavailable(Exchange, "HealthCheckService not available"); Exchange.Stop(); return null!; } // Use async evaluation so per-module health contributors are included. var eval = await healthSvc.EvaluateAsync(); // Degraded is 200 by default (the node serves, just slower). Some deployments prefer a // stricter readiness that also fails on Degraded — opt in via Tsak:Health:DegradedNotReady. var degradedNotReady = Context.GetService() ?.GetValue("Tsak:Health:DegradedNotReady", false) ?? false; var notReady = eval.Status == HealthStatus.Unhealthy || (degradedNotReady && eval.Status == HealthStatus.Degraded); if (notReady) { ApiResponse.ServiceUnavailable(Exchange, eval.Description); Exchange.Stop(); return null!; } return new { status = "ok" }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/LifecycleController.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/LifecycleController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Monitoring; namespace redb.Tsak.Core.Controllers; /// /// REST API for the lifecycle event audit trail. /// Supports filtering by context, route, event type, and time. /// [Route("/api/lifecycle")] public class LifecycleController : RedbController { private LifecycleAuditService GetAudit() => Context.GetService() ?? throw new InvalidOperationException("LifecycleAuditService not registered in context"); [HttpGet("")] public object GetEvents( [FromQuery("context")] string? contextName = null, [FromQuery("route")] string? routeId = null, [FromQuery("type")] string? eventType = null, [FromQuery("since")] string? since = null, [FromQuery("limit")] int? limit = null) { LifecycleEventType? parsedType = null; if (eventType is not null && Enum.TryParse(eventType, true, out var t)) parsedType = t; DateTime? parsedSince = null; if (since is not null && DateTime.TryParse(since, out var s)) parsedSince = s.ToUniversalTime(); return GetAudit().GetEvents( contextName: contextName, routeId: routeId, eventType: parsedType, since: parsedSince, limit: limit ?? 100); } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/LogsController.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/LogsController.cs ---- using System.IO.Compression; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// Recent log access from in-memory ring buffer + log file management. /// GET /api/logs?afterId=-1&limit=500&level=Error — incremental log entries /// GET /api/logs?beforeId=1234&limit=200 — the entries older than an id, newest first ("load older") /// GET /api/logs/files — list available log files /// GET /api/logs/files/{filename} — download log file as ZIP /// [Route("/api/logs")] [RequiresRole(TsakRoles.Operator)] // log bodies may carry payload fragments public class LogsController : RedbController { [HttpGet("")] public object GetLogs( [FromQuery("afterId")] long? afterId, [FromQuery("limit")] int? limit, [FromQuery("level")] string? level, [FromQuery("beforeId")] long? beforeId) { if (afterId.HasValue && beforeId.HasValue) return new { Error = "InvalidQuery", Message = "afterId and beforeId cannot be combined" }; var buffer = Context.GetService(); if (buffer is null) return new LogsResponse { Available = false, Entries = [] }; var entries = afterId.HasValue ? buffer.GetAfter(afterId.Value, limit ?? 500, level) : beforeId.HasValue ? buffer.GetBefore(beforeId.Value, limit ?? 200, level) : buffer.GetRecent(limit ?? 100, level); return new LogsResponse { Available = true, Count = entries.Count, TotalBuffered = buffer.Count, BufferCapacity = buffer.Capacity, Entries = entries.ToArray() }; } [HttpGet("files")] public object GetLogFiles() { var logsDir = Path.Combine(Directory.GetCurrentDirectory(), "Logs"); if (!Directory.Exists(logsDir)) return new LogFilesResponse { Available = false, Files = [] }; var files = Directory.GetFiles(logsDir, "*.txt") .Select(f => new FileInfo(f)) .OrderByDescending(f => f.LastWriteTimeUtc) .Select(f => new LogFileInfo { Name = f.Name, Size = f.Length, LastModified = new DateTimeOffset(f.LastWriteTimeUtc, TimeSpan.Zero) }) .ToArray(); return new LogFilesResponse { Available = true, Files = files }; } // Admin-only (review item 2.8): a whole log file is a bulk-exfil path — its body can carry raw // endpoint URIs with passwords and payload fragments. The proper fix is redaction at the core // logging layer, outside redb.Tsak; until then, only admins // may pull entire files. Live-tail via GET /api/logs stays Operator (ring buffer, same risk but // the interactive path operators need). [HttpGet("files/{filename}")] [RequiresRole(TsakRoles.Admin)] public object DownloadLogFile([FromRoute("filename")] string filename) { // Sanitize filename to prevent path traversal var safeName = Path.GetFileName(filename); if (string.IsNullOrEmpty(safeName) || safeName != filename) return new { Error = "InvalidFilename", Message = "Invalid filename" }; var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", safeName); if (!File.Exists(filePath)) return new { Error = "NotFound", Message = $"Log file '{safeName}' not found" }; using var ms = new MemoryStream(); using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) { // Open with FileShare.ReadWrite to avoid conflict with Serilog's active write lock var entry = zip.CreateEntry(safeName, CompressionLevel.Optimal); using var entryStream = entry.Open(); using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fs.CopyTo(entryStream); } return ms.ToArray(); } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/ModulesController.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/ModulesController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Modules; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// Module management: list, register, unregister modules. /// GET /api/modules — list all modules /// GET /api/modules/{name} — get single module details /// DELETE /api/modules/{name} — unregister a module /// [Route("/api/modules")] public class ModulesController : RedbController { private ITsakModuleRegistry GetRegistry() => Context.GetService() ?? throw new InvalidOperationException("ITsakModuleRegistry not registered in context"); [HttpGet("")] public object ListModules() { var registry = GetRegistry(); return registry.GetAllModules().Select(m => new ModuleInfo { ModuleName = m.ModuleName, Version = m.Version, Description = m.Description, Status = m.Status.ToString(), CanInitialize = m.CanInitialize, Dependencies = m.Dependencies.ToArray() }).ToList(); } [HttpGet("/{name}")] public object? GetModule([FromRoute("name")] string name) { var registry = GetRegistry(); var module = registry.GetModule(name); if (module is null) { ApiResponse.NotFound(Exchange, $"Module '{name}' not found."); Exchange.Stop(); return null; } return new ModuleInfo { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Status = module.Status.ToString(), CanInitialize = module.CanInitialize, Dependencies = module.Dependencies.ToArray() }; } [HttpDelete("/{name}")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "UnregisterModule", TargetParam = "name")] public async Task UnregisterModule([FromRoute("name")] string name) { var registry = GetRegistry(); var removed = await registry.UnregisterModuleAsync(name); if (!removed) { ApiResponse.NotFound(Exchange, $"Module '{name}' not found."); Exchange.Stop(); return null; } return new ModuleRemovedResponse { ModuleName = name, Removed = true }; } /// /// Uploads a .tpkg for deployment. The package bytes are the request body; the detached /// signature (base64) travels in the X-Tsak-Signature header. Disabled by default /// (Tsak:Modules:Upload:Enabled), admin-only, audited. All validation — size, valid ZIP, /// manifest, name sanitization, signature — happens in . /// [HttpPost("/upload")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "UploadModule")] public async Task Upload( [FromBody] byte[] package, [FromHeader("X-Tsak-Signature")] string? signature) { var svc = Context.GetService(); if (svc is null || !svc.UploadEnabled) { ApiResponse.Forbidden(Exchange, "Module upload is disabled (Tsak:Modules:Upload:Enabled=false)."); Exchange.Stop(); return null!; } byte[]? sigBytes = null; if (!string.IsNullOrWhiteSpace(signature)) sigBytes = System.Text.Encoding.ASCII.GetBytes(signature); var result = await svc.InstallAsync(package, sigBytes, CancellationToken.None); if (!result.Success) { ApiResponse.BadRequest(Exchange, result.Message); Exchange.Stop(); return null!; } return new ModuleDeployResponse { Success = true, Message = result.Message, ModuleName = result.ModuleName, Version = result.Version }; } /// /// Dry-run validation of a `.tpkg` — same checks as upload (size, ZIP, manifest, name, /// signature) but installs nothing. For CI to verify a package before deploying. /// [HttpPost("/validate")] [RequiresRole(TsakRoles.Admin)] public object Validate( [FromBody] byte[] package, [FromHeader("X-Tsak-Signature")] string? signature) { var svc = Context.GetService(); if (svc is null || !svc.UploadEnabled) { ApiResponse.Forbidden(Exchange, "Module upload/validate is disabled."); Exchange.Stop(); return null!; } byte[]? sigBytes = null; if (!string.IsNullOrWhiteSpace(signature)) sigBytes = System.Text.Encoding.ASCII.GetBytes(signature); var result = svc.Validate(package, sigBytes); return new ModuleDeployResponse { Success = result.Success, Message = result.Message, ModuleName = result.ModuleName, Version = result.Version }; } /// Rolls a module back to its previous on-disk version. Admin-only, audited. [HttpPost("/{name}/rollback")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "RollbackModule", TargetParam = "name")] public object Rollback([FromRoute("name")] string name) { var svc = Context.GetService(); if (svc is null || !svc.UploadEnabled) { ApiResponse.Forbidden(Exchange, "Module upload/rollback is disabled."); Exchange.Stop(); return null!; } var result = svc.Rollback(name); if (!result.Success) { ApiResponse.BadRequest(Exchange, result.Message); Exchange.Stop(); return null!; } return new ModuleDeployResponse { Success = true, Message = result.Message, ModuleName = result.ModuleName }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/RoutesController.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/RoutesController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Controllers; /// /// Route-level management: list, detail, start, stop, inflight browse. /// GET /api/contexts/{ctx}/routes — list routes /// GET /api/contexts/{ctx}/routes/{routeId} — route detail /// POST /api/contexts/{ctx}/routes/{routeId}/start — start route /// POST /api/contexts/{ctx}/routes/{routeId}/stop — stop route (optional timeout) /// GET /api/contexts/{ctx}/routes/{routeId}/inflight — in-flight exchanges for route /// GET /api/contexts/{ctx}/inflight — all in-flight exchanges for context /// [Route("/api/contexts")] public class RoutesController : RedbController { private ITsakContextManager GetManager() => Context.GetService() ?? throw new InvalidOperationException("ITsakContextManager not registered in context"); private ITsakStateStore? GetStateStore() => Context.GetService(); internal const string RouteSuspendedKeyPrefix = "route:suspended:"; internal const string RouteStartedKeyPrefix = "route:started:"; internal static string RouteSuspendedKey(string contextName, string routeId) => $"{RouteSuspendedKeyPrefix}{contextName}:{routeId}"; internal static string RouteStartedKey(string contextName, string routeId) => $"{RouteStartedKeyPrefix}{contextName}:{routeId}"; private ContextInfoCollector GetCollector() => Context.GetService() ?? new ContextInfoCollector(GetManager()); // ═════════════════════════════════════════════════════════════════ // List routes // ═════════════════════════════════════════════════════════════════ [HttpGet("/{name}/routes")] public object? ListRoutes([FromRoute("name")] string name) { var collector = GetCollector(); var detail = collector.Collect(name); if (detail is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } return detail.Routes; } // ═════════════════════════════════════════════════════════════════ // Route detail // ═════════════════════════════════════════════════════════════════ [HttpGet("/{name}/routes/{routeId}")] public object? GetRoute([FromRoute("name")] string name, [FromRoute("routeId")] string routeId) { var collector = GetCollector(); var route = collector.CollectRoute(name, routeId); if (route is null) { var mgr = GetManager(); if (mgr.GetContext(name) is null) ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); else ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } return route; } // ═════════════════════════════════════════════════════════════════ // Start route // ═════════════════════════════════════════════════════════════════ [HttpPost("/{name}/routes/{routeId}/start")] [AuditAdminAction(ActionName = "StartRoute", TargetParam = "routeId")] public async Task StartRoute([FromRoute("name")] string name, [FromRoute("routeId")] string routeId) { var mgr = GetManager(); var ctx = mgr.GetContext(name) as RouteContext; if (ctx is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } var route = ctx.GetRoute(routeId); if (route is null) { ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } await ctx.ResumeRoute(routeId); // Persist route state for context restart var stateStore = GetStateStore(); if (stateStore is not null) { await stateStore.RemoveAsync(RouteSuspendedKey(name, routeId)); await stateStore.SetAsync(RouteStartedKey(name, routeId), "true"); } return new RouteActionResponse { RouteId = routeId, Status = route.Status.ToString() }; } // ═════════════════════════════════════════════════════════════════ // Stop route (optional timeout via query parameter) // ═════════════════════════════════════════════════════════════════ [HttpPost("/{name}/routes/{routeId}/stop")] [AuditAdminAction(ActionName = "StopRoute", TargetParam = "routeId")] public async Task StopRoute( [FromRoute("name")] string name, [FromRoute("routeId")] string routeId, [FromQuery("timeoutSeconds")] int? timeoutSeconds = null) { var mgr = GetManager(); var ctx = mgr.GetContext(name) as RouteContext; if (ctx is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } var route = ctx.GetRoute(routeId); if (route is null) { ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } TimeSpan? timeout = timeoutSeconds.HasValue ? TimeSpan.FromSeconds(timeoutSeconds.Value) : null; await ctx.StopRoute(routeId, timeout); // Persist suspended state so route stays stopped on context restart var stateStore = GetStateStore(); if (stateStore is not null) { await stateStore.SetAsync(RouteSuspendedKey(name, routeId), "true"); await stateStore.RemoveAsync(RouteStartedKey(name, routeId)); } return new RouteActionResponse { RouteId = routeId, Status = route.Status.ToString() }; } // ═════════════════════════════════════════════════════════════════ // Inflight exchanges — per route // ═════════════════════════════════════════════════════════════════ [HttpGet("/{name}/routes/{routeId}/inflight")] public object? GetRouteInflight([FromRoute("name")] string name, [FromRoute("routeId")] string routeId) { var mgr = GetManager(); var ctx = mgr.GetContext(name) as RouteContext; if (ctx is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } if (ctx.GetRoute(routeId) is null) { ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } var collector = GetCollector(); return collector.BrowseInflight(name, routeId); } // ═════════════════════════════════════════════════════════════════ // Inflight exchanges — all routes in context // ═════════════════════════════════════════════════════════════════ [HttpGet("/{name}/inflight")] public object? GetContextInflight([FromRoute("name")] string name) { var mgr = GetManager(); var ctx = mgr.GetContext(name) as RouteContext; if (ctx is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } var collector = GetCollector(); return collector.BrowseInflight(name); } // ═════════════════════════════════════════════════════════════════ // Per-route metrics // ═════════════════════════════════════════════════════════════════ [HttpGet("/{name}/routes/{routeId}/metrics")] public object? GetRouteMetrics([FromRoute("name")] string name, [FromRoute("routeId")] string routeId) { var collector = GetCollector(); var metrics = collector.CollectRouteMetrics(name, routeId); if (metrics is null) { var mgr = GetManager(); if (mgr.GetContext(name) is null) ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); else ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } return metrics; } // ═════════════════════════════════════════════════════════════════ // Force-stop route (immediate cancel, no drain) // ═════════════════════════════════════════════════════════════════ [HttpPost("/{name}/routes/{routeId}/force-stop")] [RequiresRole(TsakRoles.Admin)] // abandons in-flight work — not an everyday operation [AuditAdminAction(ActionName = "ForceStopRoute", TargetParam = "routeId")] public async Task ForceStopRoute( [FromRoute("name")] string name, [FromRoute("routeId")] string routeId) { // Protect _system context routes from force-stop if (name.Equals(SystemContextBuilder.SystemContextName, StringComparison.OrdinalIgnoreCase)) { ApiResponse.Forbidden(Exchange, "Cannot force-stop routes in the _system context."); Exchange.Stop(); return null; } var mgr = GetManager(); var ctx = mgr.GetContext(name) as RouteContext; if (ctx is null) { ApiResponse.NotFound(Exchange, $"Context '{name}' not found."); Exchange.Stop(); return null; } var route = ctx.GetRoute(routeId); if (route is null) { ApiResponse.NotFound(Exchange, $"Route '{routeId}' not found in context '{name}'."); Exchange.Stop(); return null; } // Force-stop with zero timeout — triggers immediate cancel await ctx.StopRoute(routeId, TimeSpan.Zero); // Persist suspended state so route stays stopped on context restart var stateStore = GetStateStore(); if (stateStore is not null) { await stateStore.SetAsync(RouteSuspendedKey(name, routeId), "true"); await stateStore.RemoveAsync(RouteStartedKey(name, routeId)); } // Record in audit trail var auditService = Context.GetService(); auditService?.Record(new LifecycleEvent( DateTime.UtcNow, name, routeId, LifecycleEventType.RouteStopped, "Force-stopped via API (no drain)")); return new RouteActionResponse { RouteId = routeId, Status = route.Status.ToString() }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/SchedulerController.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/SchedulerController.cs ---- using Microsoft.Extensions.Logging; using Quartz; using Quartz.Impl.Matchers; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// Quartz scheduler management endpoints. /// Mirrors lt.tsak RouteContainerController scheduler/ endpoints. /// /// Every route context owns its Quartz scheduler (redb.Route's scheduler per context, as Apache Camel's per /// CamelContext): the endpoints read the schedulers of every context of the node — this one included — and report /// each job with its context. A job key is unique within its context only, so an action takes the context; without /// it the key must be found in exactly one context, never guessed. /// /// [Route("/api/scheduler")] public class SchedulerController : RedbController { private ILogger? Log => Context.GetService(); [HttpGet("/status")] public async Task GetStatus() { var schedulers = Schedulers(); var perContext = new List(schedulers.Count); foreach (var (context, scheduler) in schedulers) perContext.Add(await StatusOf(context, scheduler)); var live = perContext.Where(s => !s.IsShutdown).ToList(); if (live.Count == 0) { return new SchedulerStatusResponse { IsStarted = false, InStandbyMode = false, IsShutdown = true, SchedulerName = perContext.Count == 1 ? perContext[0].SchedulerName : "N/A", SchedulerInstanceId = perContext.Count == 1 ? perContext[0].SchedulerInstanceId : "N/A", TotalJobs = 0, RunningJobs = 0, Status = "Shutdown", Timestamp = DateTime.UtcNow, Schedulers = [.. perContext] }; } // The fields of a single scheduler summarize the node's: sums, all started, any in standby. var isStarted = live.All(s => s.IsStarted); var inStandby = live.Any(s => s.InStandbyMode); return new SchedulerStatusResponse { IsStarted = isStarted, InStandbyMode = inStandby, IsShutdown = false, SchedulerName = live.Count == 1 ? live[0].SchedulerName : CommonPrefix(live.Select(s => s.SchedulerName)), SchedulerInstanceId = live.Count == 1 ? live[0].SchedulerInstanceId : $"{live.Count} schedulers", TotalJobs = live.Sum(s => s.TotalJobs), RunningJobs = live.Sum(s => s.RunningJobs), Status = inStandby ? "Standby" : isStarted ? "Running" : "Stopped", Timestamp = DateTime.UtcNow, Schedulers = [.. perContext] }; } [HttpGet("/scheduled")] public async Task GetScheduledJobs() { var jobs = new List(); foreach (var (context, scheduler) in Schedulers().Where(s => !s.Scheduler.IsShutdown)) { var jobKeys = await scheduler.GetJobKeys(GroupMatcher.AnyGroup()); foreach (var jobKey in jobKeys) { var detail = await scheduler.GetJobDetail(jobKey); if (detail is null) continue; var triggers = await scheduler.GetTriggersOfJob(jobKey); foreach (var trigger in triggers) { var state = await scheduler.GetTriggerState(trigger.Key); jobs.Add(new ScheduledJobInfo { JobKey = jobKey.ToString(), JobName = jobKey.Name, JobGroup = jobKey.Group, JobType = detail.JobType.Name, TriggerKey = trigger.Key.ToString(), TriggerState = state.ToString(), CronExpression = trigger is ICronTrigger cron ? cron.CronExpressionString : null, NextFireTime = trigger.GetNextFireTimeUtc()?.UtcDateTime, PreviousFireTime = trigger.GetPreviousFireTimeUtc()?.UtcDateTime, Priority = trigger.Priority, Context = context }); } } } return new ScheduledJobsResponse { TotalScheduledJobs = jobs.Count, Jobs = jobs.ToArray() }; } [HttpGet("/jobs")] public async Task GetRunningJobs() { var jobs = new List(); foreach (var (context, scheduler) in Schedulers().Where(s => !s.Scheduler.IsShutdown)) { var running = await scheduler.GetCurrentlyExecutingJobs(); jobs.AddRange(running.Select(j => new RunningJobInfo { JobKey = j.JobDetail.Key.ToString(), JobName = j.JobDetail.Key.Name, JobGroup = j.JobDetail.Key.Group, JobType = j.JobDetail.JobType.Name, TriggerKey = j.Trigger.Key.ToString(), FireTime = j.FireTimeUtc.UtcDateTime, RunTimeMs = (long)j.JobRunTime.TotalMilliseconds, RefireCount = j.RefireCount, Context = context })); } return new RunningJobsResponse { TotalRunningJobs = jobs.Count, Jobs = jobs.ToArray() }; } /// Starts (or resumes from standby) the scheduler of , or of every context. [HttpPost("/start")] [AuditAdminAction(ActionName = "SchedulerStart")] public async Task Start([FromQuery("context")] string? context = null) { var (targets, error) = Targets(context); if (error is not null) return error; var messages = new List(); foreach (var (name, scheduler) in targets) { if (!scheduler.IsStarted) { await scheduler.Start(); Log?.LogInformation("Scheduler of context {Context} started", name); messages.Add(Say(name, "Scheduler started", targets.Count)); } else if (scheduler.InStandbyMode) { await scheduler.Start(); Log?.LogInformation("Scheduler of context {Context} resumed from standby", name); messages.Add(Say(name, "Scheduler resumed from standby", targets.Count)); } else { messages.Add(Say(name, "Scheduler already running", targets.Count)); } } return new SchedulerActionResponse { Success = true, Message = string.Join("; ", messages) }; } /// Moves the scheduler of , or of every context, to standby. [HttpPost("/standby")] [AuditAdminAction(ActionName = "SchedulerStandby")] public async Task Standby([FromQuery("context")] string? context = null) { var (targets, error) = Targets(context); if (error is not null) return error; var success = true; var messages = new List(); foreach (var (name, scheduler) in targets) { if (scheduler.InStandbyMode) { messages.Add(Say(name, "Scheduler already in standby", targets.Count)); } else if (!scheduler.IsStarted) { success = false; messages.Add(Say(name, "Scheduler not started", targets.Count)); } else { await scheduler.Standby(); Log?.LogInformation("Scheduler of context {Context} moved to standby", name); messages.Add(Say(name, "Scheduler moved to standby", targets.Count)); } } return new SchedulerActionResponse { Success = success, Message = string.Join("; ", messages) }; } [HttpPost("/pause-job")] [AuditAdminAction(ActionName = "PauseJob", TargetParam = "jobKeyStr")] public async Task PauseJob([FromQuery("key")] string jobKeyStr, [FromQuery("context")] string? context = null) { var (scheduler, key, error) = await FindJob(jobKeyStr, context); if (error is not null) return error; await scheduler!.PauseJob(key!); Log?.LogInformation("Job '{JobKey}' paused", key); return new SchedulerActionResponse { Success = true, Message = $"Job '{key}' paused" }; } [HttpPost("/resume-job")] [AuditAdminAction(ActionName = "ResumeJob", TargetParam = "jobKeyStr")] public async Task ResumeJob([FromQuery("key")] string jobKeyStr, [FromQuery("context")] string? context = null) { var (scheduler, key, error) = await FindJob(jobKeyStr, context); if (error is not null) return error; await scheduler!.ResumeJob(key!); Log?.LogInformation("Job '{JobKey}' resumed", key); return new SchedulerActionResponse { Success = true, Message = $"Job '{key}' resumed" }; } /// /// Fires a job immediately (out of schedule) — the "run it now" operator button. Requires the /// operator role and is audited. /// [HttpPost("/fire-job")] [RequiresRole(TsakRoles.Operator)] [AuditAdminAction(ActionName = "FireJob", TargetParam = "jobKeyStr")] public async Task FireJob([FromQuery("key")] string jobKeyStr, [FromQuery("context")] string? context = null) { var (scheduler, key, error) = await FindJob(jobKeyStr, context); if (error is not null) return error; await scheduler!.TriggerJob(key!); Log?.LogInformation("Job '{JobKey}' fired manually", key); return new SchedulerActionResponse { Success = true, Message = $"Job '{key}' fired" }; } /// /// The scheduler of every route context of the node that has one — this management context first — each once. /// A context gets its scheduler with its first Quartz route; one without such a route has none. /// private List<(string Context, IScheduler Scheduler)> Schedulers() { var result = new List<(string, IScheduler)>(); var seen = new HashSet(ReferenceEqualityComparer.Instance); if (Context.GetService() is { } own && seen.Add(own)) result.Add((Context.ContextId, own)); if (Context.GetService() is { } manager) { foreach (var (name, context) in manager.GetAllContexts()) { if (context.GetService() is { } scheduler && seen.Add(scheduler)) result.Add((name, scheduler)); } } return result; } /// The live schedulers an action targets: the one of , or all of them. private (List<(string Context, IScheduler Scheduler)> Targets, SchedulerActionResponse? Error) Targets(string? context) { var live = Schedulers().Where(s => !s.Scheduler.IsShutdown).ToList(); if (context is not null) { var match = live.Where(s => s.Context == context).ToList(); return match.Count == 0 ? ([], Fail($"Scheduler of context '{context}' not available")) : (match, null); } return live.Count == 0 ? ([], Fail("Scheduler not available")) : (live, null); } /// /// The scheduler holding : in , or — without it — in the one /// context that has the key; a key in several contexts is refused with their names, never guessed. /// private async Task<(IScheduler? Scheduler, JobKey? Key, SchedulerActionResponse? Error)> FindJob(string jobKeyStr, string? context) { var (targets, error) = Targets(context); if (error is not null) return (null, null, error); var found = new List<(string Context, IScheduler Scheduler, JobKey Key)>(); foreach (var (name, scheduler) in targets) { if (await FindJobKey(scheduler, jobKeyStr) is { } key) found.Add((name, scheduler, key)); } return found.Count switch { 0 => (null, null, Fail($"Job '{jobKeyStr}' not found")), 1 => (found[0].Scheduler, found[0].Key, null), _ => (null, null, Fail( $"Job '{jobKeyStr}' exists in contexts {string.Join(", ", found.Select(f => $"'{f.Context}'"))}; pass the context.")) }; } private static async Task StatusOf(string context, IScheduler scheduler) { if (scheduler.IsShutdown) { return new SchedulerContextStatus { Context = context, SchedulerName = scheduler.SchedulerName, SchedulerInstanceId = scheduler.SchedulerInstanceId, IsStarted = false, InStandbyMode = false, IsShutdown = true, TotalJobs = 0, RunningJobs = 0, Status = "Shutdown" }; } var jobKeys = await scheduler.GetJobKeys(GroupMatcher.AnyGroup()); var running = await scheduler.GetCurrentlyExecutingJobs(); return new SchedulerContextStatus { Context = context, SchedulerName = scheduler.SchedulerName, SchedulerInstanceId = scheduler.SchedulerInstanceId, IsStarted = scheduler.IsStarted, InStandbyMode = scheduler.InStandbyMode, IsShutdown = false, TotalJobs = jobKeys.Count, RunningJobs = running.Count, Status = scheduler.InStandbyMode ? "Standby" : scheduler.IsStarted ? "Running" : "Stopped" }; } /// Find a Quartz JobKey by its ToString() representation among all registered jobs. private static async Task FindJobKey(IScheduler scheduler, string jobKeyStr) { var allKeys = await scheduler.GetJobKeys(GroupMatcher.AnyGroup()); return allKeys.FirstOrDefault(k => k.ToString() == jobKeyStr); } private static string CommonPrefix(IEnumerable names) { var list = names.ToList(); var prefix = list[0]; foreach (var name in list.Skip(1)) { var i = 0; while (i < prefix.Length && i < name.Length && prefix[i] == name[i]) i++; prefix = prefix[..i]; } return prefix.TrimEnd('-'); } private static string Say(string context, string message, int targets) => targets == 1 ? message : $"{context}: {message}"; private static SchedulerActionResponse Fail(string message) => new() { Success = false, Message = message }; } Path: redb-tsak/src/redb.Tsak.Core/Controllers/StorageController.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/StorageController.cs ---- using System.Diagnostics; using Microsoft.Extensions.Configuration; using redb.Core; using redb.Core.Providers; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.RedbCore.Extensions; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Security; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Controllers; /// /// Storage maintenance of the redb instances this node can reach. /// GET /api/storage/instances — the host's own storage and every named instance a context declares /// GET /api/storage/stats — index and table statistics of one instance, plus the counter window /// POST /api/storage/analyze — refresh the planner statistics, of one table or of the whole database /// /// Reads sit at operator level, not viewer: index and column names describe the application's data model, the /// same reasoning that puts diagnostic dumps there. The refresh is an admin action and is audited — on a large /// database it runs for minutes and it writes. /// /// /// The instance is named in the query string, never in the path: instance names come from configuration keys /// and a path segment cannot carry every character one might hold. /// /// [Route("/api/storage")] [RequiresRole(TsakRoles.Operator)] public class StorageController : RedbController { private ITsakContextManager Manager => Context.GetService() ?? throw new InvalidOperationException("ITsakContextManager not registered in context"); [HttpGet("/instances")] public object ListInstances() { var instances = new List { DescribeHostInstance() }; instances.AddRange(Manager.GetNamedRedbInstances()); return instances; } [HttpGet("/stats")] public async Task GetStats( [FromQuery("instance")] string? instance, [FromQuery("context")] string? context) { var redb = Resolve(instance, context); if (redb is null) return null; var maintenance = redb.Maintenance; var window = await maintenance.GetStatisticsWindowAsync(); var tables = await maintenance.GetTableStatsAsync(); var indexes = await maintenance.GetIndexStatsAsync(); return new RedbStorageStats { Instance = instance ?? "", ContextName = context, CountersSince = window.CountersSince, IsReplica = window.IsReplica, Tables = tables.Select(Map).ToArray(), Indexes = indexes.Select(Map).ToArray() }; } /// /// Refreshes the planner statistics. Without table the whole database is analyzed, which on a large /// one runs for minutes — the caller is expected to hold a control-timeout client. The table name is /// checked against the catalogs by the engine provider before it reaches any SQL. /// [HttpPost("/analyze")] [RequiresRole(TsakRoles.Admin)] [AuditAdminAction(ActionName = "AnalyzeStorage", TargetParam = "table")] public async Task Analyze( [FromQuery("instance")] string? instance, [FromQuery("context")] string? context, [FromQuery("table")] string? table, [FromQuery("schema")] string? schema) { var redb = Resolve(instance, context); if (redb is null) return null; var sw = Stopwatch.StartNew(); try { if (string.IsNullOrWhiteSpace(table)) await redb.Maintenance.AnalyzeAsync(); else await redb.Maintenance.AnalyzeTableAsync(table, string.IsNullOrWhiteSpace(schema) ? null : schema); } catch (InvalidOperationException ex) { // The provider refuses a table the catalogs do not know: a stale page, or a name that never // existed. That is a request problem, not a server fault. ApiResponse.BadRequest(Exchange, ex.Message); Exchange.Stop(); return null; } sw.Stop(); return new RedbAnalyzeResult { Instance = instance ?? "", Table = table, Schema = schema, ElapsedMs = sw.ElapsedMilliseconds }; } /// /// Resolves the instance to work with: the host's own storage when no name is given, otherwise the named /// instance registered on that context. Both come back scoped to this request, with a connection of their /// own. Writes the 404 and stops the exchange when the name resolves to nothing, and answers null. /// private IRedbService? Resolve(string? instance, string? contextName) { if (string.IsNullOrWhiteSpace(instance)) return this.Redb(); if (string.IsNullOrWhiteSpace(contextName)) { ApiResponse.BadRequest(Exchange, "A named instance needs the context that declares it: pass 'context'."); Exchange.Stop(); return null; } var context = Manager.GetContext(contextName); if (context is null) { ApiResponse.NotFound(Exchange, $"Context '{contextName}' not found."); Exchange.Stop(); return null; } var known = Manager.GetNamedRedbInstances().Any(i => string.Equals(i.Name, instance, StringComparison.OrdinalIgnoreCase) && string.Equals(i.ContextName, contextName, StringComparison.OrdinalIgnoreCase)); if (!known) { ApiResponse.NotFound(Exchange, $"Context '{contextName}' has no redb instance named '{instance}'."); Exchange.Stop(); return null; } // Scoped to this exchange, so concurrent requests never share the instance's connection. A // non-active instance opens its connection right here — that is what makes this call the one that // wakes it, and why the dashboard asks only when the operator asks. return context.GetRedbService(instance, Exchange); } /// The host's own storage, described from the configuration it was built from. private RedbInstanceInfo DescribeHostInstance() { var configuration = Context.GetService(); var provider = configuration?["Tsak:Redb:Provider"]; // The same switch the host's own wiring uses to pick its connection string, so the fingerprint of the // host matches the fingerprint of a named instance that points at the same database. var connectionString = provider?.ToLowerInvariant() switch { null => null, "mssql" or "sqlserver" => configuration?.GetConnectionString("MSSql"), "sqlite" => configuration?.GetConnectionString("Sqlite"), _ => configuration?.GetConnectionString("Postgres") }; return RedbInstanceDescription.Describe( name: "", contextName: null, provider: provider, connectionString: connectionString, usePro: configuration?.GetValue("Tsak:Redb:UsePro", true) ?? true, isActive: true); } private static RedbTableInfo Map(TableStatistics t) => new() { Schema = t.Schema, Table = t.Table, IsRedbOwned = t.IsRedbOwned, EstimatedRows = t.EstimatedRows, DataSizeBytes = t.DataSizeBytes, IndexesSizeBytes = t.IndexesSizeBytes, DeadRows = t.DeadRows, LastAnalyze = t.LastAnalyze, LastAutoAnalyze = t.LastAutoAnalyze, LastVacuum = t.LastVacuum, HasStatistics = t.HasStatistics }; private static RedbIndexInfo Map(IndexStatistics i) => new() { Schema = i.Schema, Table = i.Table, Name = i.Name, IsUnique = i.IsUnique, Columns = i.Columns.ToArray(), IncludedColumns = i.IncludedColumns.ToArray(), IsPrimaryKey = i.IsPrimaryKey, IsUniqueConstraint = i.IsUniqueConstraint, IsClustered = i.IsClustered, BacksForeignKey = i.BacksForeignKey, IsRedbOwned = i.IsRedbOwned, IsSystemCritical = i.IsSystemCritical, CriticalReason = i.CriticalReason.ToString(), SizeBytes = i.SizeBytes, EstimatedRows = i.EstimatedRows, Seeks = i.Seeks, Scans = i.Scans, Updates = i.Updates, LastUsed = i.LastUsed }; } Path: redb-tsak/src/redb.Tsak.Core/Controllers/SystemController.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/SystemController.cs ---- using System.Reflection; using Microsoft.Extensions.Configuration; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; using Dto = redb.Tsak.Contracts; namespace redb.Tsak.Core.Controllers; /// /// System-level endpoints: health, metrics, info. /// GET /api/system/health — health check /// GET /api/system/metrics — latest metrics snapshot /// GET /api/system/info — version, uptime, etc. /// [Route("/api/system")] public class SystemController : RedbController { [HttpGet("/health")] public async Task GetHealth() { var healthSvc = Context.GetService(); if (healthSvc is null) return new Dto.HealthCheckResult { Status = Dto.HealthStatus.Unhealthy, Description = "HealthCheckService not available.", Checks = new Dictionary(), Timestamp = DateTime.UtcNow }; var eval = await healthSvc.EvaluateAsync(); return new Dto.HealthCheckResult { Status = eval.Status, Description = eval.Description, Checks = eval.Checks, Details = eval.Details, Timestamp = eval.Timestamp }; } [HttpGet("/metrics")] public object GetMetrics() { var metricsSvc = Context.GetService(); if (metricsSvc is null) return new Dto.MetricsResponse { Available = false }; var (latest, storedPoints) = metricsSvc.GetSnapshot(); return new Dto.MetricsResponse { Available = true, StoredPoints = storedPoints, Latest = latest is null ? null : new Dto.MetricSnapshot { Timestamp = latest.Timestamp, TimestampMs = latest.TimestampMs, Cpu = new Dto.CpuMetrics { ProcessUsage = latest.Cpu.ProcessUsage, SystemUsage = latest.Cpu.SystemUsage }, Memory = new Dto.MemoryMetrics { WorkingSetMB = latest.Memory.WorkingSetMB, PrivateMemoryMB = latest.Memory.PrivateMemoryMB, VirtualMemoryMB = latest.Memory.VirtualMemoryMB, GCMemoryMB = latest.Memory.GCMemoryMB, SystemMemoryUsageMB = latest.Memory.SystemMemoryUsageMB }, Threading = new Dto.ThreadingMetrics { ActiveThreads = latest.Threading.ActiveThreads, ThreadPoolPendingWork = latest.Threading.ThreadPoolPendingWork }, GarbageCollector = new Dto.GcMetrics { Gen0Collections = latest.GarbageCollector.Gen0Collections, Gen1Collections = latest.GarbageCollector.Gen1Collections, Gen2Collections = latest.GarbageCollector.Gen2Collections, TotalMemoryMB = latest.GarbageCollector.TotalMemoryMB } } }; } [HttpGet("/metrics/history")] public object GetMetricsHistory([FromQuery("minutes")] int? minutesParam) { var metricsSvc = Context.GetService(); if (metricsSvc is null) return new Dto.MetricsHistoryResponse { Available = false }; var minutes = minutesParam ?? 5; if (minutes < 1) minutes = 1; if (minutes > 720) minutes = 720; var history = metricsSvc.GetHistory(minutes); return new Dto.MetricsHistoryResponse { Available = true, Points = history.Select(p => new Dto.MetricSnapshot { Timestamp = p.Timestamp, TimestampMs = p.TimestampMs, Cpu = new Dto.CpuMetrics { ProcessUsage = p.Cpu.ProcessUsage, SystemUsage = p.Cpu.SystemUsage }, Memory = new Dto.MemoryMetrics { WorkingSetMB = p.Memory.WorkingSetMB, PrivateMemoryMB = p.Memory.PrivateMemoryMB, VirtualMemoryMB = p.Memory.VirtualMemoryMB, GCMemoryMB = p.Memory.GCMemoryMB, SystemMemoryUsageMB = p.Memory.SystemMemoryUsageMB }, Threading = new Dto.ThreadingMetrics { ActiveThreads = p.Threading.ActiveThreads, ThreadPoolPendingWork = p.Threading.ThreadPoolPendingWork }, GarbageCollector = new Dto.GcMetrics { Gen0Collections = p.GarbageCollector.Gen0Collections, Gen1Collections = p.GarbageCollector.Gen1Collections, Gen2Collections = p.GarbageCollector.Gen2Collections, TotalMemoryMB = p.GarbageCollector.TotalMemoryMB } }).ToArray() }; } [HttpGet("/info")] public object GetInfo() { var contextMgr = Context.GetService(); var moduleReg = Context.GetService(); var moduleContexts = Context.GetService(); // NOTE: GetEntryAssembly() is host-dependent — the Worker under the default deployment, // the web host when the dashboard runs standalone. var entry = Assembly.GetEntryAssembly(); return new Dto.SystemInfoResponse { Version = entry?.GetName().Version?.ToString() ?? "unknown", // Same source as the startup banner: the informational version ("3.7.2") rather // than the four-part assembly version ("3.7.2.0"). InformationalVersion = entry?.GetCustomAttribute() ?.InformationalVersion?.Split('+')[0] ?? entry?.GetName().Version?.ToString(), StartedAt = NodeStartTime.Value.UtcDateTime, Uptime = (DateTimeOffset.UtcNow - NodeStartTime.Value).ToString(), ContextCount = contextMgr?.GetAllContexts().Count ?? 0, ModuleCount = moduleReg?.GetAllModules().Count ?? 0, MachineName = Environment.MachineName, ProcessorCount = Environment.ProcessorCount, WorkingSetMb = Environment.WorkingSet / (1024.0 * 1024), ModuleContextsAlive = moduleContexts?.ModuleContextsAlive ?? 0, OrphanedModuleContexts = moduleContexts?.OrphanedModuleContexts ?? 0, MaxOrphanedModuleContexts = moduleContexts?.MaxOrphanedContexts ?? 0, ModuleContextsNotice = moduleContexts?.Notice }; } /// /// Effective (merged, resolved) configuration for this node — the Tsak:* and /// ConnectionStrings:* settings the process is actually running with, flattened and with /// secrets redacted. Answers "what config is this node on" without SSH-ing in. Admin-only: it /// reveals topology (providers, connection hosts, feature flags). /// [HttpGet("/config")] [RequiresRole(TsakRoles.Admin)] public object GetConfig() { var config = Context.GetService(); if (config is null) return new Dto.EffectiveConfigResult { Available = false }; var values = new SortedDictionary(StringComparer.Ordinal); var redacted = 0; foreach (var section in new[] { "Tsak", "ConnectionStrings" }) { foreach (var kv in config.GetSection(section).AsEnumerable(makePathsRelative: false)) { if (kv.Value is null) continue; // structural node, not a leaf value var (value, wasRedacted) = ConfigRedactor.Redact(kv.Key, kv.Value); values[kv.Key] = value; if (wasRedacted) redacted++; } } return new Dto.EffectiveConfigResult { Available = true, RedactedCount = redacted, Values = values }; } /// /// The assemblies actually loaded in the process — name, version, and where each came from /// (shared layer / app bin / .NET runtime). Since the redb.* framework is byte-loaded from /// Libs/shared its Location is empty, so shared origin is inferred from the shared-layer /// tracker. Answers "which redb is REALLY running" on an incident without SSH-ing in — the /// diagnostic counterpart to the swappable shared layer. Admin-only. /// [HttpGet("/assemblies")] [RequiresRole(TsakRoles.Admin)] public object GetAssemblies() { var baseDir = AppContext.BaseDirectory; var items = AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .Select(a => { var name = a.GetName(); string location = ""; try { location = a.Location; } catch { /* byte-loaded → not supported */ } string source; if (Modules.SharedRuntime.IsLoaded(name.Name ?? "") && string.IsNullOrEmpty(location)) source = "shared"; // byte-loaded from Libs/shared (no Location) else if (string.IsNullOrEmpty(location)) source = "in-memory"; else if (location.StartsWith(baseDir, StringComparison.OrdinalIgnoreCase)) source = location.Contains($"{Path.DirectorySeparatorChar}shared{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase) ? "shared" : "bin"; else source = "runtime"; return name.Name is null ? null : new Dto.LoadedAssemblyInfo { Name = name.Name, Version = name.Version?.ToString(), Source = source, Location = location }; }) .Where(x => x is not null) .Select(x => x!) .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) .ToArray(); var redb = items.Where(x => x.Name.StartsWith("redb.", StringComparison.OrdinalIgnoreCase)) .ToArray(); return new Dto.AssembliesResponse { Count = items.Length, RedbCount = redb.Length, Redb = redb, // the interesting ones first, at a glance All = items }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/UsersController.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/UsersController.cs ---- using redb.Core; using redb.Core.Models.Users; using redb.Core.Providers; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Route.RedbCore.Extensions; using redb.Tsak.Contracts; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; [Route("/api/users")] [RequiresRole(TsakRoles.Admin)] public class UsersController : RedbController { // Per-request scoped IRedbService (own connection) — NOT the captive singleton, which would // share one non-thread-safe connection across concurrent requests. private IUserProvider GetProvider() => this.Redb().UserProvider; [HttpGet("")] public async Task ListUsers() { var provider = GetProvider(); var users = await provider.GetUsersAsync(); return users .Where(u => u.Id > 0) .Select(u => new TsakUserInfo { Id = u.Id, Login = u.Login, Name = u.Name, Role = u.CodeString ?? "viewer", Enabled = u.Enabled, DateRegister = u.DateRegister }) .ToList(); } [HttpGet("/{login}")] public async Task GetUser([FromRoute("login")] string login) { var provider = GetProvider(); var user = await provider.GetUserByLoginAsync(login); if (user is null) { ApiResponse.NotFound(Exchange, $"User '{login}' not found."); Exchange.Stop(); return null; } return new TsakUserInfo { Id = user.Id, Login = user.Login, Name = user.Name, Role = user.CodeString ?? "viewer", Enabled = user.Enabled, DateRegister = user.DateRegister }; } [HttpPost("")] [AuditAdminAction(ActionName = "CreateUser")] public async Task CreateUser([FromBody] TsakCreateUserRequest? request) { if (request is null || string.IsNullOrWhiteSpace(request.Login) || string.IsNullOrWhiteSpace(request.Password)) { ApiResponse.BadRequest(Exchange, "Login and password are required."); Exchange.Stop(); return null; } var provider = GetProvider(); if (!await provider.IsLoginAvailableAsync(request.Login)) { ApiResponse.BadRequest(Exchange, $"Login '{request.Login}' is already taken."); Exchange.Stop(); return null; } var coreRequest = new CreateUserRequest { Login = request.Login, Password = request.Password, Name = request.Name, Enabled = true, CodeString = request.Role ?? "viewer" }; var user = await provider.CreateUserAsync(coreRequest); return new TsakUserInfo { Id = user.Id, Login = user.Login, Name = user.Name, Role = user.CodeString ?? "viewer", Enabled = user.Enabled, DateRegister = user.DateRegister }; } [HttpPut("/{login}")] [AuditAdminAction(ActionName = "UpdateUser", TargetParam = "login")] public async Task UpdateUser([FromRoute("login")] string login, [FromBody] TsakUpdateUserRequest? request) { if (request is null) { ApiResponse.BadRequest(Exchange, "Request body is required."); Exchange.Stop(); return null; } var provider = GetProvider(); var user = await provider.GetUserByLoginAsync(login); if (user is null) { ApiResponse.NotFound(Exchange, $"User '{login}' not found."); Exchange.Stop(); return null; } if (user.Id <= 0) { ApiResponse.BadRequest(Exchange, "System users cannot be modified."); Exchange.Stop(); return null; } // Admin (id=1): only password change allowed if (user.Id == 1) { if (!string.IsNullOrEmpty(request.Password)) await provider.SetPasswordAsync(user, request.Password); return new TsakUserInfo { Id = user.Id, Login = user.Login, Name = user.Name, Role = user.CodeString ?? "viewer", Enabled = user.Enabled, DateRegister = user.DateRegister }; } var coreRequest = new UpdateUserRequest { Name = request.Name, CodeString = request.Role, Enabled = request.Enabled }; var updated = await provider.UpdateUserAsync(user, coreRequest); if (!string.IsNullOrEmpty(request.Password)) await provider.SetPasswordAsync(updated, request.Password); return new TsakUserInfo { Id = updated.Id, Login = updated.Login, Name = updated.Name, Role = updated.CodeString ?? "viewer", Enabled = updated.Enabled, DateRegister = updated.DateRegister }; } [HttpDelete("/{login}")] [AuditAdminAction(ActionName = "DeleteUser", TargetParam = "login")] public async Task DeleteUser([FromRoute("login")] string login) { var provider = GetProvider(); var user = await provider.GetUserByLoginAsync(login); if (user is null) { ApiResponse.NotFound(Exchange, $"User '{login}' not found."); Exchange.Stop(); return null; } if (user.Id <= 1) { ApiResponse.BadRequest(Exchange, "System users cannot be deleted."); Exchange.Stop(); return null; } await provider.DeleteUserAsync(user); return new TsakUserActionResponse { Login = login, Action = "deleted" }; } } Path: redb-tsak/src/redb.Tsak.Core/Controllers/WatchdogController.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/WatchdogController.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using redb.Tsak.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Monitoring.Alerts; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Controllers; /// /// REST API for the Route Watchdog: status, alerts, enable/disable, alert-delivery test. /// [Route("/api/watchdog")] public class WatchdogController : RedbController { private RouteWatchdogService GetWatchdog() => Context.GetService() ?? throw new InvalidOperationException("RouteWatchdogService not registered in context"); private AlertDispatcher? GetDispatcher() => Context.GetService(); [HttpGet("/status")] public object GetStatus() { return GetWatchdog().GetState(); } [HttpGet("/alerts")] public object GetAlerts() { return GetWatchdog().GetState().ActiveAlerts; } [HttpPost("/enable")] [AuditAdminAction(ActionName = "WatchdogEnable")] public object Enable() { var watchdog = GetWatchdog(); watchdog.Enable(); return new { enabled = true }; } [HttpPost("/disable")] [AuditAdminAction(ActionName = "WatchdogDisable")] public object Disable() { var watchdog = GetWatchdog(); watchdog.Disable(); return new { enabled = false }; } /// Alert-delivery status: is delivery active, and which channels are enabled. [HttpGet("/alerts/status")] public object GetAlertStatus() { var alerts = GetDispatcher(); return new AlertDeliveryStatus { Active = alerts?.IsActive ?? false, Channels = alerts?.EnabledChannels ?? [] }; } /// /// Sends a synthetic alert through every enabled channel and reports the per-channel outcome — /// so an operator can verify webhook / Telegram / email / endpoint configuration without waiting /// for a real hung exchange. Bypasses the dedup window. /// [HttpPost("/test-alert")] [AuditAdminAction(ActionName = "WatchdogTestAlert")] public async Task TestAlert() { var alerts = GetDispatcher(); if (alerts is null || !alerts.IsActive) { return new AlertTestResult { Delivered = false, Message = "Alert delivery is not active. Enable it and at least one channel under Tsak:Watchdog:Alerts." }; } var probe = new AlertNotification { Level = "Test", Title = "Tsak alert delivery test", NodeId = Environment.MachineName, Timestamp = DateTimeOffset.UtcNow }; var results = await alerts.TestAsync(probe, CancellationToken.None); return new AlertTestResult { Delivered = results.All(r => r.Success), Channels = results.Select(r => new AlertChannelOutcome { Channel = r.Channel, Success = r.Success, Error = r.Error }).ToList() }; } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/CheckpointDlqHandler.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/Dlq/CheckpointDlqHandler.cs ---- using redb.Route.Abstractions; namespace redb.Tsak.Core.Dlq; /// /// Context-level error handler (installed as RouteContext.ErrorHandler when Tsak starts the context) that /// dead-letters a failed exchange when the route carried a replay checkpoint. Reads route.checkpoint off the /// exchange and hands it to for durable capture. /// /// Capture is opt-in by construction: only routes with a .Replayable("…") marker leave a /// checkpoint, so only those are captured. Routes without a checkpoint fall through — the DLQ never /// tries to own an exchange the route author did not mark as replayable (and Route already warns if a /// marker sits on a broker/transacted route, where the broker/transaction owns redelivery). /// /// /// As the context's error handler it sees only the failures no OnException took — Apache Camel's model: an /// OnException that takes a failure owns it; it can still dead-letter it explicitly with /// .To("tsak-dlq:"). /// /// /// Capture never marks the failure handled. When the module brought an error handler of its own /// (<deadLetterChannel> in its context.xml, or one set in code) it is : the /// failure is captured first, then the module's handler sends it on and decides whether it is handled. /// /// public sealed class CheckpointDlqHandler : IErrorHandler { private readonly string _contextName; private readonly DlqService _dlq; public CheckpointDlqHandler(string contextName, DlqService dlq, IErrorHandler? next = null) { _contextName = contextName; _dlq = dlq; Next = next; } /// The error handler the module installed itself, run after the capture; null when none. public IErrorHandler? Next { get; } public async Task HandleError(IExchange exchange, Exception exception, CancellationToken ct = default) { await CaptureAsync(_contextName, _dlq, exchange, exception, ct).ConfigureAwait(false); if (Next is not null) await Next.HandleError(exchange, exception, ct).ConfigureAwait(false); } /// /// Dead-letters the exchange when its route left a replay checkpoint; no checkpoint, nothing to capture (the /// failure goes on as it would without the DLQ). Shared with the tsak-dlq: endpoint. /// internal static async Task CaptureAsync(string contextName, DlqService dlq, IExchange exchange, Exception exception, CancellationToken ct) { if (exchange.Properties.TryGetValue(RouteCheckpoint.PropertyKey, out var v) && v is RouteCheckpoint checkpoint) { await dlq.CaptureAsync(contextName, checkpoint, exception, ct).ConfigureAwait(false); return true; } return false; } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/DlqRetentionRouteBuilder.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/Dlq/DlqRetentionRouteBuilder.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Tsak.Core.Dlq; /// /// Daily dead-letter retention as a first-class redb.Route cron route (cron://tsak-dlq-retention) /// instead of a bare Quartz job — visible in the Routes API/dashboard and the scheduler page, using /// redb.Route + the Cron connector like any business route. Prunes tsak_dlq entries older than /// Tsak:Dlq:RetentionDays. The cron:// consumer runs on the shared scheduler injected /// into every Tsak context. Registered by only when the DLQ /// is active and retention is enabled. /// public sealed class DlqRetentionRouteBuilder : RouteBuilder { /// Route id — how the sweep shows up in the Routes API and the dashboard. public const string RouteIdName = "tsak-dlq-retention"; /// Default retention window when the config key is absent. public const int DefaultRetentionDays = 30; /// Daily at 03:05 (Quartz cron) — staggered a few minutes after audit retention. public const string CronSchedule = "0 5 3 * * ?"; private readonly DlqService _dlq; private readonly int _retentionDays; private readonly ILogger? _logger; public DlqRetentionRouteBuilder(DlqService dlq, int retentionDays, ILogger? logger) { _dlq = dlq; _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 (!_dlq.IsAvailable || _retentionDays <= 0) return; var cutoff = DateTimeOffset.UtcNow.AddDays(-_retentionDays); try { var removed = await _dlq.PruneAsync(cutoff, ct); if (removed > 0) _logger?.LogInformation( "DLQ retention: removed {Removed} entries older than {Cutoff:o} ({Days}d)", removed, cutoff, _retentionDays); } catch (Exception ex) { _logger?.LogWarning(ex, "DLQ retention sweep failed"); } }); } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/DlqSchemaInitializer.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/Dlq/DlqSchemaInitializer.cs ---- using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Audit; namespace redb.Tsak.Core.Dlq; /// /// Creates the tsak_dlq table on startup for whichever provider Tsak is configured with. /// Same shape as AuditSchemaInitializer/QuartzSchemaInitializer: raw ADO.NET, provider /// switch over Tsak:Redb:Provider, one embedded idempotent script per dialect. No-ops when the /// DLQ is disabled or the node runs without a database. /// internal sealed class DlqSchemaInitializer : IHostedService { private readonly IConfiguration _configuration; private readonly ILogger _logger; public DlqSchemaInitializer(IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { if (!_configuration.GetValue("Tsak:Dlq:Enabled", true)) { _logger.LogDebug("DLQ disabled (Tsak:Dlq:Enabled=false)"); return; } var provider = DlqStorage.ResolveProvider(_configuration); if (provider == AuditProvider.None) { _logger.LogInformation( "No redb provider configured — dead-letter store disabled (no {Table} table)", DlqStorage.TableName); return; } var connStr = DlqStorage.ResolveConnectionString(_configuration, provider); if (string.IsNullOrEmpty(connStr)) { _logger.LogWarning( "Provider '{Provider}' configured but its connection string is missing — DLQ disabled", provider); return; } var sql = ReadEmbeddedScript(DlqStorage.ScriptResource(provider)); if (sql is null) { _logger.LogWarning("DLQ schema script '{Resource}' not found in embedded resources", DlqStorage.ScriptResource(provider)); return; } try { await using var conn = DlqStorage.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, DlqStorage.TableName, DlqStorage.ClusterIndexName, cancellationToken); await TsakSqlDialect.For(provider).EnsureNullableLongTextColumnAsync( conn, DlqStorage.TableName, DlqStorage.AttachmentsColumn, cancellationToken); _logger.LogInformation("DLQ table {Table} ensured ({Provider})", DlqStorage.TableName, provider); } catch (Exception ex) { _logger.LogError(ex, "Failed to ensure DLQ table {Table} ({Provider})", DlqStorage.TableName, provider); } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; private static string? ReadEmbeddedScript(string logicalName) { using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(logicalName); if (stream is null) return null; using var reader = new StreamReader(stream); return reader.ReadToEnd(); } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/DlqService.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/Dlq/DlqService.cs ---- using System.Data.Common; using System.Globalization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Tsak.Contracts; using redb.Tsak.Core.Audit; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Services.Storage; namespace redb.Tsak.Core.Dlq; /// /// The dead-letter store and its operations: capture a failed exchange (from a route checkpoint), /// query/page the store, replay an entry back through its route, discard, and prune. Raw ADO.NET on /// purpose — the table is flat and provider-specific, like the audit store. /// /// Several Tsak clusters may share the database: an entry carries the cluster that captured it /// (Tsak:Cluster:ClusterName), and every operation sees only this node's cluster, so another /// cluster's entry is "not found" here. An entry captured before cluster isolation has no cluster: it is /// listed and pruned by every cluster, and replayed only while the database holds a single cluster /// (; without one — outside cluster mode — it is this node's own). /// /// public sealed class DlqService { private readonly IConfiguration _configuration; private readonly ITsakContextManager _contextManager; private readonly ILogger _logger; private readonly ITsakClusterDirectory? _clusterDirectory; private readonly string _clusterName; public DlqService( IConfiguration configuration, ITsakContextManager contextManager, ILogger logger, ITsakClusterDirectory? clusterDirectory = null) { _configuration = configuration; _contextManager = contextManager; _logger = logger; _clusterDirectory = clusterDirectory; _clusterName = TsakStorageScope.ClusterName(configuration); } public AuditProvider Provider => DlqStorage.ResolveProvider(_configuration); public bool IsAvailable => _configuration.GetValue("Tsak:Dlq:Enabled", true) && Provider != AuditProvider.None && !string.IsNullOrEmpty(DlqStorage.ResolveConnectionString(_configuration, Provider)); // ── capture ────────────────────────────────────────────────────── /// Persists a failed exchange captured at a route checkpoint. Never throws. public async Task CaptureAsync(string contextName, RouteCheckpoint checkpoint, Exception exception, CancellationToken ct = default) { if (!IsAvailable) return; try { var s = ExchangeSnapshotCodec.Serialize(checkpoint.Snapshot); var correlationId = checkpoint.Snapshot.In.Headers.TryGetValue("CorrelationId", out var c) ? c?.ToString() : null; var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.InsertSql(provider); AddParam(cmd, "entry_id", Guid.NewGuid().ToString()); AddDateParam(cmd, provider, "occurred_at", DateTimeOffset.UtcNow); AddParam(cmd, "context_name", contextName); AddParam(cmd, "route_id", checkpoint.RouteId); AddParam(cmd, "marker_name", checkpoint.MarkerName); AddParam(cmd, "status", "pending"); AddParam(cmd, "exception_type", exception.GetType().Name); AddParam(cmd, "exception_message", Truncate(exception.Message, 2000)); AddParam(cmd, "correlation_id", correlationId); AddParam(cmd, "body_kind", s.BodyKind); AddParam(cmd, "body_type", s.BodyType); AddParam(cmd, "body_data", s.BodyData); AddParam(cmd, "headers_json", s.HeadersJson); AddParam(cmd, "properties_json", s.PropertiesJson); AddParam(cmd, "attachments_json", s.AttachmentsJson); // Bind a real bool: PostgreSQL BOOLEAN has NO implicit cast from integer, so an int 1/0 // makes the whole INSERT throw (silently, via the catch) — the DLQ then captures nothing // on Postgres. bool maps cleanly to PG boolean / SQL Server bit / SQLite 0/1. AddParam(cmd, "replayable", s.Replayable); AddParam(cmd, "cluster_name", _clusterName); await cmd.ExecuteNonQueryAsync(ct); _logger.LogInformation("DLQ captured failed exchange: route={Route} marker={Marker} ex={Ex}", checkpoint.RouteId, checkpoint.MarkerName, exception.GetType().Name); } catch (Exception ex) { // Capturing a dead-letter must never break the failure path further. _logger.LogWarning(ex, "DLQ capture failed for route {Route}", checkpoint.RouteId); } } // ── query ──────────────────────────────────────────────────────── public async Task QueryAsync( string? context = null, string? route = null, string? status = null, DateTimeOffset? since = null, DateTimeOffset? until = null, int limit = 100, int offset = 0, CancellationToken ct = default) { if (!IsAvailable) return new FailedExchangeQueryResult { Available = false, Entries = [] }; limit = Math.Clamp(limit, 1, 1000); offset = Math.Max(offset, 0); var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; try { await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.SelectSql(provider); BindQueryParameters(cmd, provider, context, route, status, 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(MapSummary(reader)); return new FailedExchangeQueryResult { Available = true, Count = entries.Count, Limit = limit, Offset = offset, Entries = entries.ToArray() }; } catch (Exception ex) { _logger.LogError(ex, "DLQ query failed ({Provider})", provider); return new FailedExchangeQueryResult { Available = false, Error = ex.Message, Entries = [] }; } } // ── replay / discard / prune ───────────────────────────────────── public async Task ReplayAsync(string entryId, CancellationToken ct = default) { if (!IsAvailable) return new ExchangeReplayResult { Success = false, Message = "DLQ is not available (no database)." }; // Attribution first: every statement is scoped to this cluster, so another cluster's entry is not // found. An entry captured before cluster isolation carries no cluster — while several clusters // share the database, it cannot be told whose it is, and replaying it could run another cluster's // exchange through this node's same-named route. try { var existing = await TryLoadRowAsync(entryId, ct).ConfigureAwait(false); if (existing is null) return new ExchangeReplayResult { Success = false, Message = "Entry not found.", EntryId = entryId }; if (existing.ClusterName is null && await IsSharedByClustersAsync(ct).ConfigureAwait(false)) return new ExchangeReplayResult { Success = false, EntryId = entryId, Message = "Entry was captured before cluster isolation and several clusters share this database — " + "it cannot be attributed to this cluster, so it is not replayed." }; } catch (Exception ex) { return new ExchangeReplayResult { Success = false, Message = $"Load failed: {ex.Message}", EntryId = entryId }; } // Atomic claim (review item 3.3): flip pending → replaying, but only if still pending. // The DB serializes the conditional UPDATE, so of two concurrent replays exactly one wins the // claim and actually replays — the other is told it is already being handled. This is what // stops a double-click / two operators from replaying the same failed exchange twice. A crash // between claim and replay leaves the row in 'replaying' (visible, not lost) rather than // silently pending-and-forgotten. int claimed; try { claimed = await ClaimForReplayAsync(entryId, ct).ConfigureAwait(false); } catch (Exception ex) { return new ExchangeReplayResult { Success = false, Message = $"Claim failed: {ex.Message}", EntryId = entryId }; } if (claimed == 0) { // Not pending: not found, already replayed, or another replay claimed it first. var current = await TryLoadRowAsync(entryId, ct).ConfigureAwait(false); return current is null ? new ExchangeReplayResult { Success = false, Message = "Entry not found.", EntryId = entryId } : new ExchangeReplayResult { Success = false, EntryId = entryId, Message = $"Entry is not available for replay (status '{current.Status}') — already replayed or being replayed." }; } // We own the claim. Load the full payload. DlqRow? row; try { row = await TryLoadRowAsync(entryId, ct).ConfigureAwait(false); } catch (Exception ex) { await ReleaseClaimAsync(entryId, ct).ConfigureAwait(false); return new ExchangeReplayResult { Success = false, Message = $"Load failed: {ex.Message}", EntryId = entryId }; } if (row is null) // deleted between claim and load — nothing left to release return new ExchangeReplayResult { Success = false, Message = "Entry not found.", EntryId = entryId }; if (!row.Replayable) { await ReleaseClaimAsync(entryId, ct).ConfigureAwait(false); return new ExchangeReplayResult { Success = false, Message = "Entry body did not round-trip; not replayable.", EntryId = entryId }; } var context = _contextManager.GetContext(row.ContextName); if (context is null) { await ReleaseClaimAsync(entryId, ct).ConfigureAwait(false); return new ExchangeReplayResult { Success = false, Message = $"Context '{row.ContextName}' is not loaded.", EntryId = entryId }; } try { var snapshot = ExchangeSnapshotCodec.Rehydrate(new SerializedSnapshot( row.BodyKind, row.BodyType, row.BodyData, row.HeadersJson, row.PropertiesJson, row.AttachmentsJson, row.Replayable)); await context.ReplayAsync(row.RouteId, row.MarkerName, snapshot, ct); await UpdateStatusAsync(entryId, "replayed", DateTimeOffset.UtcNow, ct); return new ExchangeReplayResult { Success = true, Message = "Replayed.", EntryId = entryId }; } catch (Exception ex) { _logger.LogWarning(ex, "DLQ replay failed for entry {Entry} (route {Route})", entryId, row.RouteId); // Release the claim so the entry can be retried rather than being stuck in 'replaying'. await ReleaseClaimAsync(entryId, ct).ConfigureAwait(false); return new ExchangeReplayResult { Success = false, Message = $"Replay failed: {ex.Message}", EntryId = entryId }; } } /// True when the database holds more than one Tsak cluster (known only in cluster mode). private async Task IsSharedByClustersAsync(CancellationToken ct) => _clusterDirectory is not null && await _clusterDirectory.CountClustersAsync(ct).ConfigureAwait(false) > 1; /// Atomic pending → replaying claim. Returns rows affected (1 = won, 0 = lost/not pending). private async Task ClaimForReplayAsync(string entryId, CancellationToken ct) { var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.ClaimForReplaySql(provider); AddParam(cmd, "entry_id", entryId); AddParam(cmd, "from_status", "pending"); AddParam(cmd, "to_status", "replaying"); AddDateParam(cmd, provider, "claimed_at", DateTimeOffset.UtcNow); ClusterColumn.BindScope(cmd, _clusterName); return await cmd.ExecuteNonQueryAsync(ct); } /// Release a claim back to pending (with replayed_at cleared) so the entry can be retried. private Task ReleaseClaimAsync(string entryId, CancellationToken ct) => UpdateStatusAsync(entryId, "pending", null, ct); /// Loads one full DLQ row (with payload) or null if it no longer exists. private async Task TryLoadRowAsync(string entryId, CancellationToken ct) { var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.SelectOneSql(provider); AddParam(cmd, "entry_id", entryId); ClusterColumn.BindScope(cmd, _clusterName); await using var reader = await cmd.ExecuteReaderAsync(ct); return await reader.ReadAsync(ct) ? MapFull(reader) : null; } public async Task DiscardAsync(string entryId, CancellationToken ct = default) { if (!IsAvailable) return false; var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.DeleteOneSql(provider); AddParam(cmd, "entry_id", entryId); ClusterColumn.BindScope(cmd, _clusterName); return await cmd.ExecuteNonQueryAsync(ct) > 0; } public async Task PruneAsync(DateTimeOffset cutoff, CancellationToken ct = default) { if (!IsAvailable) return 0; var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.DeleteOlderThanSql(); AddDateParam(cmd, provider, "cutoff", cutoff); ClusterColumn.BindScope(cmd, _clusterName); return await cmd.ExecuteNonQueryAsync(ct); } private async Task UpdateStatusAsync(string entryId, string status, DateTimeOffset? replayedAt, CancellationToken ct) { var provider = Provider; var connStr = DlqStorage.ResolveConnectionString(_configuration, provider)!; await using var conn = DlqStorage.CreateConnection(provider, connStr); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = DlqStorage.UpdateStatusSql(provider); AddParam(cmd, "status", status); AddDateParam(cmd, provider, "replayed_at", replayedAt); AddParam(cmd, "entry_id", entryId); ClusterColumn.BindScope(cmd, _clusterName); await cmd.ExecuteNonQueryAsync(ct); } // ── mapping / helpers ──────────────────────────────────────────── private sealed record DlqRow( string EntryId, string ContextName, string RouteId, string MarkerName, string BodyKind, string? BodyType, string? BodyData, string HeadersJson, string PropertiesJson, string? AttachmentsJson, bool Replayable, string Status, string? ClusterName); private static FailedExchangeEntry MapSummary(DbDataReader r) => new() { EntryId = GetString(r, "entry_id") ?? "", OccurredAt = ParseTs(r, "occurred_at"), ContextName = GetString(r, "context_name") ?? "", RouteId = GetString(r, "route_id") ?? "", MarkerName = GetString(r, "marker_name") ?? "", Status = GetString(r, "status") ?? "pending", ExceptionType = GetString(r, "exception_type"), ExceptionMessage = GetString(r, "exception_message"), CorrelationId = GetString(r, "correlation_id"), BodyKind = GetString(r, "body_kind") ?? "none", Replayable = GetBool(r, "replayable"), ReplayedAt = r.IsDBNull(r.GetOrdinal("replayed_at")) ? null : ParseTs(r, "replayed_at") }; private static DlqRow MapFull(DbDataReader r) => new( GetString(r, "entry_id") ?? "", GetString(r, "context_name") ?? "", GetString(r, "route_id") ?? "", GetString(r, "marker_name") ?? "", GetString(r, "body_kind") ?? "none", GetString(r, "body_type"), GetString(r, "body_data"), GetString(r, "headers_json") ?? "{}", GetString(r, "properties_json") ?? "{}", GetString(r, "attachments_json"), GetBool(r, "replayable"), GetString(r, "status") ?? "pending", GetString(r, "cluster_name")); /// /// Binds the filter and paging parameters of with explicit types /// (see for why a typed null matters on PostgreSQL); the cluster scope /// is bound next to it by the caller. Internal so the bound shape can be checked without a database. /// internal static void BindQueryParameters( DbCommand cmd, AuditProvider provider, string? context, string? route, string? status, DateTimeOffset? since, DateTimeOffset? until, int limit, int offset) { DbParameterBinding.AddString(cmd, "context", context); DbParameterBinding.AddString(cmd, "route", route); DbParameterBinding.AddString(cmd, "status", status); DbParameterBinding.AddTimestamp(cmd, provider, "since", since); DbParameterBinding.AddTimestamp(cmd, provider, "until", until); DbParameterBinding.AddInt32(cmd, "limit", limit); DbParameterBinding.AddInt32(cmd, "offset", offset); } /// /// Typed binding by CLR type. A null string is a typed null: an untyped reaches /// PostgreSQL as unknown and breaks the (@x IS NULL OR col = @x) shape with 42P08. /// private static void AddParam(DbCommand cmd, string name, object? value) { switch (value) { case null: case string: DbParameterBinding.AddString(cmd, name, (string?)value); return; case bool b: DbParameterBinding.AddBoolean(cmd, name, b); return; case int i: DbParameterBinding.AddInt32(cmd, name, i); return; default: throw new ArgumentException( $"No typed binding for parameter '{name}' of type {value.GetType().Name}.", nameof(value)); } } /// Timestamp in the column's own type per provider; see . private static void AddDateParam(DbCommand cmd, AuditProvider provider, string name, DateTimeOffset? value) => DbParameterBinding.AddTimestamp(cmd, provider, name, value); private static string? Truncate(string? v, int max) => v is null || v.Length <= max ? v : v[..max]; private static string? GetString(DbDataReader r, string col) { var i = r.GetOrdinal(col); if (r.IsDBNull(i)) return null; var v = r.GetValue(i); return v as string ?? v.ToString(); } private static bool GetBool(DbDataReader r, string col) { var i = r.GetOrdinal(col); if (r.IsDBNull(i)) return false; return r.GetValue(i) switch { bool b => b, long l => l != 0, int n => n != 0, _ => Convert.ToInt64(r.GetValue(i)) != 0 }; } private static DateTimeOffset ParseTs(DbDataReader r, string col) { var i = r.GetOrdinal(col); 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 p) => p, _ => default }; } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/DlqStorage.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/Dlq/DlqStorage.cs ---- using System.Data.Common; using Microsoft.Extensions.Configuration; using redb.Tsak.Core.Audit; namespace redb.Tsak.Core.Dlq; /// /// The dead-letter table and its statements. Lives on the same database and provider as the audit log /// (); everything provider-specific — connection string, ADO provider, DDL /// script, casts, paging — comes from the provider's . /// Every statement except the insert is scoped to the node's cluster plus the entries written before /// cluster isolation (, parameter @cluster). /// public static class DlqStorage { public const string TableName = "tsak_dlq"; /// Index on the cluster column, created by the schema initializer. public const string ClusterIndexName = "ix_tsak_dlq_cluster"; /// Message attachments of the entry (see ); null on entries without any. public const string AttachmentsColumn = "attachments_json"; /// Reuse the audit provider enum — the DLQ lives on the same database. public static AuditProvider ResolveProvider(IConfiguration configuration) => AuditStorage.ResolveProvider(configuration); public static string? ResolveConnectionString(IConfiguration configuration, AuditProvider provider) => AuditStorage.ResolveConnectionString(configuration, provider); public static string ScriptResource(AuditProvider provider) => $"DlqSchema.{TsakSqlDialect.For(provider).ScriptSuffix}"; public static DbConnection CreateConnection(AuditProvider provider, string connectionString) => AuditStorage.CreateConnection(provider, connectionString); /// /// INSERT. Column list and parameter names are identical everywhere; the entry id is bound as text /// and cast by the dialect where the column is uuid. The timestamp is bound typed /// (), so it needs no cast. /// public static string InsertSql(AuditProvider provider) { var entryId = TsakSqlDialect.For(provider).Uuid("@entry_id"); return $""" INSERT INTO {TableName} (entry_id, occurred_at, context_name, route_id, marker_name, status, exception_type, exception_message, correlation_id, body_kind, body_type, body_data, headers_json, properties_json, attachments_json, replayable, cluster_name) VALUES ({entryId}, @occurred_at, @context_name, @route_id, @marker_name, @status, @exception_type, @exception_message, @correlation_id, @body_kind, @body_type, @body_data, @headers_json, @properties_json, @attachments_json, @replayable, @cluster_name) """; } /// Paged SELECT, newest-first, all filters optional. public static string SelectSql(AuditProvider provider) { const string body = $""" SELECT entry_id, occurred_at, context_name, route_id, marker_name, status, exception_type, exception_message, correlation_id, body_kind, replayable, replayed_at FROM {TableName} WHERE {ClusterColumn.ScopeCondition} AND (@context IS NULL OR context_name = @context) AND (@route IS NULL OR route_id = @route) AND (@status IS NULL OR status = @status) AND (@since IS NULL OR occurred_at >= @since) AND (@until IS NULL OR occurred_at <= @until) ORDER BY occurred_at DESC """; return body + "\n" + TsakSqlDialect.For(provider).Paging("@limit", "@offset"); } /// Full row for one entry (includes the serialized payload) — used by replay. public static string SelectOneSql(AuditProvider provider) { var entryId = TsakSqlDialect.For(provider).Uuid("@entry_id"); return $""" SELECT entry_id, occurred_at, context_name, route_id, marker_name, status, exception_type, exception_message, correlation_id, body_kind, body_type, body_data, headers_json, properties_json, attachments_json, replayable, replayed_at, cluster_name FROM {TableName} WHERE entry_id = {entryId} AND {ClusterColumn.ScopeCondition} """; } public static string UpdateStatusSql(AuditProvider provider) { var entryId = TsakSqlDialect.For(provider).Uuid("@entry_id"); return $"UPDATE {TableName} SET status = @status, replayed_at = @replayed_at " + $"WHERE entry_id = {entryId} AND {ClusterColumn.ScopeCondition}"; } /// /// Atomic replay claim: flips a single entry @from_status → @to_status, but only if it /// is still in @from_status. The DB serializes the conditional UPDATE, so exactly one /// concurrent caller sees affected == 1 (the winner) — the rest see 0. Prevents two /// operators / a double-click from replaying the same failed exchange twice. /// public static string ClaimForReplaySql(AuditProvider provider) { var entryId = TsakSqlDialect.For(provider).Uuid("@entry_id"); return $"UPDATE {TableName} SET status = @to_status, replayed_at = @claimed_at " + $"WHERE entry_id = {entryId} AND status = @from_status AND {ClusterColumn.ScopeCondition}"; } public static string DeleteOneSql(AuditProvider provider) { var entryId = TsakSqlDialect.For(provider).Uuid("@entry_id"); return $"DELETE FROM {TableName} WHERE entry_id = {entryId} AND {ClusterColumn.ScopeCondition}"; } /// Retention sweep. Cutoff computed in C#, passed as a parameter — no server-side date math. public static string DeleteOlderThanSql() => $"DELETE FROM {TableName} WHERE occurred_at < @cutoff AND {ClusterColumn.ScopeCondition}"; } Path: redb-tsak/src/redb.Tsak.Core/Dlq/ExchangeSnapshotCodec.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/Dlq/ExchangeSnapshotCodec.cs ---- using System.Text; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Serialization; namespace redb.Tsak.Core.Dlq; /// Serialized form of an exchange snapshot for durable DLQ storage. public sealed record SerializedSnapshot( string BodyKind, // bytes | string | json | none string? BodyType, // CLR type name when BodyKind=json string? BodyData, // base64 (bytes) / literal (string) / json string HeadersJson, string PropertiesJson, string? AttachmentsJson, // message attachments: metadata and base64 content; null when there are none bool Replayable); // false when the body could not round-trip /// One stored message attachment of a . public sealed record SerializedAttachment( string Name, string? FileName, string ContentType, string? ContentId, IReadOnlyDictionary Headers, string Data); // base64 /// /// Serializes an snapshot for durable storage and rehydrates it back into a /// fresh exchange for replay. The rehydrated exchange carries no DI scope — the route tail resolves /// redb/SQL lazily from the context provider on replay (fresh connections, cleaned up by /// ReleaseScopes), so no scope needs to be reattached here. /// /// Body fidelity: byte[] and string round-trip exactly; other bodies go through /// System.Text.Json (best-effort — the exact CLR type is restored when its assembly is loadable, /// otherwise the body comes back as a ). A body that cannot be serialized at /// all is stored with BodyKind=none and Replayable=false — the entry stays visible but /// is not durably replayable (§fork-2 limitation). /// /// /// Attachments: the message attachments are stored with their metadata and content (base64, like a /// byte[] body) and come back as byte content in their order. Their size is bounded before they get /// here: the checkpoint the entry comes from is not taken when the attachments exceed /// RedbRoute:Attachments:MaxReplayableBytes, so such an exchange leaves no entry to store. /// /// public static class ExchangeSnapshotCodec { private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = false }; public static SerializedSnapshot Serialize(IExchange snapshot) { var msg = snapshot.In; var (kind, type, data, replayable) = SerializeBody(msg.Body); var headers = ScalarMap(msg.Headers); var props = ScalarMap(snapshot.Properties, skipKey: RouteCheckpoint.PropertyKey); return new SerializedSnapshot(kind, type, data, JsonSerializer.Serialize(headers, JsonOptions), JsonSerializer.Serialize(props, JsonOptions), SerializeAttachments(msg.Attachments), replayable); } /// Rebuilds a fresh exchange from stored data, ready for IRouteContext.ReplayAsync. public static IExchange Rehydrate(SerializedSnapshot s) { var body = DeserializeBody(s.BodyKind, s.BodyType, s.BodyData); var message = new Message(body); foreach (var (k, v) in Deserialize(s.HeadersJson)) message.Headers[k] = v; foreach (var attachment in DeserializeAttachments(s.AttachmentsJson)) message.Attachments.Add(attachment); var exchange = new Exchange(message); foreach (var (k, v) in Deserialize(s.PropertiesJson)) exchange.Properties[k] = v; return exchange; } // ── body ───────────────────────────────────────────────────────── private static (string kind, string? type, string? data, bool replayable) SerializeBody(object? body) { switch (body) { case null: return ("none", null, null, true); case byte[] bytes: return ("bytes", null, Convert.ToBase64String(bytes), true); case string str: return ("string", null, str, true); default: try { var json = JsonSerializer.Serialize(body, body.GetType(), JsonOptions); return ("json", body.GetType().AssemblyQualifiedName, json, true); } catch { // Streams, delegates, non-serializable graphs — keep the entry visible, mark not replayable. return ("none", null, null, false); } } } private static object? DeserializeBody(string kind, string? type, string? data) { if (data is null) return null; return kind switch { "bytes" => Base64Text.Decode(data), "string" => data, "json" => DeserializeJsonBody(type, data), _ => null }; } private static object? DeserializeJsonBody(string? type, string json) { // Restore the exact CLR type when its assembly is loadable; otherwise hand back a JsonElement // (still usable if the tail treats the body as JSON). if (!string.IsNullOrEmpty(type) && Type.GetType(type, throwOnError: false) is { } clr) { try { return JsonSerializer.Deserialize(json, clr, JsonOptions); } catch { /* fall through */ } } return JsonSerializer.Deserialize(json, JsonOptions); } // ── attachments ────────────────────────────────────────────────── private static string? SerializeAttachments(IReadOnlyList attachments) { if (attachments.Count == 0) return null; var stored = attachments.Select(a => new SerializedAttachment( a.Name, a.FileName, a.ContentType, a.ContentId, a.Headers, Convert.ToBase64String(a.Content.ReadAllBytes()))).ToList(); return JsonSerializer.Serialize(stored, JsonOptions); } private static IEnumerable DeserializeAttachments(string? json) { if (string.IsNullOrEmpty(json)) return []; var stored = JsonSerializer.Deserialize>(json, JsonOptions) ?? []; return stored.Select(a => new Attachment { Name = a.Name, FileName = a.FileName, ContentType = a.ContentType, ContentId = a.ContentId, Headers = a.Headers, Content = AttachmentContent.FromBytes(Base64Text.Decode(a.Data)), }); } // ── headers / properties as scalar maps ────────────────────────── /// Keeps only JSON-friendly scalar values; complex objects are stringified. private static Dictionary ScalarMap(IDictionary source, string? skipKey = null) { var result = new Dictionary(StringComparer.Ordinal); foreach (var (k, v) in source) { if (k == skipKey) continue; result[k] = v switch { null or string or bool or int or long or double or decimal => v, byte[] b => Convert.ToBase64String(b), _ => v.ToString() }; } return result; } private static Dictionary Deserialize(string json) { if (string.IsNullOrEmpty(json)) return new(); var raw = JsonSerializer.Deserialize>(json, JsonOptions) ?? new(); var result = new Dictionary(StringComparer.Ordinal); foreach (var (k, e) in raw) result[k] = e.ValueKind switch { JsonValueKind.String => e.GetString(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Number => e.TryGetInt64(out var l) ? l : e.GetDouble(), JsonValueKind.Null => null, _ => e.GetRawText() }; return result; } } Path: redb-tsak/src/redb.Tsak.Core/Dlq/Scripts/dlq_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/Dlq/Scripts/dlq_postgres.sql ---- -- Tsak dead-letter store — PostgreSQL -- Auto-applied by DlqSchemaInitializer on startup when a redb provider is configured. Idempotent. CREATE TABLE IF NOT EXISTS tsak_dlq ( id BIGSERIAL PRIMARY KEY, entry_id UUID NOT NULL, occurred_at TIMESTAMPTZ NOT NULL, context_name VARCHAR(200) NOT NULL, route_id VARCHAR(200) NOT NULL, marker_name VARCHAR(200) NOT NULL, status VARCHAR(20) NOT NULL, -- pending | replayed | discarded exception_type VARCHAR(200), exception_message VARCHAR(2000), correlation_id VARCHAR(200), body_kind VARCHAR(20) NOT NULL, -- bytes | string | json | none body_type VARCHAR(400), -- CLR type name for body_kind=json body_data TEXT, -- base64 (bytes) / literal (string) / json headers_json TEXT, properties_json TEXT, attachments_json TEXT, -- message attachments: metadata and base64 content replayable BOOLEAN NOT NULL, replayed_at TIMESTAMPTZ, cluster_name VARCHAR(200), -- NULL on entries captured before cluster isolation CONSTRAINT uq_tsak_dlq_entry_id UNIQUE (entry_id) ); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_occurred ON tsak_dlq (occurred_at DESC); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_status ON tsak_dlq (status); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_route ON tsak_dlq (route_id); Path: redb-tsak/src/redb.Tsak.Core/Dlq/Scripts/dlq_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/Dlq/Scripts/dlq_sqlServer.sql ---- -- Tsak dead-letter store — SQL Server / Azure SQL -- Auto-applied by DlqSchemaInitializer on startup. Idempotent (OBJECT_ID / sys.indexes guards). IF OBJECT_ID(N'[dbo].[tsak_dlq]', N'U') IS NULL CREATE TABLE [dbo].[tsak_dlq] ( [id] bigint IDENTITY(1,1) NOT NULL PRIMARY KEY, [entry_id] uniqueidentifier NOT NULL, [occurred_at] datetimeoffset NOT NULL, [context_name] nvarchar(200) NOT NULL, [route_id] nvarchar(200) NOT NULL, [marker_name] nvarchar(200) NOT NULL, [status] nvarchar(20) NOT NULL, [exception_type] nvarchar(200) NULL, [exception_message] nvarchar(2000) NULL, [correlation_id] nvarchar(200) NULL, [body_kind] nvarchar(20) NOT NULL, [body_type] nvarchar(400) NULL, [body_data] nvarchar(max) NULL, [headers_json] nvarchar(max) NULL, [properties_json] nvarchar(max) NULL, [attachments_json] nvarchar(max) NULL, [replayable] bit NOT NULL, [replayed_at] datetimeoffset NULL, [cluster_name] nvarchar(200) NULL, CONSTRAINT [uq_tsak_dlq_entry_id] UNIQUE ([entry_id]) ); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_dlq_occurred' AND object_id = OBJECT_ID(N'[dbo].[tsak_dlq]')) CREATE INDEX [ix_tsak_dlq_occurred] ON [dbo].[tsak_dlq] ([occurred_at] DESC); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_dlq_status' AND object_id = OBJECT_ID(N'[dbo].[tsak_dlq]')) CREATE INDEX [ix_tsak_dlq_status] ON [dbo].[tsak_dlq] ([status]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'ix_tsak_dlq_route' AND object_id = OBJECT_ID(N'[dbo].[tsak_dlq]')) CREATE INDEX [ix_tsak_dlq_route] ON [dbo].[tsak_dlq] ([route_id]); Path: redb-tsak/src/redb.Tsak.Core/Dlq/Scripts/dlq_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/Dlq/Scripts/dlq_sqlite.sql ---- -- Tsak dead-letter store — SQLite -- Auto-applied by DlqSchemaInitializer on startup. Idempotent. -- Timestamps are TEXT ISO-8601 (Tsak's own table, not the redb REAL-Julian convention) — -- lexicographic ordering equals chronological ordering. CREATE TABLE IF NOT EXISTS tsak_dlq ( id INTEGER PRIMARY KEY AUTOINCREMENT, entry_id TEXT NOT NULL, occurred_at TEXT NOT NULL, context_name TEXT NOT NULL, route_id TEXT NOT NULL, marker_name TEXT NOT NULL, status TEXT NOT NULL, exception_type TEXT, exception_message TEXT, correlation_id TEXT, body_kind TEXT NOT NULL, body_type TEXT, body_data TEXT, headers_json TEXT, properties_json TEXT, attachments_json TEXT, replayable INTEGER NOT NULL, replayed_at TEXT, cluster_name TEXT, CONSTRAINT uq_tsak_dlq_entry_id UNIQUE (entry_id) ); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_occurred ON tsak_dlq (occurred_at DESC); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_status ON tsak_dlq (status); CREATE INDEX IF NOT EXISTS ix_tsak_dlq_route ON tsak_dlq (route_id); Path: redb-tsak/src/redb.Tsak.Core/Dlq/TsakDlqComponent.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/Dlq/TsakDlqComponent.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Tsak.Core.Dlq; /// /// The checkpoint DLQ as an endpoint. Scheme: tsak-dlq; URI: tsak-dlq: (no path, no options). /// /// The context's sees only the failures no OnException took — Apache /// Camel's model: an OnException that takes a failure owns it, and a logging one without Handled() /// still keeps it from the DLQ. Sending to this endpoint from the handler's body dead-letters the failure /// explicitly, as onException(...).to(deadLetterUri) does in Camel: /// /// OnException<HttpRequestException>().Log("upstream down").To("tsak-dlq:"); /// /// The capture is the one the handler makes: the route must have left a replay checkpoint (.Replayable("…") /// before the failing step); without one nothing is captured and a warning names the route. /// /// Registered by Tsak on every context it creates while a DLQ service is configured. /// public sealed class TsakDlqComponent : ComponentBase { /// The scheme of the endpoint, tsak-dlq. public const string SchemeName = "tsak-dlq"; private readonly DlqService _dlq; public TsakDlqComponent(string contextName, DlqService dlq) { ContextName = contextName; _dlq = dlq; } /// public override string Scheme => SchemeName; /// The Tsak context name the captured entries are filed under. public string ContextName { get; } internal DlqService Dlq => _dlq; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); if (!string.IsNullOrEmpty(uri.Path)) throw new ArgumentException( $"'{EndpointUri.Sanitize(uri.NormalizedKey)}': the DLQ of the context takes no path — write tsak-dlq:", nameof(uri)); var options = new TsakDlqEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new TsakDlqEndpoint(uri, this, options); } } /// Options of tsak-dlq: — none. public sealed class TsakDlqEndpointOptions : EndpointOptions { /// public override void Validate() { } } /// The tsak-dlq: endpoint: a producer only. public sealed class TsakDlqEndpoint : EndpointBase { public TsakDlqEndpoint(EndpointUri uri, TsakDlqComponent component, TsakDlqEndpointOptions options) : base(uri, component, options) { } /// public override IProducer CreateProducer() => new TsakDlqProducer((TsakDlqComponent)Component); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("tsak-dlq: is a destination — use it in To(), from an OnException body."); } /// Dead-letters the failure the exchange carries, from its replay checkpoint. public sealed class TsakDlqProducer : IProducer { private readonly TsakDlqComponent _component; public TsakDlqProducer(TsakDlqComponent component) => _component = component; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // An OnException body runs with the failure on the exchange; anywhere else there is nothing to dead-letter. var failure = exchange.Exception ?? throw new InvalidOperationException( $"Route '{exchange.RouteId}': tsak-dlq: dead-letters a failure — send to it from an OnException body."); if (!await CheckpointDlqHandler.CaptureAsync(_component.ContextName, _component.Dlq, exchange, failure, ct) .ConfigureAwait(false)) { _component.Logger?.LogWarning( "Route '{RouteId}': tsak-dlq: received a failure but the route left no replay checkpoint — nothing was " + "captured. Mark the route .Replayable(\"…\") before the step that can fail.", exchange.RouteId); } } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-tsak/src/redb.Tsak.Core/Extensions/AdminAuditServiceCollectionExtensions.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/Extensions/AdminAuditServiceCollectionExtensions.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Route.Controllers; using redb.Tsak.Core.Audit; using redb.Tsak.Core.Security; namespace redb.Tsak.Core.Extensions; /// /// DI helpers for registering Tsak admin audit components. /// public static class AdminAuditServiceCollectionExtensions { /// /// Registers the admin audit pipeline: /// /// — the always-present fallback sink (structured /// WRN log line, JSON after a [tsak-audit] anchor). /// — the effective , /// which persists to tsak_audit_log via direct://tsak-audit once /// SystemContextBuilder attaches it, and delegates to the log sink until then and /// whenever no database is configured. /// as . /// — creates the table on startup per provider. /// — backs GET /api/audit and the retention job. /// /// All registrations are idempotent, so calling this multiple times is safe. /// public static IServiceCollection AddTsakAdminAudit(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); // The concrete log sink is always available for RouteAdminAuditService to fall back to. services.TryAddSingleton(); // Effective sink: route-backed, fire-and-forget, with the log sink as fallback. services.TryAddSingleton(sp => new RouteAdminAuditService( sp.GetRequiredService(), sp.GetRequiredService>())); services.TryAddEnumerable(ServiceDescriptor.Singleton()); // Schema creation + query service. The initializer no-ops without a provider. services.AddSingleton(); services.TryAddSingleton(); // Retention runs as a cron:// route mounted on the _system context (SystemContextBuilder), // not a bare Quartz job — nothing to register here. return services; } } Path: redb-tsak/src/redb.Tsak.Core/Extensions/AlertServiceCollectionExtensions.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/Extensions/AlertServiceCollectionExtensions.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Monitoring.Alerts; namespace redb.Tsak.Core.Extensions; /// /// Registers the watchdog alert-delivery pipeline: the config-bound options, the natively /// supported channels (webhook, Telegram, email — all zero extra dependencies), and the /// dispatcher. The generic broker endpoint channel is attached later by /// SystemContextBuilder, once the _system route context exists. /// public static class AlertServiceCollectionExtensions { public static IServiceCollection AddTsakAlerts(this IServiceCollection services, IConfiguration configuration) { ArgumentNullException.ThrowIfNull(services); var options = new WatchdogAlertOptions(); configuration.GetSection("Tsak:Watchdog:Alerts").Bind(options); services.TryAddSingleton(options); // One shared HttpClient for the webhook + Telegram channels — a short timeout so a slow // collector cannot stall the alert pump. services.TryAddSingleton(_ => new AlertHttpClient( new HttpClient { Timeout = TimeSpan.FromSeconds(10) })); services.TryAddSingleton(sp => { var http = sp.GetRequiredService().Client; var channels = new IAlertChannel[] { new WebhookAlertChannel(options.Webhook, http), new TelegramAlertChannel(options.Telegram, http), new EmailAlertChannel(options.Email) // The endpoint (broker) channel is attached in SystemContextBuilder — it needs the // route context, and its target component is provided by the host, not Core. }; return new AlertDispatcher(options, channels, sp.GetRequiredService>()); }); return services; } } /// Wrapper so a single long-lived can be a DI singleton. public sealed class AlertHttpClient(HttpClient client) { public HttpClient Client { get; } = client; } Path: redb-tsak/src/redb.Tsak.Core/Extensions/RedbConfigBinder.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/Extensions/RedbConfigBinder.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Configuration; using redb.Core.Models.Configuration; namespace redb.Tsak.Core.Extensions; /// /// Maps a configuration section onto . /// /// /// /// Why this exists. Both config paths — the unnamed instance in /// ServiceCollectionExtensions and the named ones in RedbInstanceFactory — used to /// copy properties across one hand-written line at a time. The lists went stale: of the 37 public /// properties on , the named path carried 15 and 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. EnablePvtPrefilter and /// StringCollation, both added in 3.7, were simply the latest to fall through. /// /// /// The failure was silent, and that is the part worth fixing. An unrecognised key produced /// no diagnostic at all: Tsak__Redb__EnablePvtPrefilter=true did nothing and said nothing, /// and so would a typo. Binding by reflection means a new core property becomes configurable on its /// own, and reporting unknown keys means the next mistake announces itself instead of being found /// months later by someone reading the source. /// /// /// This binder never overrides an explicit decision. Callers apply it FIRST and then set /// whatever they compute themselves (the save strategy, EnsureCreated, the legacy /// Tsak:Redb:Cache subsection). Existing behaviour is therefore unchanged; the binder only /// reaches properties nobody was setting. /// /// internal static class RedbConfigBinder { /// /// Keys that share the section with real settings but are not configuration properties: /// they select the provider or the tier. Listed so they are not reported as unknown. "License" is read by /// nothing since 4.8.0 (Pro needs no key); a configuration that still carries it is ignored silently. /// private static readonly HashSet Infrastructure = new(StringComparer.OrdinalIgnoreCase) { "Provider", "ConnectionString", "UsePro", "License", "Cache", "ContextName", "Instances" }; /// /// Deployed configs already use these names, and they do not match the property they set — /// the property is a while the key carries minutes. Binding alone would /// drop them silently, taking working settings away from everyone who upgrades. /// private static readonly Dictionary MinuteAliases = new(StringComparer.OrdinalIgnoreCase) { ["PropsCacheTtlMinutes"] = nameof(RedbServiceConfiguration.PropsCacheTtl), ["ListCacheTtlMinutes"] = nameof(RedbServiceConfiguration.ListCacheTtl), }; /// /// Properties the binder must not touch: the connection string belongs to the instance and is /// supplied separately, and letting the same section rewrite it invites hard-to-trace mismatches. /// private static readonly HashSet NeverBind = new(StringComparer.OrdinalIgnoreCase) { nameof(RedbServiceConfiguration.ConnectionString) }; private static readonly Lazy> KnownProperties = new(() => new HashSet( typeof(RedbServiceConfiguration) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite) .Select(p => p.Name), StringComparer.OrdinalIgnoreCase)); /// The configuration object being built. /// The section holding the settings. /// How to name this section in diagnostics, e.g. Tsak:Redb. /// Receives one line per applied or rejected key. public static void Apply( RedbServiceConfiguration cfg, IConfiguration section, string origin, Action? report = null) { if (section is null) return; var children = section.GetChildren().ToList(); if (children.Count == 0) return; var applied = new List(); foreach (var child in children) { var key = child.Key; // The stock appsettings document keys with the '"//Key": "..."' JSON-comment // convention (the format has no comments). Such keys are documentation, not // settings — reporting them as typos would teach operators to ignore the very // warning that exists to catch real typos. if (key.StartsWith("//", StringComparison.Ordinal)) continue; if (Infrastructure.Contains(key)) continue; if (MinuteAliases.TryGetValue(key, out var target)) { if (int.TryParse(child.Value, out var minutes)) { if (target == nameof(RedbServiceConfiguration.PropsCacheTtl)) cfg.PropsCacheTtl = TimeSpan.FromMinutes(minutes); else cfg.ListCacheTtl = TimeSpan.FromMinutes(minutes); applied.Add($"{key}={minutes}m"); } else { report?.Invoke($"[WARN] {origin}:{key} — expected a whole number of minutes, got '{child.Value}'. Ignored."); } continue; } if (NeverBind.Contains(key)) { report?.Invoke($"[WARN] {origin}:{key} is set elsewhere and is ignored here."); continue; } if (!KnownProperties.Value.Contains(key)) { report?.Invoke( $"[WARN] {origin}:{key} is not a redb setting and does nothing. " + "Check the spelling against RedbServiceConfiguration."); continue; } // A validating setter (StringCollation runs CollationNameValidator) throws from inside // the binder, where the message says nothing about which key was at fault. Bind one key // at a time so the failure can name itself; the cost is negligible at startup. try { var single = new ConfigurationBuilder() .AddInMemoryCollection(Flatten(child, key)) .Build(); single.Bind(cfg); applied.Add($"{key}={Describe(child)}"); } catch (Exception ex) { throw new InvalidOperationException( $"{origin}:{key} = '{child.Value}' was rejected: {ex.Message}", ex); } } if (applied.Count > 0) report?.Invoke($"[redb] {origin}: applied {string.Join(", ", applied)}"); } /// Re-emits one section (scalar or subtree) as flat key/value pairs. private static IEnumerable> Flatten(IConfigurationSection section, string prefix) { if (section.Value != null) { yield return new KeyValuePair(prefix, section.Value); yield break; } foreach (var child in section.GetChildren()) foreach (var pair in Flatten(child, $"{prefix}:{child.Key}")) yield return pair; } private static string Describe(IConfigurationSection section) => section.Value ?? "{…}"; } Path: redb-tsak/src/redb.Tsak.Core/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Quartz; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using OpenTelemetry.Exporter; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using OpenTelemetry.Trace; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.SQLite.Pro.Extensions; // UseSqlite is tier-agnostic (AddRedb → Free, AddRedbPro → Pro) using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Modules; using redb.Tsak.Core.Services; using redb.Tsak.Core.Security; using redb.Tsak.Core.Services.Storage; using redb.Core.Models.Configuration; using redb.Tsak.Core.Quartz; using redb.Route.Http; using redb.Route.Telemetry; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Extensions; /// /// DI registration for Tsak services. /// Reads Tsak:Storage and Tsak:Redb config sections to configure storage provider. /// public static class ServiceCollectionExtensions { /// /// Register all Tsak services into the DI container. /// Storage mode is determined by Tsak:Storage:Type (InMemory | Redb). /// public static IServiceCollection AddTsak(this IServiceCollection services, IConfiguration configuration) { ConfigureRedb(services, configuration); ConfigureStorage(services, configuration); // The ONE load-boundary trust gate for module code — startup discovery, hot-reload scans // and staged validation all verify through it (review 2026-09-02, К3). services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Shared registry for cross-context direct-vm / vm components services.TryAddSingleton(); // REST API (_system context) — HTTP component + builder services.AddRedbRouteHttp(); services.AddSingleton(); // Reverse proxies the worker sits behind (Tsak:Http:TrustedProxies, addresses or CIDRs). // Configured on the shared Kestrel host, so every HTTP-based listener in the process, the // management API included, sees the client's address and scheme rather than the proxy's. // A value that does not parse fails the start: a silent drop from a security list is how // a typo and a working configuration become indistinguishable. var trustedProxies = configuration.GetSection("Tsak:Http:TrustedProxies").Get() ?? []; services.AddRedbRouteHttpHosting(hosting => { foreach (var entry in trustedProxies) { try { hosting.TrustedProxies.Add(entry); } catch (FormatException ex) { throw new InvalidOperationException( $"Tsak:Http:TrustedProxies contains '{entry}', which is neither an IP address nor a CIDR network.", ex); } } }); // Admin audit (default sink: structured WRN log; Pro can replace with redb-backed sink) services.AddTsakAdminAudit(); // Watchdog alert delivery (all channels off by default; configured via Tsak:Watchdog:Alerts) services.AddTsakAlerts(configuration); // Dead-letter queue (capture failed exchanges at route checkpoints + replay). services.AddSingleton(); services.AddSingleton(); // Retention runs as a cron:// route on the _system context (SystemContextBuilder), not a job. // Module deployment (upload/rollback). Disabled by default — an RCE-capable surface. var uploadOptions = new Modules.ModuleUploadOptions(); configuration.GetSection("Tsak:Modules:Upload").Bind(uploadOptions); var moduleSigOptions = new Modules.ModuleSignatureOptions(); configuration.GetSection("Tsak:Modules:Signature").Bind(moduleSigOptions); services.AddSingleton(uploadOptions); services.AddSingleton(moduleSigOptions); services.AddSingleton(); ConfigureHotReload(services, configuration); ConfigureMonitoring(services, configuration); ConfigureQuartz(services, configuration); // Cluster (Pro) is registered separately via redb.Tsak.Core.Pro.Extensions.AddTsakCluster() // because it lives in the Pro assembly which depends on this Core library. services.AddHostedService(); return services; } private static void ConfigureStorage(IServiceCollection services, IConfiguration configuration) { var storageType = configuration["Tsak:Storage:Type"] ?? "InMemory"; if (storageType.Equals("InMemory", StringComparison.OrdinalIgnoreCase)) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Warn: InMemory state store loses route:suspended:* on restart — clustered routes // won't respect previously suspended state after a process restart. if (configuration.GetValue("Tsak:Cluster:Enabled")) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Error.WriteLine( "[WARN] Cluster is enabled but Storage:Type is InMemory. " + "Route suspension state will be LOST on process restart. " + "Consider Storage:Type=Redb for persistent state."); Console.ResetColor(); } } else if (storageType.Equals("Redb", StringComparison.OrdinalIgnoreCase)) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); } } private static void ConfigureRedb(IServiceCollection services, IConfiguration configuration) { var provider = configuration["Tsak:Redb:Provider"]?.ToLowerInvariant(); if (string.IsNullOrEmpty(provider)) return; // Default to Pro (the Pro redb tier is free): absent Tsak:Redb:UsePro ⇒ Pro. Set it to false // explicitly to run the Free tier. var usePro = configuration.GetValue("Tsak:Redb:UsePro", true); var connectionString = provider switch { "mssql" or "sqlserver" => configuration.GetConnectionString("MSSql"), "sqlite" => configuration.GetConnectionString("Sqlite"), _ => configuration.GetConnectionString("Postgres") }; if (string.IsNullOrEmpty(connectionString)) throw new InvalidOperationException( $"Connection string for provider '{provider}' is not configured. " + $"Set ConnectionStrings:{(provider switch { "mssql" or "sqlserver" => "MSSql", "sqlite" => "Sqlite", _ => "Postgres" })} in appsettings.json"); var strategy = Enum.TryParse(configuration["Tsak:Redb:PropsSaveStrategy"], true, out var parsed) ? parsed : PropsSaveStrategy.DeleteInsert; if (usePro) { services.AddRedbPro(options => { if (provider is "mssql" or "sqlserver") options.UseMsSql(connectionString); else if (provider is "sqlite") options.UseSqlite(connectionString); else options.UsePostgres(connectionString); options.Configure(c => { // Binder first, explicit decisions after: everything below stays authoritative, // and the binder only reaches properties nothing here was setting. RedbConfigBinder.Apply(c, configuration.GetSection("Tsak:Redb"), "Tsak:Redb", m => Console.Error.WriteLine(m)); c.PropsSaveStrategy = strategy; c.EnsureCreated = true; ApplyCacheConfig(c, configuration); }); }); } else { services.AddRedb(options => { if (provider is "mssql" or "sqlserver") options.UseMsSql(connectionString); else if (provider is "sqlite") options.UseSqlite(connectionString); else options.UsePostgres(connectionString); options.Configure(c => { // Binder first, explicit decisions after: everything below stays authoritative, // and the binder only reaches properties nothing here was setting. RedbConfigBinder.Apply(c, configuration.GetSection("Tsak:Redb"), "Tsak:Redb", m => Console.Error.WriteLine(m)); c.PropsSaveStrategy = strategy; c.EnsureCreated = true; ApplyCacheConfig(c, configuration); }); }); } } /// /// Maps the optional Tsak:Redb:Cache section onto the redb configuration. Every key is /// optional and defaults to redb's own default, so an absent section changes nothing. /// /// Safety note: SkipHashValidationOnCacheCheck=true trusts the in-process cache /// without re-checking the object hash in the database. That is correct only for a single writer. /// In a Tsak cluster (multiple nodes writing to the same database) it can serve stale data, so we /// log a warning if both are on. /// /// private static void ApplyCacheConfig(redb.Core.Models.Configuration.RedbServiceConfiguration c, IConfiguration configuration) { var cache = configuration.GetSection("Tsak:Redb:Cache"); if (!cache.Exists()) return; // Props cache if (cache["EnableProps"] is { } ep && bool.TryParse(ep, out var enableProps)) c.EnablePropsCache = enableProps; if (cache.GetValue("PropsMaxSize") is { } pms) c.PropsCacheMaxSize = pms; if (cache.GetValue("PropsTtlMinutes") is { } ptm) c.PropsCacheTtl = TimeSpan.FromMinutes(ptm); if (cache["SkipHashValidationOnCacheCheck"] is { } sh && bool.TryParse(sh, out var skipHash)) c.SkipHashValidationOnCacheCheck = skipHash; // List cache if (cache["EnableList"] is { } el && bool.TryParse(el, out var enableList)) c.EnableListCache = enableList; if (cache.GetValue("ListTtlMinutes") is { } ltm) c.ListCacheTtl = TimeSpan.FromMinutes(ltm); // Metadata cache if (cache["EnableMetadata"] is { } em && bool.TryParse(em, out var enableMeta)) c.EnableMetadataCache = enableMeta; if (cache.GetValue("MetadataTtlMinutes") is { } mtm) c.MetadataCacheLifetimeMinutes = mtm; // Hash recompute on save + cache domain isolation if (cache["AutoRecomputeHash"] is { } ar && bool.TryParse(ar, out var autoHash)) c.AutoRecomputeHash = autoHash; if (!string.IsNullOrWhiteSpace(cache["CacheDomain"])) c.CacheDomain = cache["CacheDomain"]; // Cluster + skip-hash is a stale-read hazard. if (c.SkipHashValidationOnCacheCheck && configuration.GetValue("Tsak:Cluster:Enabled")) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Error.WriteLine( "[WARN] Tsak:Redb:Cache:SkipHashValidationOnCacheCheck=true with Tsak:Cluster:Enabled=true. " + "Skipping cache hash validation can serve STALE data across cluster nodes writing to the same " + "database. Set it to false in clustered deployments."); Console.ResetColor(); } } private static void ConfigureMonitoring(IServiceCollection services, IConfiguration configuration) { var section = configuration.GetSection("Tsak:Metrics"); services.Configure(section); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Control-plane health (review item 4.1): if the _system context fails to start, readiness must // report the node as unhealthy instead of silently serving as if fully operational. services.AddSingleton(); services.AddSingleton(); // Schema problems of the redb databases (host and named instances): Degraded while one needs a person. services.AddSingleton(); // Module contexts that stay in memory after a hot swap: Degraded above Tsak:HotReload:MaxOrphanedContexts. services.AddSingleton(); // GET /api/health/deploy: hot swap or cold deploy for this node; Pro adds cordon and the cluster form. services.AddSingleton(); services.AddHostedService(); // Log ring buffer — in-memory circular buffer for live log viewing var logBufferSize = configuration.GetValue("Tsak:Logs:BufferSize") ?? 2000; var logBuffer = new LogRingBuffer(logBufferSize); services.AddSingleton(logBuffer); services.AddSingleton(new RingBufferSink(logBuffer)); // Route watchdog — detects hung exchanges var watchdogSection = configuration.GetSection("Tsak:Watchdog"); services.Configure(watchdogSection); services.AddSingleton(); services.AddHostedService(sp => sp.GetRequiredService()); // OpenTelemetry pipeline. // • Metrics → Prometheus exporter (Grafana) — Tsak:Metrics:Prometheus:Enabled // • Traces → OTLP exporter (Jaeger / collector) — Tsak:Tracing:Otlp:Enabled // Either toggle (or both) activates the shared pipeline; both default to off. var prometheusEnabled = configuration.GetValue("Tsak:Metrics:Prometheus:Enabled"); var otlpEnabled = configuration.GetValue("Tsak:Tracing:Otlp:Enabled"); if (prometheusEnabled || otlpEnabled) { // Modules hosted on top of Tsak (e.g. redb.Identity) can expose their own // Meters and ActivitySources without taking a runtime dependency on Tsak — // they advertise the names via configuration and Tsak subscribes them into // the OTel pipeline on startup. Keeps Tsak.Core module-agnostic. // Example: // "Tsak": { "Metrics": { "Prometheus": { // "AdditionalMeters": [ "RedbIdentity" ], // "AdditionalSources": [ "RedbIdentity" ] // } } } var additionalMeters = configuration .GetSection("Tsak:Metrics:Prometheus:AdditionalMeters") .Get() ?? Array.Empty(); var additionalSources = configuration .GetSection("Tsak:Metrics:Prometheus:AdditionalSources") .Get() ?? Array.Empty(); var otel = services.AddOpenTelemetry(); // Resource service.name — what shows up in Jaeger / the collector. Configurable // so operators can distinguish nodes; defaults to "redb-tsak-worker" (without it // OTel reports the ugly "unknown_service:redb.Tsak.Worker"). var serviceName = configuration.GetValue("Tsak:Tracing:ServiceName"); if (string.IsNullOrWhiteSpace(serviceName)) serviceName = "redb-tsak-worker"; otel.ConfigureResource(r => r.AddService(serviceName)); if (prometheusEnabled) { var port = configuration.GetValue("Tsak:Metrics:Prometheus:Port") ?? 9464; // The OTel scrape listener binds LOOPBACK only (localhost) — that needs no admin // and no URL ACL on any OS (the Windows wildcard-bind footgun is gone). It is an // internal endpoint: the public scrape target is the Tsak facade's `/metrics` // route (Kestrel, the Api port), which proxies to this loopback listener. See // SystemContextBuilder. Keeping it on loopback also means it is never exposed // unauthenticated on an external interface by accident. var prefix = $"http://localhost:{port}/"; // Pre-flight the bind: an optional metrics exporter must NEVER crash the host. // (Loopback almost always binds; this just guarantees graceful degradation.) if (CanBindHttpListener(prefix)) { otel.WithMetrics(m => { m.AddMeter(RouteMetrics.MeterName); foreach (var meter in additionalMeters) { if (!string.IsNullOrWhiteSpace(meter)) m.AddMeter(meter); } m.AddRuntimeInstrumentation() .AddProcessInstrumentation() .AddPrometheusHttpListener(o => { // The listener binds http://{Host}:{Port}/ — the same loopback prefix checked above. o.Host = "localhost"; o.Port = port; }); }); } } // Tracing sources are always subscribed when the pipeline is up; the OTLP // exporter is attached only when Tsak:Tracing:Otlp:Enabled. Jaeger ingests // OTLP natively (gRPC :4317 / HTTP :4318) — point Endpoint at the collector. otel.WithTracing(t => { t.AddSource(RouteActivitySource.SourceName); foreach (var source in additionalSources) { if (!string.IsNullOrWhiteSpace(source)) t.AddSource(source); } if (otlpEnabled) { var endpoint = configuration.GetValue("Tsak:Tracing:Otlp:Endpoint") ?? "http://localhost:4317"; var protocol = configuration.GetValue("Tsak:Tracing:Otlp:Protocol"); t.AddOtlpExporter(o => { o.Endpoint = new Uri(endpoint); if (string.Equals(protocol, "http/protobuf", StringComparison.OrdinalIgnoreCase)) o.Protocol = OtlpExportProtocol.HttpProtobuf; }); } }); } } /// /// Probes whether an can claim . /// Returns false (and logs an actionable warning to stderr) instead of letting a bind failure /// propagate and take down hosting — the Prometheus exporter is optional infrastructure. /// private static bool CanBindHttpListener(string prefix) { // Retry briefly: on a restart the previous Worker may still hold the port for a // moment (HTTP.sys releases the binding slightly after the old process exits), which // would otherwise make the new instance silently skip metrics for that run. const int attempts = 5; for (var attempt = 1; attempt <= attempts; attempt++) { try { var listener = new System.Net.HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); listener.Stop(); listener.Close(); return true; } catch (Exception ex) { if (attempt < attempts) { System.Threading.Thread.Sleep(700); continue; } Console.Error.WriteLine( $"[Tsak] Prometheus exporter DISABLED — cannot bind HttpListener '{prefix}' after " + $"{attempts} attempts. The Worker continues without metrics (an optional exporter " + $"must never crash the host). Reason: {ex.Message}"); return false; } } return false; } private static void ConfigureHotReload(IServiceCollection services, IConfiguration configuration) { var section = configuration.GetSection("Tsak:HotReload"); services.Configure(section); // Shared assembly loader — loads connectors and shared models from Libs/shared/ services.AddSingleton(); // Counts the module contexts in memory and checks that the ones let go leave it. services.AddSingleton(); // Always register — needed for initial module loading via ALC. // Periodic scanning is controlled by HotReload:Enabled at runtime. services.AddSingleton(); } /// Scheduler name shipped in appsettings.json; with AdoJobStore it is scoped to the Tsak cluster. private const string DefaultSchedulerName = "TsakScheduler"; private static void ConfigureQuartz(IServiceCollection services, IConfiguration configuration) { var quartzSection = configuration.GetSection("Quartz"); if (quartzSection.Exists()) { services.Configure(quartzSection); // Auto-inject connection string and driver delegate from redb config // when AdoJobStore is used without explicit Quartz data source settings var jobStoreType = configuration["Quartz:quartz.jobStore.type"] ?? ""; if (jobStoreType.Contains("AdoJobStore", StringComparison.OrdinalIgnoreCase)) { // Same provider set as redb storage; the per-provider Quartz values live in the dialect. var dialect = Audit.TsakSqlDialect.ForQuartz(configuration); var explicitCs = configuration["Quartz:quartz.dataSource.default.connectionString"]; if (string.IsNullOrEmpty(explicitCs)) { var connStr = configuration.GetConnectionString(dialect.ConnectionStringName); if (!string.IsNullOrEmpty(connStr)) { services.PostConfigure(opts => { opts["quartz.dataSource.default.connectionString"] = connStr; opts["quartz.dataSource.default.provider"] = dialect.QuartzProvider; opts.TryAdd("quartz.jobStore.dataSource", "default"); opts.TryAdd("quartz.jobStore.tablePrefix", "QRTZ_"); opts.TryAdd("quartz.serializer.type", "newtonsoft"); opts.TryAdd("quartz.jobStore.driverDelegateType", dialect.QuartzDriverDelegate); }); } } // Quartz hard-refuses SQLite + clustered at startup ("SQLite cannot be used as // clustered mode due to locking problems": the QRTZ_LOCKS semaphore needs the row // locks SQLite does not have). The shipped clustered=true default (review // 2026-09-02, В11) targets the shared-database providers; a SQLite database is a // local file no second node can share, so non-clustered is safe by construction. // Publish already forces this (sanitize-appsettings.ps1) — mirrored here so a dev // run behaves the same. Deliberate override, not TryAdd; registered after the // blocks above so it wins. if (!dialect.SupportsClusteredJobStore) { services.PostConfigure(opts => opts["quartz.jobStore.clustered"] = "false"); } // Quartz clusters AdoJobStore nodes by scheduler name, and several Tsak clusters may // share one database: the shipped name (or none) is scoped to the Tsak cluster, so each // Tsak cluster is its own Quartz cluster. Any other name is the operator's deliberate // Quartz cluster boundary and is kept. var schedulerName = $"{DefaultSchedulerName}-{redb.Tsak.Core.Services.Storage.TsakStorageScope.ClusterName(configuration)}"; services.PostConfigure(opts => { if (!opts.TryGetValue("quartz.scheduler.instanceName", out var name) || string.IsNullOrWhiteSpace(name) || name == DefaultSchedulerName) opts["quartz.scheduler.instanceName"] = schedulerName; }); } } else { // No `Quartz` config section: in-memory schedulers (non-persistent, single node). RAMJobStore is // Quartz's default; set it explicitly for clarity. services.Configure(opts => opts.TryAdd("quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz")); } // The schema initializer creates the AdoJobStore tables before any context — and so any scheduler — starts // (it no-ops otherwise). Hosted services start sequentially in registration order; TsakHostedService is // registered after this. services.AddSingleton(); // A scheduler per route context, as Apache Camel's per CamelContext (redb.Route.Quartz builds it from these // options with the context's first cron/qtimer route, names it {prefix}-{context}, starts it after the // context and shuts it down with the context). Tsak shares the options, not a scheduler: each context has its // own job namespace — two modules that both say cron://nightly do not collide — and, clustered, a Quartz // cluster of exactly the nodes that run that context. TsakContextManager and SystemContextBuilder hand the // options to every context; the dashboard reads the scheduler of each. // The node id of the same configuration the Quartz section came from: quartz.scheduler.instanceId = NODE. var nodeId = Services.TsakNodeIdentity.Resolve(configuration); services.AddSingleton(provider => SchedulerOptionsOf(provider.GetRequiredService>().Value, nodeId)); } /// /// The per-context scheduler options from the resolved Quartz properties: the configured name (scoped to the Tsak /// cluster above) becomes the prefix the context name follows. A scheduler per context keeps a small pool unless /// configured otherwise. /// /// quartz.scheduler.instanceId = NODE (the shipped value) becomes : the instance /// stays the same across restarts, so after a crash the node takes its own fired triggers back at its first /// check-in instead of waiting until the cluster counts its old record as failed, and a preferred-node pin names /// a node that comes back. Every context's scheduler of the node carries it; they are distinct Quartz clusters /// (one scheduler name each), so the id is unique where Quartz needs it. AUTO and an explicit id are /// Quartz's and stay as configured. /// /// internal static redb.Route.Quartz.QuartzSchedulerOptions SchedulerOptionsOf(QuartzOptions quartz, string nodeId) { var properties = quartz .Where(p => p.Value is not null && p.Key != "quartz.scheduler.instanceName") .ToDictionary(p => p.Key, p => p.Value!, StringComparer.Ordinal); if (properties.TryGetValue("quartz.scheduler.instanceId", out var instanceId) && string.Equals(instanceId.Trim(), Services.TsakNodeIdentity.QuartzInstanceIdOfNode, StringComparison.OrdinalIgnoreCase)) properties["quartz.scheduler.instanceId"] = nodeId; // threadCount is Quartz's older name of maxConcurrency (the shipped appsettings use it): either one is a // configured pool, and adding the other would leave the pool size to the order Quartz applies them in. if (!properties.ContainsKey("quartz.threadPool.maxConcurrency") && !properties.ContainsKey("quartz.threadPool.threadCount")) properties["quartz.threadPool.maxConcurrency"] = DefaultContextSchedulerThreads; var prefix = quartz.TryGetValue("quartz.scheduler.instanceName", out var name) && !string.IsNullOrWhiteSpace(name) ? name : DefaultSchedulerName; return new redb.Route.Quartz.QuartzSchedulerOptions { InstanceNamePrefix = prefix, Properties = properties }; } /// Thread pool of one context's scheduler when the configuration sets none. private const string DefaultContextSchedulerThreads = "4"; } Path: redb-tsak/src/redb.Tsak.Core/Models/TsakContextInfo.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/Models/TsakContextInfo.cs ---- namespace redb.Tsak.Core.Models; /// /// Context snapshot DTO built by ContextInfoCollector.CollectSnapshotsAsync. /// NOTE: the heartbeat no longer propagates these snapshots (review 2026-09-02, И12) — nothing /// in the codebase currently calls the builder or reads TsakNodeProps.Contexts; the /// dashboard renders contexts via live per-node API calls instead. /// public class TsakContextInfo { public string ContextName { get; set; } = string.Empty; public string Status { get; set; } = "Stopped"; public bool IsAnonymous { get; set; } public bool AutoStart { get; set; } = true; public DateTimeOffset? StartedAt { get; set; } public string[] ModuleNames { get; set; } = []; public string[] Components { get; set; } = []; public int RouteCount { get; set; } public int EndpointCount { get; set; } public Dictionary Routes { get; set; } = new(); public Dictionary Endpoints { get; set; } = new(); } /// /// Route snapshot in a shape the redb props store keeps, for heartbeat propagation. /// public class TsakRouteSnapshot { public string RouteId { get; set; } = string.Empty; public string FromUri { get; set; } = string.Empty; public string Status { get; set; } = "Stopped"; public bool AutoStart { get; set; } = true; } /// /// Endpoint snapshot in a shape the redb props store keeps, for heartbeat propagation. /// public class TsakEndpointSnapshot { public string Uri { get; set; } = string.Empty; public string Scheme { get; set; } = string.Empty; public bool IsConsumer { get; set; } public bool IsProducer { get; set; } public long MessagesIn { get; set; } public long MessagesOut { get; set; } public long Errors { get; set; } public long Warnings { get; set; } public long BytesIn { get; set; } public double ThroughputPerSecond { get; set; } public string HealthStatus { get; set; } = "Healthy"; public string? HealthReason { get; set; } public DateTimeOffset? LastActivity { get; set; } public DateTimeOffset? StartedAt { get; set; } public double UptimeSeconds { get; set; } public double AverageProcessingTimeMs { get; set; } public string? LastErrorMessage { get; set; } public DateTimeOffset? LastErrorTime { get; set; } public string? LastWarningMessage { get; set; } public DateTimeOffset? LastWarningTime { get; set; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/InitRouteConvention.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/Modules/InitRouteConvention.cs ---- using System.Reflection; namespace redb.Tsak.Core.Modules; /// /// The InitRoute.main module convention: an exported type named InitRoute with one public static /// main in one of two forms — IRouteContext main(IRouteContext) or /// Task<IRouteContext> main(IRouteContext). A main that fits neither form, or more than one /// main, is an explicit error: skipping it silently made the module vanish without a trace. The /// context type is matched by name (IRouteContext or RouteContext), as discovery always did — /// module assemblies load into their own load contexts. /// internal static class InitRouteConvention { public const string TypeName = "InitRoute"; public const string MethodName = "main"; public const string SyncForm = "public static IRouteContext main(IRouteContext context)"; public const string AsyncForm = "public static Task main(IRouteContext context)"; public enum Form { Unsupported, Sync, Async } public static Form Classify(MethodInfo main) { var parameters = main.GetParameters(); if (parameters.Length != 1 || !IsContextType(parameters[0].ParameterType)) return Form.Unsupported; var returnType = main.ReturnType; if (IsContextType(returnType)) return Form.Sync; if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>) && IsContextType(returnType.GetGenericArguments()[0])) return Form.Async; return Form.Unsupported; } /// /// The one main of an InitRoute type. Throws naming the /// type, the found signatures and the supported forms when a main fits neither form or there is more /// than one. /// public static MethodInfo Resolve(Type initRoute, IReadOnlyList mains) { var unsupported = mains.Where(m => Classify(m) == Form.Unsupported).ToList(); if (unsupported.Count > 0) throw new InvalidOperationException( $"{initRoute.FullName} declares main with an unsupported signature: " + $"{string.Join("; ", unsupported.Select(Describe))}. Supported: '{SyncForm}' or '{AsyncForm}'."); if (mains.Count > 1) throw new InvalidOperationException( $"{initRoute.FullName} declares more than one main ({string.Join("; ", mains.Select(Describe))}); " + $"both forms at once or overloads are not supported. Keep one: '{SyncForm}' or '{AsyncForm}'."); return mains[0]; } /// A readable signature, e.g. Task<IRouteContext> main(IRouteContext). public static string Describe(MethodInfo main) => $"{Label(main.ReturnType)} {main.Name}({string.Join(", ", main.GetParameters().Select(p => Label(p.ParameterType)))})"; private static bool IsContextType(Type type) => type.Name is "IRouteContext" or "RouteContext"; private static string Label(Type type) { if (type == typeof(void)) return "void"; if (!type.IsGenericType) return type.Name; var name = type.Name[..type.Name.IndexOf('`')]; return $"{name}<{string.Join(", ", type.GetGenericArguments().Select(Label))}>"; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/LoadedAssemblyTracker.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/Modules/LoadedAssemblyTracker.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Runtime.Loader; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Modules; /// /// Centralized registry of byte-loaded assemblies across all Tsak loading paths. /// Prevents type identity split-brain: the same assembly name always resolves to /// the same instance regardless of which module loaded it first. /// /// Provides a single Default.Resolving handler that serves all callers: /// , , /// , and bare-DLL discovery. /// /// public static class LoadedAssemblyTracker { private static readonly ConcurrentDictionary _assemblies = new(StringComparer.OrdinalIgnoreCase); private static readonly ConcurrentDictionary> _loadLocks = new(StringComparer.OrdinalIgnoreCase); private static int _resolverRegistered; /// /// Registers the single Default.Resolving handler. /// Safe to call multiple times — only the first call registers. /// Must be called before any byte-loaded assembly usage. /// public static void EnsureResolverRegistered() { if (Interlocked.CompareExchange(ref _resolverRegistered, 1, 0) == 0) { AssemblyLoadContext.Default.Resolving += (_, name) => name.Name is not null && _assemblies.TryGetValue(name.Name, out var asm) ? asm : null; } } /// /// Returns an already-tracked assembly with the given name, the host's own instance when the host /// provides that name, or loads into the Default ALC and tracks it. /// Guarantees that the same assembly name always maps to a single instance. /// /// Caller's key — the assembly's simple name, or the file basename. /// The bytes to load when the name is new to this process. /// Takes the note when the host's instance is reused instead of the bytes. public static Assembly LoadOrReuse(string assemblyName, byte[] bytes, ILogger? logger = null) { EnsureResolverRegistered(); // Fast path: reuse existing if (_assemblies.TryGetValue(assemblyName, out var existing)) return existing; // The host may already provide this name — a shared-framework assembly above all: a module // library takes Microsoft.Extensions.* from NuGet, while the worker resolves those very names from // Microsoft.AspNetCore.App. Byte-loading the package's copy added a SECOND instance to the Default // context that nothing ever bound to (ModuleAssemblyLoadContext asks Default first, so the host's // copy wins every resolution) and that never unloads. Reuse what the host resolves; only a name the // host cannot resolve is loaded from the bytes. Same first step as ModuleAssemblyLoadContext.Load. if (TryLoadFromHost(assemblyName) is { } hostProvided) { var canonicalName = hostProvided.GetName().Name ?? assemblyName; var hostTracked = _assemblies.GetOrAdd(canonicalName, hostProvided); if (!string.Equals(canonicalName, assemblyName, StringComparison.OrdinalIgnoreCase)) _assemblies.TryAdd(assemblyName, hostTracked); logger?.LogDebug( "Assembly {Name} is provided by the host — reusing that instance instead of loading the copy that came with the module", assemblyName); return hostTracked; } // Use Lazy to guarantee only one Assembly.Load call per name, // even under concurrent access. Losers get the winner's Assembly. var lazy = _loadLocks.GetOrAdd(assemblyName, _ => new Lazy(() => { var loaded = Assembly.Load(bytes); var actualName = loaded.GetName().Name ?? assemblyName; // The REAL simple name is the canonical key (it's what the runtime's Default.Resolving asks // for). If that identity is ALREADY tracked (e.g. loaded from shared/ or a prior call under // the matching name), the assembly we just loaded is a DUPLICATE — keep the canonical // instance and alias the caller's key to IT, never to the duplicate (review: ALC finding #2). // Then also alias under the caller's key (typically the file basename) so a later call with // the same basename reuses this instance rather than byte-loading a second copy (3.5). var canonical = _assemblies.GetOrAdd(actualName, loaded); if (!string.Equals(actualName, assemblyName, StringComparison.OrdinalIgnoreCase)) _assemblies.TryAdd(assemblyName, canonical); return canonical; })); var result = lazy.Value; _loadLocks.TryRemove(assemblyName, out _); // Prefer the canonical (real-name) instance, then the caller-key alias, then the lazy result. return _assemblies.TryGetValue(result.GetName().Name ?? assemblyName, out var byReal) ? byReal : _assemblies.TryGetValue(assemblyName, out var tracked) ? tracked : result; } /// /// The host's own instance of , or null when the host cannot resolve /// that name. Resolution runs against the Default context: the shared frameworks and the worker's own /// directory, plus this tracker's own Resolving handler for names already byte-loaded here. /// private static Assembly? TryLoadFromHost(string assemblyName) { try { return AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); } catch (FileNotFoundException) { return null; } // the host does not have it — load the bytes catch (FileLoadException) { return null; } catch (BadImageFormatException) { return null; } catch (ArgumentException) { return null; } // a file basename is not always a valid assembly name } /// /// Force-replaces the tracked assembly with a newly loaded one. /// Used during hot-reload when a shared dependency DLL has been updated. /// Old assembly stays in memory (Default ALC can't unload) but all future /// JIT resolutions will see the new instance. /// public static Assembly Replace(string assemblyName, byte[] bytes) { EnsureResolverRegistered(); var loaded = Assembly.Load(bytes); var actualName = loaded.GetName().Name ?? assemblyName; _assemblies[actualName] = loaded; // Alias under the caller's key too (3.5) so a later LoadOrReuse(fileBasename) reuses this. if (!string.Equals(actualName, assemblyName, StringComparison.OrdinalIgnoreCase)) _assemblies[assemblyName] = loaded; return loaded; } /// /// Tracks an assembly loaded externally (e.g. by /// which loads into Default ALC via LoadFromStream). /// public static void Track(Assembly assembly) { EnsureResolverRegistered(); var name = assembly.GetName().Name; if (name is not null) _assemblies.TryAdd(name, assembly); } /// /// Tracks an assembly, replacing if already present. /// Used by on reload. /// public static void TrackOrReplace(Assembly assembly) { EnsureResolverRegistered(); var name = assembly.GetName().Name; if (name is not null) _assemblies[name] = assembly; } /// /// Tries to find a tracked assembly by name. /// Used by to resolve shared deps /// before falling back to probe paths. /// public static bool TryGet(string assemblyName, out Assembly? assembly) => _assemblies.TryGetValue(assemblyName, out assembly); /// Number of tracked assemblies — for diagnostics. public static int Count => _assemblies.Count; /// /// Resets all state. For testing only. /// internal static void Reset() { _assemblies.Clear(); _loadLocks.Clear(); // Note: Default.Resolving handler stays (can't unsubscribe lambda) but will // return null for all lookups after Clear(). } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleAssemblyLoadContext.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/Modules/ModuleAssemblyLoadContext.cs ---- using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; namespace redb.Tsak.Core.Modules; /// /// Isolated for module isolation. /// Each dynamically loaded module gets its own ALC. /// When collectible, the ALC can be unloaded and replaced without restarting the process. /// When non-collectible (default), a replaced ALC stays in memory until the process restarts. /// Loads from bytes so the original DLL file is never locked. /// Probes configured directories for dependencies so modules don't need /// to be in the host application's bin folder. /// public sealed class ModuleAssemblyLoadContext : AssemblyLoadContext { // Every module context made in the process, weakly. AssemblyLoadContext.All drops a context the moment its Unload // starts, while the context stays in memory until it is collected: the count of what is in memory needs its own list. private static readonly List> Created = []; private readonly string[] _probePaths; public ModuleAssemblyLoadContext(string name, string[]? probePaths = null, bool isCollectible = false) : base(name: name, isCollectible: isCollectible) { _probePaths = probePaths ?? []; lock (Created) Created.Add(new WeakReference(this)); } /// /// The module contexts in memory, unloading ones included, until they are collected. The list holds them only for /// as long as the caller does. /// internal static List InMemory() { var alive = new List(); lock (Created) { Created.RemoveAll(reference => !reference.TryGetTarget(out _)); foreach (var reference in Created) { if (reference.TryGetTarget(out var context)) alive.Add(context); } } return alive; } /// /// The companion assemblies of the package this context belongs to. They load into the Default context, shared /// by name across packages, yet they are the module's code: its type resolver searches them along with /// . /// internal IReadOnlyList Companions { get; set; } = []; /// /// The manifest of the package this context belongs to, null for a module loaded from a bare DLL: its /// order the contexts of the package's modules at start. /// internal ModuleManifest? Manifest { get; set; } /// /// When Tsak let this context go (); null while a module, or the rollback history, still uses /// it. From then on the context should leave memory: counts it while it does not. /// internal DateTime? ReleasedAtUtc { get; private set; } /// Set by once it has taken this released context into its unload check. internal bool UnloadChecked { get; set; } /// Set by when this collectible context outlived the collections of its check. internal bool OutlivedUnload { get; set; } /// /// Lets the context go: unloads it if collectible. A context that is not collectible stays in memory until the process /// restarts. Either way it is marked released, so sees it. /// public void TryUnload() { ReleasedAtUtc ??= DateTime.UtcNow; if (IsCollectible) Unload(); } /// Reads into memory and loads from stream — file is never locked. public Assembly LoadFromBytes(string dllPath) { var bytes = File.ReadAllBytes(dllPath); return LoadFromStream(new MemoryStream(bytes)); } protected override Assembly? Load(AssemblyName assemblyName) { // First, try to resolve from the default (host) ALC. // This ensures shared contract types (IRouteContext, ITsakModule, etc.) // use the same identity as the host — preventing type mismatch across ALCs. try { var hostAssembly = Default.LoadFromAssemblyName(assemblyName); if (hostAssembly is not null) return hostAssembly; } catch (FileNotFoundException) { } catch (FileLoadException) { } // Second, check centralized tracker — covers byte-loaded assemblies from // packages, bare DLLs, and shared layer. This ensures that dependencies // shared across modules use the same Assembly instance (same static fields). if (assemblyName.Name is not null && LoadedAssemblyTracker.TryGet(assemblyName.Name, out var tracked) && tracked is not null) return tracked; // Not in host or tracker — probe module directories. This is a PRIVATE module dependency // (a shared/host/contract assembly would have resolved above via Default or the tracker), so // load it into THIS module's ALC, not the Default ALC (review item 3.7a). That keeps it // unloadable together with the module, and lets two modules carry DIFFERENT versions of the // same private dependency instead of silently sharing whichever loaded first into Default. foreach (var dir in _probePaths) { var candidate = Path.Combine(dir, assemblyName.Name + ".dll"); if (File.Exists(candidate)) { var bytes = File.ReadAllBytes(candidate); return LoadFromStream(new MemoryStream(bytes)); } } return null; } protected override nint LoadUnmanagedDll(string unmanagedDllName) { foreach (var dir in _probePaths) { // Direct match in probe directory var candidate = Path.Combine(dir, unmanagedDllName); if (File.Exists(candidate)) return LoadUnmanagedDllFromPath(candidate); // NuGet runtimes layout: runtimes/{rid}/native/{lib} var rid = RuntimeInformation.RuntimeIdentifier; candidate = Path.Combine(dir, "runtimes", rid, "native", unmanagedDllName); if (File.Exists(candidate)) return LoadUnmanagedDllFromPath(candidate); } return nint.Zero; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleContextMonitor.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/Modules/ModuleContextMonitor.cs ---- using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Modules; /// /// Tells how many module load contexts are in memory and how many of them should be gone. A context should be gone /// once Tsak let it go (): a version replaced by a hot swap or a /// package reload and dropped from the rollback history, a removed module, the throwaway context of a package check. /// /// With false such a context never leaves memory, so it counts as orphaned /// from the moment it is let go. A collectible one is checked after the operation that let it go, off the hot path: /// a few full collections with growing pauses between them. One still alive after the last of them is logged as a /// warning and counted. A context that leaves memory later stops being counted, because the count is taken from the /// module contexts still in memory (). /// /// public sealed class ModuleContextMonitor { /// Full collections a released collectible context gets before it counts as orphaned. internal const int Collections = 10; /// What the node needs once too many contexts stay in memory. public const string RestartAdvice = "restart the node to reclaim memory"; private static readonly TimeSpan LongestPause = TimeSpan.FromSeconds(5); private readonly HotReloadOptions _options; private readonly ILogger _logger; private readonly TimeSpan _firstPause; private readonly object _gate = new(); private Task _running = Task.CompletedTask; private bool _checking; private bool _again; private int _reportedOrphaned; public ModuleContextMonitor(IOptions options, ILogger logger) : this(options.Value, logger, TimeSpan.FromMilliseconds(100)) { } /// The hot-reload options. /// Where unloads that do not finish are reported; null logs nothing. /// The pause after the first collection; each next one doubles, up to five seconds. internal ModuleContextMonitor(HotReloadOptions options, ILogger? logger, TimeSpan firstPause) { _options = options; _logger = logger ?? NullLogger.Instance; _firstPause = firstPause; } /// /// Module load contexts in memory: the live modules, the rollback history, the orphaned ones and the ones still /// unloading. /// public int ModuleContextsAlive => ModuleAssemblyLoadContext.InMemory().Count; /// /// Module load contexts in memory that Tsak let go: not collectible, or collectible and still alive after the /// collections of their check. /// public int OrphanedModuleContexts => ModuleAssemblyLoadContext.InMemory() .Count(c => c.ReleasedAtUtc is not null && (!c.IsCollectible || c.OutlivedUnload)); /// The limit above which the node should be restarted (). public int MaxOrphanedContexts => _options.EffectiveMaxOrphanedContexts; /// What to do about the orphaned contexts: null within the limit, the restart advice above it. public string? Notice { get { var orphaned = OrphanedModuleContexts; return orphaned > MaxOrphanedContexts ? Describe(orphaned) : null; } } /// /// Checks the contexts let go since the last check, in the background. Calls while a check runs fold into one more /// round after it, so a series of swaps costs one check at a time. /// public void ScheduleCheck() { lock (_gate) { if (_checking) { _again = true; return; } _checking = true; _running = Task.Run(RunAsync); } } /// For tests: schedules a check and returns the task that ends when no check is left. internal Task CheckAsync() { ScheduleCheck(); lock (_gate) return _running; } private async Task RunAsync() { while (true) { try { await CheckOnceAsync().ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "HotReload: the unload check of module contexts failed"); } lock (_gate) { if (!_again) { _checking = false; return; } _again = false; } } } private async Task CheckOnceAsync() { var released = TakeReleased(); if (released.Count > 0) { var pause = _firstPause; for (var round = 1; round <= Collections && released.Exists(r => r.Context.IsAlive); round++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (round < Collections && released.Exists(r => r.Context.IsAlive)) { await Task.Delay(pause).ConfigureAwait(false); pause = pause * 2 < LongestPause ? pause * 2 : LongestPause; } } MarkOutlived(released); } ReportLimit(); } /// /// Out of line, so no local of the async check roots a context: only weak references leave this method. /// [MethodImpl(MethodImplOptions.NoInlining)] private static List<(string Name, WeakReference Context)> TakeReleased() { var released = new List<(string, WeakReference)>(); foreach (var context in ModuleAssemblyLoadContext.InMemory()) { if (!context.IsCollectible || context.ReleasedAtUtc is null || context.UnloadChecked) continue; context.UnloadChecked = true; released.Add((context.Name ?? "", new WeakReference(context))); } return released; } [MethodImpl(MethodImplOptions.NoInlining)] private void MarkOutlived(List<(string Name, WeakReference Context)> released) { foreach (var (name, reference) in released) { if (reference.Target is not ModuleAssemblyLoadContext context) continue; context.OutlivedUnload = true; _logger.LogWarning( "HotReload: module context {Name} still alive after {Collections} collections: something outside the " + "module still refers to it, and its memory stays until the node restarts", name, Collections); } } /// Warns once each time the orphaned count grows above the limit. private void ReportLimit() { var orphaned = OrphanedModuleContexts; var reported = Volatile.Read(ref _reportedOrphaned); if (orphaned > MaxOrphanedContexts && orphaned > reported) _logger.LogWarning("HotReload: {Notice}", Describe(orphaned)); Volatile.Write(ref _reportedOrphaned, orphaned); } private string Describe(int orphaned) => $"{orphaned} module context(s) stay in memory after their modules were replaced or removed " + $"(limit {MaxOrphanedContexts}): {RestartAdvice}"; } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleLoadGate.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/Modules/ModuleLoadGate.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Modules; /// /// The ONE load-boundary trust gate for module code (review 2026-09-02, К3). Before this class the /// signature check lived only inside HotReloadService's scan, so startup discovery executed .tpkg /// packages unverified after every process restart, and a bare .dll dropped into a watched /// directory bypassed the gate entirely. Every path that is about to load module code — startup /// discovery, hot-reload scans, staged validation, package reloads — must go through here. /// /// returns the verified BYTES, and the caller opens the package /// from that buffer (ModulePackage.Open(byte[], ...)) — verifying a path and then /// re-reading the file gave an attacker a swap window between the check and the load. /// /// public sealed class ModuleLoadGate { private readonly ILogger _logger; public bool SignatureRequired { get; } private readonly ModuleSignatureVerifier? _verifier; public ModuleLoadGate(IConfiguration configuration, ILogger logger) { _logger = logger; var sigOptions = new ModuleSignatureOptions(); configuration.GetSection("Tsak:Modules:Signature").Bind(sigOptions); SignatureRequired = sigOptions.Required; var pem = sigOptions.ResolvePem(); _verifier = pem is not null ? new ModuleSignatureVerifier(pem) : null; if (SignatureRequired && _verifier is null) _logger.LogError( "Tsak:Modules:Signature:Required=true but no public key is configured — ALL .tpkg packages " + "will be refused at load. Set Tsak:Modules:Signature:PublicKeyPath."); else if (SignatureRequired) _logger.LogInformation("Module signature enforcement ON — unsigned/tampered packages and bare DLLs will be refused"); } /// /// Reads a .tpkg and, when enforcement is on, verifies its detached .sig. /// Returns the package bytes to load from, or null when the package must be refused /// (missing file, missing/invalid signature, no key configured). /// public byte[]? ReadVerifiedTpkg(string tpkgPath) { byte[] pkg; try { pkg = File.ReadAllBytes(tpkgPath); } catch (Exception ex) { _logger.LogWarning(ex, "Could not read package {Pkg}", Path.GetFileName(tpkgPath)); return null; } if (!SignatureRequired) return pkg; if (_verifier is null) { _logger.LogError("Refusing {Pkg}: signature required but no public key configured", Path.GetFileName(tpkgPath)); return null; } var sigPath = tpkgPath + ".sig"; if (!File.Exists(sigPath)) { _logger.LogError("Refusing {Pkg}: no signature file ({Sig}) alongside the package", Path.GetFileName(tpkgPath), Path.GetFileName(sigPath)); return null; } try { var sig = File.ReadAllBytes(sigPath); if (_verifier.VerifyWithEncodedSignature(pkg, sig)) return pkg; _logger.LogError("Refusing {Pkg}: signature verification FAILED — unsigned by the trusted key or modified", Path.GetFileName(tpkgPath)); return null; } catch (Exception ex) { _logger.LogError(ex, "Refusing {Pkg}: signature check errored", Path.GetFileName(tpkgPath)); return null; } } /// /// A bare .dll carries no manifest and no detached signature, so with enforcement on it is /// refused outright — otherwise dropping Evil.dll into a watched directory executes arbitrary /// code the .tpkg signature feature claims to prevent. Package deployments (.tpkg + .sig) are /// the supported shape under enforcement. /// public bool AllowBareDll(string dllPath) { if (!SignatureRequired) return true; // The scan revisits the same files every interval — log the refusal once per path, // not once per scan. if (_refusalLogged.TryAdd(dllPath, 0)) _logger.LogCritical( "Refusing bare assembly {Dll}: Tsak:Modules:Signature:Required=true admits only signed .tpkg packages " + "— a bare DLL cannot carry a signature. Package it as a signed .tpkg.", Path.GetFileName(dllPath)); return false; } private readonly ConcurrentDictionary _refusalLogged = new(StringComparer.OrdinalIgnoreCase); } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleManifest.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/Modules/ModuleManifest.cs ---- using System.Text.Json.Serialization; namespace redb.Tsak.Core.Modules; /// /// Manifest embedded in a .tpkg package (manifest.json). /// Package metadata: Name, Version (informational for logs), EntryPoints, Dependencies. /// Module configuration (ContextName, settings) lives in {Name}.config.json. /// XML route artifacts (Route-XML Ф5.1) ride in the same package as a third artifact type: /// is the explicit ordered list of .route.xml entries, /// the in-package directory file-references resolve from, and /// the configuration keys the module fails fast on when the /// merged context configuration provides no value. All four are optional — a package without /// them behaves exactly as before. /// public sealed class ModuleManifest { [JsonPropertyName("Name")] public string Name { get; set; } = ""; [JsonPropertyName("Version")] public string Version { get; set; } = "1.0.0"; [JsonPropertyName("EntryPoints")] public List EntryPoints { get; set; } = []; [JsonPropertyName("Dependencies")] public List Dependencies { get; set; } = []; /// Explicit ordered list of XML route artifacts inside the package (e.g. "routes/orders.route.xml"). [JsonPropertyName("Artifacts")] public List Artifacts { get; set; } = []; /// Route-format version the artifacts were packaged for; the loader refuses a newer one with a clear message. [JsonPropertyName("SchemaVersion")] public string? SchemaVersion { get; set; } /// In-package directory the artifacts' file references (XSLT, schemas) resolve from. [JsonPropertyName("Resources")] public string Resources { get; set; } = "resources"; /// Configuration keys ({{key}} without a default) the module requires from the merged context configuration. [JsonPropertyName("RequiredConfigKeys")] public List RequiredConfigKeys { get; set; } = []; } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModulePackage.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/Modules/ModulePackage.cs ---- using System.IO.Compression; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Text.Json; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Modules; /// /// Loads a .tpkg (ZIP archive) containing manifest.json + module DLLs + per-module config. /// Each package gets its own : entry point DLLs are /// loaded into the package ALC (isolating module code), while companion DLLs go through /// into the Default ALC (shared across packages). /// Like WSO2 MI CAR files — drop into Libs/, auto-discovered and hot-reloaded. /// public sealed class ModulePackage : IDisposable { private readonly ILogger? _logger; public ModuleManifest Manifest { get; } public string PackagePath { get; } public DateTime LastWriteUtc { get; } /// /// The isolated ALC owning this package's entry point assemblies. /// Null only for legacy callers that don't pass collectible. /// Call to unload (if collectible). /// public ModuleAssemblyLoadContext? Alc { get; private set; } /// Entry point assemblies loaded into for module discovery. public List LoadedAssemblies { get; } = []; /// Companion (non-entry-point) assemblies loaded into Default ALC via Tracker. public List CompanionAssemblies { get; } = []; /// /// XML route artifacts (Route-XML Ф5.1), read during /// from the SAME verified bytes the signature gate checked — never re-read from disk. /// Order follows . Empty for packages without artifacts. /// public IReadOnlyList<(string Name, string Content)> XmlArtifacts => _xmlArtifacts; private readonly List<(string Name, string Content)> _xmlArtifacts = []; /// /// The package's directory on disk ({PackageRoot}/resources): the /// resources are extracted with their paths inside the package, since artifact file-references need real file paths /// (the rest of the package is never unpacked). Null when the package carries no XML artifacts. /// public string? ResourcesRoot { get; private set; } /// /// The directory the resources were extracted under, laid out as the package is: a reference written from the package /// root (file="resources/order.xsd", the project's own layout) resolves here, one written from the resources /// directory (file="order.xsd") resolves under . Deleted by . /// public string? PackageRoot { get; private set; } /// The package's context.xml content, when the package carries one (read in Open). public string? ContextXml { get; private set; } private ModulePackage(ModuleManifest manifest, string packagePath, DateTime lastWriteUtc, ILogger? logger) { Manifest = manifest; PackagePath = packagePath; LastWriteUtc = lastWriteUtc; _logger = logger; } /// /// Opens a .tpkg file, reads manifest, loads ALL DLLs from the archive. /// Companion DLLs are loaded before entry points so dependencies resolve correctly. /// Returns null if the file is not a valid .tpkg. /// /// The .tpkg file. /// Further folders the package's assemblies are resolved from. /// Where loading is reported; null logs nothing. /// /// When true, companion assemblies are force-replaced in the tracker /// (hot-reload scenario: shared dependency DLL was updated). /// Entry points are always loaded fresh into a new ALC. /// When false (default / first load), existing tracked companions are reused. /// /// /// When true, the package ALC is collectible (supports Unload). /// When false (default), the ALC stays in memory but is compatible with Emit-based APIs. /// public static ModulePackage? Open(string tpkgPath, string[]? probePaths = null, ILogger? logger = null, bool forceReload = false, bool collectible = false) { if (!File.Exists(tpkgPath)) return null; try { // Read once and open from the buffer — the same bytes a signature gate may have // verified must be the bytes that get loaded (review 2026-09-02, К3: the old // verify-then-reopen let the file be swapped between the check and the load). var bytes = File.ReadAllBytes(tpkgPath); return Open(bytes, tpkgPath, File.GetLastWriteTimeUtc(tpkgPath), probePaths, logger, forceReload, collectible); } catch (Exception ex) { logger?.LogError(ex, "Failed to open package {Path}", tpkgPath); return null; } } /// /// Reads only the manifest from a package's bytes, without loading any assembly. The hot-reload /// scan uses it to order packages by before it commits to /// reloading them. Returns null when the bytes are not a readable package. /// internal static ModuleManifest? TryReadManifest(byte[] packageBytes) { try { using var zip = new ZipArchive(new MemoryStream(packageBytes), ZipArchiveMode.Read); var manifestEntry = zip.GetEntry("manifest.json"); if (manifestEntry is null) return null; using var stream = manifestEntry.Open(); return JsonSerializer.Deserialize(stream); } catch { return null; } } /// /// Opens a .tpkg from an in-memory buffer (the caller verified these exact bytes). /// loads companion DLLs into the package's own ALC /// instead of publishing them to the process-wide tracker — for staged validation, whose /// probe must not leak a rejected package's dependencies into the Default ALC /// (review 2026-09-02, С23). /// public static ModulePackage? Open( byte[] packageBytes, string tpkgPath, DateTime lastWriteUtc, string[]? probePaths = null, ILogger? logger = null, bool forceReload = false, bool collectible = false, bool isolatedCompanions = false) { try { var lastWrite = lastWriteUtc; using var zip = new ZipArchive(new MemoryStream(packageBytes), ZipArchiveMode.Read); // Read manifest var manifestEntry = zip.GetEntry("manifest.json"); if (manifestEntry is null) { logger?.LogWarning("No manifest.json in {Path}, skipping", tpkgPath); return null; } ModuleManifest manifest; using (var stream = manifestEntry.Open()) { manifest = JsonSerializer.Deserialize(stream) ?? throw new InvalidDataException("Failed to deserialize manifest.json"); } if (string.IsNullOrWhiteSpace(manifest.Name)) { logger?.LogWarning("Manifest in {Path} has no Name, skipping", tpkgPath); return null; } var package = new ModulePackage(manifest, tpkgPath, lastWrite, logger); LoadedAssemblyTracker.EnsureResolverRegistered(); // Create per-package ALC for entry point isolation var alcName = $"pkg:{manifest.Name}"; var alc = new ModuleAssemblyLoadContext(alcName, probePaths, collectible); package.Alc = alc; var entryPointSet = new HashSet(manifest.EntryPoints, StringComparer.OrdinalIgnoreCase); // Phase 1: Load companion DLLs (non-entry-point) so dependencies are available foreach (var entry in zip.Entries) { if (!entry.FullName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) continue; if (entryPointSet.Contains(entry.FullName)) continue; try { using var dllStream = entry.Open(); using var memStream = new MemoryStream(); dllStream.CopyTo(memStream); var bytes = memStream.ToArray(); Assembly assembly; if (isolatedCompanions) { // Validation probe: keep the companion inside the throwaway ALC. memStream.Position = 0; assembly = alc.LoadFromStream(memStream); } else { var asmName = GetAssemblyNameFromBytes(bytes); assembly = forceReload ? LoadedAssemblyTracker.Replace(asmName, bytes) : LoadedAssemblyTracker.LoadOrReuse(asmName, bytes, logger); } package.CompanionAssemblies.Add(assembly); logger?.LogDebug("Loaded companion {DLL} from package {Name} (reused={Reused}, isolated={Isolated})", entry.FullName, manifest.Name, !forceReload, isolatedCompanions); } catch (Exception ex) { logger?.LogWarning(ex, "Failed to load companion {DLL} from package {Name}", entry.FullName, manifest.Name); } } // Phase 2: Load entry point DLLs into the package's isolated ALC. // Entry points always get a fresh load (per-package ALC is new). // NOT tracked in LoadedAssemblyTracker — entry points are isolated per-package. // If package B needs code from package A's entry point, it should declare // that as a companion (shared) dependency, not an entry point. foreach (var entryPoint in manifest.EntryPoints) { var dllEntry = zip.GetEntry(entryPoint); if (dllEntry is null) { logger?.LogWarning("Entry point {EP} not found in {Path}", entryPoint, tpkgPath); continue; } using var dllStream = dllEntry.Open(); using var memStream = new MemoryStream(); dllStream.CopyTo(memStream); memStream.Position = 0; // Load into package ALC (isolated entry point code) var assembly = alc.LoadFromStream(memStream); package.LoadedAssemblies.Add(assembly); logger?.LogInformation("Loaded entry point {EP} from package {Name} into ALC {Alc}", entryPoint, manifest.Name, alcName); } // The module's type resolver searches the companions too, though they live in the Default context. Isolated // companions live in this context and are found among its own assemblies: a context must not hold its own // assemblies, or the runtime's handle on an unloading context and the assemblies keep each other alive. alc.Companions = isolatedCompanions ? [] : package.CompanionAssemblies; // Its manifest's Dependencies order the contexts of the package's modules at start. alc.Manifest = manifest; if (package.CompanionAssemblies.Count > 0) logger?.LogInformation("Package {Name}: {EP} entry points, {Comp} companion DLLs loaded", manifest.Name, package.LoadedAssemblies.Count, package.CompanionAssemblies.Count); // XML route artifacts (Route-XML Ф5): read from the verified zip in manifest order, // and extract the resources directory so file-references resolve to real paths. if (manifest.Artifacts.Count > 0) package.ReadXmlArtifacts(zip, logger); return package; } catch (Exception ex) { logger?.LogError(ex, "Failed to open package {Path}", tpkgPath); return null; } } /// /// Reads the per-module config ({moduleName}.config.json) from the package as raw JSON string. /// Returns null if no config for this module is embedded in the package. /// public string? ReadModuleConfigJson(string moduleName) { try { using var zip = ZipFile.OpenRead(PackagePath); var configEntry = zip.GetEntry($"{moduleName}.config.json"); if (configEntry is null) return null; using var reader = new StreamReader(configEntry.Open()); return reader.ReadToEnd(); } catch (Exception ex) { _logger?.LogWarning(ex, "Failed to read config for module {Module} from {Path}", moduleName, PackagePath); return null; } } private void ReadXmlArtifacts(ZipArchive zip, ILogger? logger) { // The optional context.xml at the package root (Route-XML Ф5.1 layout): context-level // sections — components, beans, onInit, package blocks like — applied by // XmlRouteModule BEFORE the route artifacts, from the same verified bytes. if (zip.GetEntry("context.xml") is { } contextEntry) { using var contextReader = new StreamReader(contextEntry.Open()); ContextXml = contextReader.ReadToEnd(); } foreach (var artifact in Manifest.Artifacts) { var entry = zip.GetEntry(artifact.Replace('\\', '/')); if (entry is null) { // The packaging gate guarantees presence; a hand-edited manifest may not. // Recorded as a missing artifact — XmlRouteModule fails initialization loudly. logger?.LogError("Package {Name}: artifact {Artifact} listed in the manifest is not in the package", Manifest.Name, artifact); continue; } using var reader = new StreamReader(entry.Open()); _xmlArtifacts.Add((artifact, reader.ReadToEnd())); } var resourcesPrefix = Manifest.Resources.Trim('/') + "/"; var resourceEntries = zip.Entries .Where(e => e.FullName.Replace('\\', '/').StartsWith(resourcesPrefix, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(e.Name)) .ToList(); // A per-INSTANCE directory, not a per-content one. Several ModulePackage instances of the // same file are alive at once by design (registry discovery + the hot-reload tracker + the // staged-validation probe), and a content-keyed path made them share one directory — the // probe's Dispose deleted the resources out from under the live module (такт 5 E2E find). var root = Path.Combine(Path.GetTempPath(), "tsak-pkg", $"{Manifest.Name}-{Guid.NewGuid().ToString("N")[..16]}"); Directory.CreateDirectory(root); foreach (var entry in resourceEntries) { // Kept under its path in the package (resources/...), so both forms of a reference resolve, as in the project. var relative = entry.FullName.Replace('\\', '/'); var target = Path.GetFullPath(Path.Combine(root, relative)); if (!target.StartsWith(root, StringComparison.OrdinalIgnoreCase)) { logger?.LogError("Package {Name}: resource entry {Entry} escapes the resources directory — skipped", Manifest.Name, entry.FullName); continue; } Directory.CreateDirectory(Path.GetDirectoryName(target)!); entry.ExtractToFile(target, overwrite: true); } PackageRoot = root; ResourcesRoot = Path.Combine(root, resourcesPrefix.TrimEnd('/')); Directory.CreateDirectory(ResourcesRoot); logger?.LogInformation("Package {Name}: {Artifacts} XML artifact(s), {Resources} resource file(s) → {Root}", Manifest.Name, _xmlArtifacts.Count, resourceEntries.Count, ResourcesRoot); } public void Dispose() { Alc?.TryUnload(); Alc = null; if (PackageRoot is { } root) { PackageRoot = null; ResourcesRoot = null; try { Directory.Delete(root, recursive: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { _logger?.LogWarning(ex, "Package {Name}: could not delete extracted resources at {Root}", Manifest.Name, root); } } } /// /// Reads assembly name from raw bytes without loading the assembly into the runtime. /// private static string GetAssemblyNameFromBytes(byte[] bytes) { using var stream = new MemoryStream(bytes); using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var assemblyDef = metadataReader.GetAssemblyDefinition(); return metadataReader.GetString(assemblyDef.Name); } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleSchemeWarmup.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/Modules/ModuleSchemeWarmup.cs ---- using System.Reflection; using System.Runtime.Loader; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Attributes; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Modules; /// /// Puts the redb schemes a module reads into the process's scheme cache before the module starts, reading them from /// the database and changing nothing there. /// /// IRedbService.InitializeAsync runs before modules load and looks for [RedbScheme] types in the default /// load context only, where a module's own assembly never is. A module that syncs its schemes fills the cache itself; /// one that only reads schemes another process owns (one worker syncs, the others read) would meet every scheme on /// its first query: a lookup in the database on a blocked thread. Here they are read once, up front. /// /// /// A scheme the database does not hold yet is skipped: the module that owns it creates it. A failure is logged and /// the module starts anyway: the scheme is then read on its first query, as before. /// /// internal static class ModuleSchemeWarmup { /// Reads into the cache the schemes of every [RedbScheme] type of . public static async Task WarmAsync(IRedbService redb, IEnumerable modules, ILogger logger, CancellationToken ct = default) { foreach (var module in modules) { var types = SchemeTypes(module).ToList(); if (types.Count == 0) continue; var cached = 0; try { foreach (var type in types) { ct.ThrowIfCancellationRequested(); if (await redb.GetSchemeByTypeAsync(type, ct).ConfigureAwait(false) is not null) cached++; } } catch (Exception ex) when (ex is not OperationCanceledException) { logger.LogWarning(ex, "Module {Module}: could not read its redb schemes ahead of start; each is read on its first query instead", module.ModuleName); continue; } logger.LogDebug("Module {Module}: {Cached} of {Total} redb schemes read into the cache ahead of start", module.ModuleName, cached, types.Count); } } /// /// The [RedbScheme] types of the module's assembly and of the assemblies it references directly (a domain /// library beside the module), loaded through the module's own load context. /// internal static IEnumerable SchemeTypes(ITsakModule module) { var entry = module switch { StaticMethodModule m => m.ModuleAssembly, RouteBuilderModule m => m.ModuleAssembly, _ => null, }; if (entry is null) return []; var assemblies = new List { entry }; var loadContext = AssemblyLoadContext.GetLoadContext(entry) ?? AssemblyLoadContext.Default; foreach (var reference in entry.GetReferencedAssemblies()) { if (IsFramework(reference.Name)) continue; try { assemblies.Add(loadContext.LoadFromAssemblyName(reference)); } catch (Exception) { // A reference the module never loads (an optional dependency) holds no scheme it reads. } } return assemblies.Distinct().SelectMany(TypesWithScheme).Distinct(); } private static bool IsFramework(string? name) => name is null || name.StartsWith("System", StringComparison.Ordinal) || name.StartsWith("Microsoft.", StringComparison.Ordinal) || name is "netstandard" or "mscorlib"; private static IEnumerable TypesWithScheme(Assembly assembly) { Type?[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } catch (Exception) { return []; } return types.Where(t => t is not null && t.GetCustomAttribute() is not null)!; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleSignatureVerifier.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/Modules/ModuleSignatureVerifier.cs ---- using System.Security.Cryptography; using redb.Route.Serialization; namespace redb.Tsak.Core.Modules; /// /// Verifies a detached signature over a .tpkg package against a configured public key. /// /// This is the trust anchor for module deployment: the signature is checked at the load /// boundary (before any code from the package runs), so the public key — not "who wrote the /// file" — decides what may execute. It covers both API uploads and files dropped into the module /// directory, and uses only the BCL ( / ) — no external tool, /// no cosign dependency. /// /// /// Signing (in CI) is a SHA-256 signature over the raw .tpkg bytes with the matching private /// key; the signature travels next to the package as {name}.tpkg.sig (base64 or raw bytes). /// Both RSA (PKCS#1 v1.5) and ECDSA are accepted — the key type is inferred from the PEM. /// /// public sealed class ModuleSignatureVerifier { private readonly string _publicKeyPem; public ModuleSignatureVerifier(string publicKeyPem) { if (string.IsNullOrWhiteSpace(publicKeyPem)) throw new ArgumentException("Public key PEM is required.", nameof(publicKeyPem)); _publicKeyPem = publicKeyPem; } /// /// Loads a verifier from a PEM public key file, or returns null when the path is unset — /// signaling "no key configured". /// public static ModuleSignatureVerifier? FromKeyFile(string? publicKeyPath) { if (string.IsNullOrWhiteSpace(publicKeyPath)) return null; if (!File.Exists(publicKeyPath)) throw new FileNotFoundException($"Module signing public key not found: {publicKeyPath}"); return new ModuleSignatureVerifier(File.ReadAllText(publicKeyPath)); } /// /// Verifies over . Returns /// false on any mismatch or malformed input — never throws for a bad signature, so a /// forged upload is a clean rejection, not a crash. /// public bool Verify(byte[] packageBytes, byte[] signature) { if (packageBytes is null || packageBytes.Length == 0) return false; if (signature is null || signature.Length == 0) return false; // Try RSA first, then ECDSA — the PEM importer accepts either; we don't know a priori. try { using var rsa = RSA.Create(); rsa.ImportFromPem(_publicKeyPem); return rsa.VerifyData(packageBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } catch (CryptographicException) { /* not an RSA key — fall through */ } catch (ArgumentException) { /* malformed signature for RSA — fall through */ } try { using var ecdsa = ECDsa.Create(); ecdsa.ImportFromPem(_publicKeyPem); return ecdsa.VerifyData(packageBytes, signature, HashAlgorithmName.SHA256); } catch (CryptographicException) { return false; } catch (ArgumentException) { return false; } } /// /// Reads a signature that may be stored as base64 text or as raw signature bytes and verifies it. /// public bool VerifyWithEncodedSignature(byte[] packageBytes, byte[] signatureFileBytes) { if (signatureFileBytes is null || signatureFileBytes.Length == 0) return false; // Prefer base64 (how CI/openssl usually emit .sig); fall back to raw bytes. try { var text = System.Text.Encoding.ASCII.GetString(signatureFileBytes).Trim(); var decoded = Base64Text.Decode(text); if (Verify(packageBytes, decoded)) return true; } catch (FormatException) { /* not base64 — try raw */ } return Verify(packageBytes, signatureFileBytes); } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleTypeResolver.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/Modules/ModuleTypeResolver.cs ---- using System.Reflection; using System.Runtime.Loader; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Modules; /// /// The of a module's route context: a type name (bean:, <bean class>, /// the SQL outputClass) resolves to the module's own class first, then, as before, through the process /// (). Apache Camel's ClassResolver under OSGi works the same way: the bundle's /// class loader before the platform's. /// /// Searching the process first picked whichever assembly of the name loaded first: after a module was reloaded /// under the same name, its previous version (still loaded when the load context is not collectible); with a host /// or another module declaring a class of the same name, theirs. /// /// internal sealed class ModuleTypeResolver : IBeanTypeResolver { private readonly Assembly[] _moduleAssemblies; internal ModuleTypeResolver(IEnumerable moduleAssemblies) => _moduleAssemblies = moduleAssemblies.Distinct().ToArray(); /// The module code searched first, in order. internal IReadOnlyList ModuleAssemblies => _moduleAssemblies; /// /// The resolver of a context that runs : the assemblies of their packages, or of their /// load contexts, or, for a module of the Default context, its own assembly. /// internal static ModuleTypeResolver For(IEnumerable modules) => new(modules.SelectMany(AssembliesOf)); private static IEnumerable AssembliesOf(ITsakModule module) { if (module is XmlRouteModule xml) return xml.PackageAssemblies; var assembly = module.GetType().Assembly; return AssemblyLoadContext.GetLoadContext(assembly) switch { ModuleAssemblyLoadContext own => own.Assemblies.Concat(own.Companions), { } other when other != AssemblyLoadContext.Default => other.Assemblies, _ => [assembly], }; } /// public Type? Resolve(string typeName) { ArgumentException.ThrowIfNullOrWhiteSpace(typeName); var comma = typeName.IndexOf(','); var fullName = (comma >= 0 ? typeName[..comma] : typeName).Trim(); var assemblyName = comma >= 0 ? typeName[(comma + 1)..].Split(',')[0].Trim() : null; foreach (var assembly in _moduleAssemblies) { if (assemblyName is not null && !string.Equals(assembly.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase)) continue; if (assembly.GetType(fullName, throwOnError: false) is { } type) return type; } return DefaultBeanTypeResolver.Instance.Resolve(typeName); } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleUploadOptions.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/Modules/ModuleUploadOptions.cs ---- namespace redb.Tsak.Core.Modules; /// /// Deployment security options, bound from Tsak:Modules. /// /// A module is executable code that Tsak loads in-process, so every default here is the safe one: /// remote upload is off, and when signature enforcement is on, unsigned or tampered packages /// are refused at the load boundary regardless of how they arrived. /// /// public sealed class ModuleUploadOptions { /// /// Enables POST /api/modules/upload and /rollback. Default: false. A node /// that does not need remote deploy exposes no upload surface at all. /// public bool Enabled { get; set; } /// Maximum accepted .tpkg size in MB. Default: 100. public int MaxSizeMB { get; set; } = 100; /// /// Directory the uploaded package is written to (must be one of Tsak:Modules:AssemblyPaths /// so the hot-reload scanner picks it up). When unset, the first configured assembly path is used. /// public string? TargetPath { get; set; } /// /// Previous package versions to keep on disk for rollback ({name}.tpkg.v{n}). Default: 3. /// public int KeepVersions { get; set; } = 3; /// /// Require a valid signature for uploads even when no public key is configured to be impossible — /// i.e. when true and no key is set, uploads are refused. When false, an upload with /// no configured key is allowed but logged as a loud warning. Default: true (safe). /// public bool RequireSignatureForUpload { get; set; } = true; } /// /// Signature-enforcement options, bound from Tsak:Modules:Signature. Governs the load /// boundary — applies to every .tpkg, whether uploaded via API or dropped into the /// directory by an operator. /// public sealed class ModuleSignatureOptions { /// /// Reject any .tpkg without a valid .tpkg.sig at load time. Default: false /// (trust = filesystem access, the historical behaviour). Turn this on together with remote /// upload so a leaked API key cannot deploy arbitrary code. /// public bool Required { get; set; } /// Path to the PEM public key used to verify package signatures. public string? PublicKeyPath { get; set; } /// Inline PEM public key (alternative to ). public string? PublicKeyPem { get; set; } /// Resolves the configured PEM from inline value or file, or null when unset. public string? ResolvePem() { if (!string.IsNullOrWhiteSpace(PublicKeyPem)) return PublicKeyPem; if (!string.IsNullOrWhiteSpace(PublicKeyPath) && File.Exists(PublicKeyPath)) return File.ReadAllText(PublicKeyPath); return null; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleUploadService.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/Modules/ModuleUploadService.cs ---- using System.IO.Compression; using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Modules; /// Outcome of an upload or rollback attempt. public sealed record ModuleDeployResult(bool Success, string Message, string? ModuleName = null, string? Version = null); /// /// Handles remote module deployment: validates and installs an uploaded .tpkg, and rolls a /// module back to its previous on-disk version. Every defense lives here, so the controller stays /// thin: /// /// upload disabled unless Tsak:Modules:Upload:Enabled=true; /// size ceiling; /// the bytes must be a valid ZIP containing manifest.json with a name; /// the stored filename is derived from the manifest name and sanitized — never from client /// input — so a crafted name cannot escape the target directory (zip-slip / path traversal); /// signature verified before anything touches the live directory (fail-fast), in /// addition to the authoritative load-boundary check in HotReloadService; /// atomic install (temp file → move), with the previous version archived for rollback. /// /// public sealed class ModuleUploadService { private readonly ModuleUploadOptions _options; private readonly ModuleSignatureOptions _signature; private readonly IConfiguration _configuration; private readonly ILogger _logger; public ModuleUploadService( ModuleUploadOptions options, ModuleSignatureOptions signature, IConfiguration configuration, ILogger logger) { _options = options; _signature = signature; _configuration = configuration; _logger = logger; } public bool UploadEnabled => _options.Enabled; /// /// Validates and installs an uploaded package. is the detached /// signature (base64 or raw); may be null when signing is not enforced. /// public async Task InstallAsync(byte[] packageBytes, byte[]? signatureBytes, CancellationToken ct) { if (!_options.Enabled) return new ModuleDeployResult(false, "Module upload is disabled (Tsak:Modules:Upload:Enabled=false)."); // 1. Size ceiling — reject before doing any work. var maxBytes = (long)_options.MaxSizeMB * 1024 * 1024; if (packageBytes is null || packageBytes.Length == 0) return new ModuleDeployResult(false, "Empty upload."); if (packageBytes.Length > maxBytes) return new ModuleDeployResult(false, $"Package exceeds the {_options.MaxSizeMB} MB limit."); // 2. Signature — fail fast before the package reaches the live directory. var sigResult = VerifySignature(packageBytes, signatureBytes); if (!sigResult.ok) return new ModuleDeployResult(false, sigResult.message); // 3. Structural validation — must be a valid ZIP with a named manifest. string moduleName; string? version; try { (moduleName, version) = ReadManifest(packageBytes); } catch (Exception ex) { return new ModuleDeployResult(false, $"Invalid package: {ex.Message}"); } // 4. Sanitize the stored name — derived from the manifest, never from a client filename. var safeName = SanitizeName(moduleName); if (safeName is null) return new ModuleDeployResult(false, $"Unsafe module name in manifest: '{moduleName}'."); // 5. Resolve and confine the target directory. var targetDir = ResolveTargetDir(); if (targetDir is null) return new ModuleDeployResult(false, "No module directory configured (Tsak:Modules:AssemblyPaths)."); Directory.CreateDirectory(targetDir); var finalPath = Path.Combine(targetDir, safeName + ".tpkg"); var finalFull = Path.GetFullPath(finalPath); if (!finalFull.StartsWith(Path.GetFullPath(targetDir) + Path.DirectorySeparatorChar, StringComparison.Ordinal)) return new ModuleDeployResult(false, "Resolved path escapes the module directory."); // belt-and-braces try { // 6. Archive the current version for rollback, then atomically install. ArchivePrevious(finalFull, safeName, targetDir); var tempPath = finalFull + ".uploading"; await File.WriteAllBytesAsync(tempPath, packageBytes, ct).ConfigureAwait(false); if (signatureBytes is { Length: > 0 }) await File.WriteAllBytesAsync(finalFull + ".sig", signatureBytes, ct).ConfigureAwait(false); // Move is atomic on the same volume; overwrite the live file in one step. File.Move(tempPath, finalFull, overwrite: true); _logger.LogInformation("Module '{Name}' (v{Version}) installed to {Path}", safeName, version, finalFull); return new ModuleDeployResult(true, "Package installed. Hot-reload will load it within the scan interval.", safeName, version); } catch (Exception ex) { // Detail to the log, generic message to the client (review item 4.7) — the exception text // can carry internal paths / config and should not leak over the API. _logger.LogError(ex, "Failed to install module '{Name}'", safeName); return new ModuleDeployResult(false, "Install failed. See server logs for details."); } } /// /// Dry-run validation of an uploaded package — same structural + signature checks as /// , but nothing is written. Lets CI verify a package (size, valid ZIP, /// manifest, name, signature) before deploying it. Does NOT load the assemblies; the load-time /// staged check in HotReloadService covers that on actual install. /// public ModuleDeployResult Validate(byte[] packageBytes, byte[]? signatureBytes) { if (!_options.Enabled) return new ModuleDeployResult(false, "Module upload is disabled."); var maxBytes = (long)_options.MaxSizeMB * 1024 * 1024; if (packageBytes is null || packageBytes.Length == 0) return new ModuleDeployResult(false, "Empty package."); if (packageBytes.Length > maxBytes) return new ModuleDeployResult(false, $"Package exceeds the {_options.MaxSizeMB} MB limit."); var sig = VerifySignature(packageBytes, signatureBytes); if (!sig.ok) return new ModuleDeployResult(false, sig.message); try { var (name, version) = ReadManifest(packageBytes); if (SanitizeName(name) is null) return new ModuleDeployResult(false, $"Unsafe module name in manifest: '{name}'."); return new ModuleDeployResult(true, "Package is valid.", name, version); } catch (Exception ex) { return new ModuleDeployResult(false, $"Invalid package: {ex.Message}"); } } /// Restores the most recent archived version of a module. public ModuleDeployResult Rollback(string moduleName) { if (!_options.Enabled) return new ModuleDeployResult(false, "Module upload is disabled."); var safeName = SanitizeName(moduleName); if (safeName is null) return new ModuleDeployResult(false, $"Unsafe module name: '{moduleName}'."); var targetDir = ResolveTargetDir(); if (targetDir is null) return new ModuleDeployResult(false, "No module directory configured."); var live = Path.Combine(targetDir, safeName + ".tpkg"); var versions = Directory.GetFiles(targetDir, safeName + ".tpkg.v*") .OrderByDescending(f => f) // v-numbers are zero-padded so lexical == numeric .ToList(); if (versions.Count == 0) return new ModuleDeployResult(false, $"No previous version archived for '{safeName}'."); var previous = versions[0]; try { File.Copy(previous, live, overwrite: true); var sig = previous + ".sig"; if (File.Exists(sig)) File.Copy(sig, live + ".sig", overwrite: true); File.Delete(previous); if (File.Exists(sig)) File.Delete(sig); _logger.LogWarning("Module '{Name}' rolled back to {Previous}", safeName, Path.GetFileName(previous)); return new ModuleDeployResult(true, "Rolled back to the previous version.", safeName); } catch (Exception ex) { _logger.LogError(ex, "Failed to roll back module '{Name}'", safeName); return new ModuleDeployResult(false, "Rollback failed. See server logs for details."); } } // ── internals ──────────────────────────────────────────────────── private (bool ok, string message) VerifySignature(byte[] packageBytes, byte[]? signatureBytes) { var pem = _signature.ResolvePem(); if (pem is not null) { if (signatureBytes is null || signatureBytes.Length == 0) return (false, "A signature is required (a signing public key is configured) but none was provided."); var verifier = new ModuleSignatureVerifier(pem); return verifier.VerifyWithEncodedSignature(packageBytes, signatureBytes) ? (true, "") : (false, "Signature verification failed — the package is unsigned by the trusted key or has been modified."); } // No key configured. if (_options.RequireSignatureForUpload) return (false, "Uploads require a signature but no signing public key is configured " + "(Tsak:Modules:Signature:PublicKeyPath). Configure one, or set " + "Tsak:Modules:Upload:RequireSignatureForUpload=false to allow unsigned uploads."); _logger.LogWarning( "Accepting an UNSIGNED module upload — no signing key configured and RequireSignatureForUpload=false. " + "This trusts any admin API key with code execution; configure a signing key for production."); return (true, ""); } private static (string name, string? version) ReadManifest(byte[] packageBytes) { using var ms = new MemoryStream(packageBytes, writable: false); using var zip = new ZipArchive(ms, ZipArchiveMode.Read); // throws if not a valid ZIP var entry = zip.GetEntry("manifest.json") ?? throw new InvalidDataException("manifest.json is missing."); using var stream = entry.Open(); var manifest = JsonSerializer.Deserialize(stream) ?? throw new InvalidDataException("manifest.json could not be parsed."); if (string.IsNullOrWhiteSpace(manifest.Name)) throw new InvalidDataException("manifest.json has no module name."); return (manifest.Name, manifest.Version); } /// Allows only a safe file-name fragment: letters, digits, dot, dash, underscore. private static string? SanitizeName(string name) { if (string.IsNullOrWhiteSpace(name)) return null; if (name.Contains('/') || name.Contains('\\') || name.Contains("..")) return null; foreach (var ch in name) if (!char.IsLetterOrDigit(ch) && ch is not '.' and not '-' and not '_') return null; return name; } private string? ResolveTargetDir() { if (!string.IsNullOrWhiteSpace(_options.TargetPath)) return _options.TargetPath; var paths = _configuration.GetSection("Tsak:Modules:AssemblyPaths").Get(); return paths is { Length: > 0 } ? paths[0] : null; } private void ArchivePrevious(string livePath, string safeName, string targetDir) { if (!File.Exists(livePath)) return; // Find the next version slot (zero-padded so lexical ordering matches numeric). var existing = Directory.GetFiles(targetDir, safeName + ".tpkg.v*").Length; var archived = Path.Combine(targetDir, $"{safeName}.tpkg.v{existing + 1:D4}"); File.Copy(livePath, archived, overwrite: true); var liveSig = livePath + ".sig"; if (File.Exists(liveSig)) File.Copy(liveSig, archived + ".sig", overwrite: true); // Prune old versions beyond KeepVersions. var all = Directory.GetFiles(targetDir, safeName + ".tpkg.v*") .Where(f => !f.EndsWith(".sig", StringComparison.OrdinalIgnoreCase)) .OrderByDescending(f => f) .Skip(Math.Max(_options.KeepVersions, 0)) .ToList(); foreach (var old in all) { try { File.Delete(old); if (File.Exists(old + ".sig")) File.Delete(old + ".sig"); } catch { /* best effort */ } } } } Path: redb-tsak/src/redb.Tsak.Core/Modules/ModuleVersion.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/Modules/ModuleVersion.cs ---- using System.Globalization; namespace redb.Tsak.Core.Modules; /// /// Date-time based module version: yyyy.MM.dd.HHmm. /// Chronological comparison: newer date-time = higher version. /// public readonly struct ModuleVersion : IComparable, IEquatable { private const string Format = "yyyy.MM.dd.HHmm"; /// Parsed date-time of the version. public DateTime Timestamp { get; } /// Original version string. public string Value { get; } /// Whether this represents a valid parsed version. public bool IsValid { get; } private ModuleVersion(DateTime timestamp, string value, bool isValid) { Timestamp = timestamp; Value = value; IsValid = isValid; } /// Creates a version from the current UTC time. public static ModuleVersion Now() { var now = DateTime.UtcNow; return new ModuleVersion(now, now.ToString(Format, CultureInfo.InvariantCulture), true); } /// Parses a version string in yyyy.MM.dd.HHmm format. public static ModuleVersion Parse(string version) { if (TryParse(version, out var result)) return result; throw new FormatException($"Invalid module version format: '{version}'. Expected: {Format}"); } /// Tries to parse a version string. public static bool TryParse(string? version, out ModuleVersion result) { if (!string.IsNullOrWhiteSpace(version) && DateTime.TryParseExact(version, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt)) { result = new ModuleVersion(dt, version, true); return true; } result = new ModuleVersion(default, version ?? string.Empty, false); return false; } /// Returns true if is a higher version than . public static bool IsNewer(string? newer, string? older) { if (!TryParse(newer, out var n)) return false; if (!TryParse(older, out var o)) return true; // any valid > invalid return n.Timestamp > o.Timestamp; } public int CompareTo(ModuleVersion other) => Timestamp.CompareTo(other.Timestamp); public bool Equals(ModuleVersion other) => Timestamp == other.Timestamp; public override bool Equals(object? obj) => obj is ModuleVersion other && Equals(other); public override int GetHashCode() => Timestamp.GetHashCode(); public override string ToString() => Value; public static bool operator ==(ModuleVersion left, ModuleVersion right) => left.Equals(right); public static bool operator !=(ModuleVersion left, ModuleVersion right) => !left.Equals(right); public static bool operator <(ModuleVersion left, ModuleVersion right) => left.CompareTo(right) < 0; public static bool operator >(ModuleVersion left, ModuleVersion right) => left.CompareTo(right) > 0; public static bool operator <=(ModuleVersion left, ModuleVersion right) => left.CompareTo(right) <= 0; public static bool operator >=(ModuleVersion left, ModuleVersion right) => left.CompareTo(right) >= 0; } Path: redb-tsak/src/redb.Tsak.Core/Modules/PackageDependencyOrder.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/Modules/PackageDependencyOrder.cs ---- namespace redb.Tsak.Core.Modules; /// /// The order packages are opened in: a package after every package its names /// (a carrier of shared companion DLLs before the packages that use them), otherwise in the order given. The startup /// discovery and the hot-reload scan open packages in this one order, so a dependent never loads before its carrier. /// internal static class PackageDependencyOrder { /// /// Sorts by their dependencies (Kahn's algorithm, stable for the given order). A /// dependency on a package that is not in the list is ignored. Packages in a cycle come last, in the given order, and /// are returned in for the caller to report. /// public static List Sort(IReadOnlyList packages, Func path, Func manifest, out List cyclic) { cyclic = []; if (packages.Count <= 1) return [.. packages]; var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var package in packages) { if (!string.IsNullOrWhiteSpace(manifest(package).Name)) byName[manifest(package).Name] = package; } var dependencies = new Dictionary>(StringComparer.OrdinalIgnoreCase); var inDegree = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var package in packages) { var deps = new List(); foreach (var dep in manifest(package).Dependencies) { if (!byName.TryGetValue(dep, out var dependency) || string.Equals(path(dependency), path(package), StringComparison.OrdinalIgnoreCase) || deps.Contains(path(dependency), StringComparer.OrdinalIgnoreCase)) continue; deps.Add(path(dependency)); } dependencies[path(package)] = deps; inDegree[path(package)] = deps.Count; } var queue = new Queue(); foreach (var package in packages) { if (inDegree[path(package)] == 0) queue.Enqueue(package); } var ordered = new List(packages.Count); var emitted = new HashSet(StringComparer.OrdinalIgnoreCase); while (queue.Count > 0) { var current = queue.Dequeue(); ordered.Add(current); emitted.Add(path(current)); foreach (var package in packages) { if (emitted.Contains(path(package))) continue; if (!dependencies[path(package)].Any(p => string.Equals(p, path(current), StringComparison.OrdinalIgnoreCase))) continue; if (--inDegree[path(package)] == 0) queue.Enqueue(package); } } if (ordered.Count < packages.Count) { cyclic = packages.Where(p => !emitted.Contains(path(p))).ToList(); ordered.AddRange(cyclic); } return ordered; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/PackageFirstTypeResolver.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/Modules/PackageFirstTypeResolver.cs ---- using redb.Route.Abstractions; using redb.Route.Components.Bean; namespace redb.Tsak.Core.Modules; /// /// Bean type names of a package's module: the entry-point assemblies first, the companions second, then the resolver /// the context had before, then everything the default resolver sees. A reloaded package thus gets its own new types, /// not the first loaded assembly of the same name. /// internal sealed class PackageFirstTypeResolver(ModulePackage package, IBeanTypeResolver? next) : IBeanTypeResolver { /// Chains a package-first resolver over the one the context has, so each package keeps its own view. internal static void Install(IRouteContext context, ModulePackage package) => context.AddService(typeof(IBeanTypeResolver), new PackageFirstTypeResolver(package, context.GetService())); public Type? Resolve(string typeName) { var comma = typeName.IndexOf(','); var fullName = (comma >= 0 ? typeName[..comma] : typeName).Trim(); var assemblyName = comma >= 0 ? typeName[(comma + 1)..].Trim() : null; foreach (var assembly in package.LoadedAssemblies.Concat(package.CompanionAssemblies)) { if (assemblyName is not null && !string.Equals(assembly.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase)) continue; if (assembly.GetType(fullName) is { } type) return type; } return next?.Resolve(typeName) ?? DefaultBeanTypeResolver.Instance.Resolve(typeName); } } Path: redb-tsak/src/redb.Tsak.Core/Modules/RouteBuilderModule.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/Modules/RouteBuilderModule.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Modules; /// /// Adapter wrapping an IRouteBuilder implementation as an ITsakModule. /// During Initialize a is registered with the context via /// AddRoutes so its routes are actually compiled at Start (issue #3). /// public class RouteBuilderModule : ITsakModule { private readonly IRouteBuilder _builder; public RouteBuilderModule(string moduleName, string version, IRouteBuilder builder, string? sourceDirectory = null) { ModuleName = moduleName; Version = version; _builder = builder; SourceDirectory = sourceDirectory; } public string ModuleName { get; } public string Version { get; } /// The assembly the module's route builder comes from. internal System.Reflection.Assembly ModuleAssembly => _builder.GetType().Assembly; public string Description => $"RouteBuilder module: {_builder.GetType().FullName}"; public IReadOnlyList Dependencies => []; public bool CanInitialize => true; public TsakModuleStatus Status { get; internal set; } = TsakModuleStatus.Loaded; public string? SourceDirectory { get; } public IRouteContext Initialize(IRouteContext context) { // The context compiles ONLY builders registered via AddRoutes (it appends them to its own list // and runs their build at Start). Calling _builder.Configure(context) directly just fills the // builder's OWN definition list, which the context never reads — the routes silently never // compile ("started successfully: all 0 endpoints operational", issue #3). Register instead. if (_builder is RouteBuilder routeBuilder) { if (context is not RouteContext routeContext) throw new InvalidOperationException( $"RouteBuilderModule '{ModuleName}' needs a RouteContext to register its routes, but got " + $"{context?.GetType().FullName ?? "null"}. A RouteBuilder's routes are compiled only when the " + "builder is added to the context via AddRoutes."); routeContext.AddRoutes(routeBuilder); } else { // A hand-rolled IRouteBuilder that is not a RouteBuilder is expected to register its own // routes on the context inside Configure — call it directly (best-effort). _builder.Configure(context); } Status = TsakModuleStatus.Initialized; return context; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/SharedAssemblyLoader.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/Modules/SharedAssemblyLoader.cs ---- using System.Collections.Concurrent; using System.Collections.Immutable; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Modules; /// /// Loads assemblies from the shared layer (Libs/shared/) into the Default ALC. /// These assemblies (connectors, shared models) become available to all module contexts /// via RouteContextExtensions.AddComponents(). /// Tracks file timestamps for change detection during hot-reload scans. /// public sealed class SharedAssemblyLoader { private readonly ILogger _logger; private readonly string _sharedPath; // Published snapshot of loaded shared assemblies. Immutable + swapped atomically under _loadLock, // so a concurrent reader (TsakContextManager.CreateContext enumerates LoadedAssemblies during a // hot-reload) never sees a torn/cleared set — review item 3.4. private ImmutableArray _loadedAssemblies = ImmutableArray.Empty; private readonly object _loadLock = new(); private readonly ConcurrentDictionary _fileTimestamps = new(StringComparer.OrdinalIgnoreCase); private bool _resolvingHandlerRegistered; public SharedAssemblyLoader( ILogger logger, IOptions options) { _logger = logger; var configuredPath = options.Value.SharedPath ?? "Libs/shared"; // Resolve relative paths against AppContext.BaseDirectory (bin output), // not CWD — so Libs/shared works for both dotnet run and deployed scenarios _sharedPath = Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(AppContext.BaseDirectory, configuredPath); } /// Assemblies currently loaded from the shared layer. public IReadOnlyList LoadedAssemblies => _loadedAssemblies; /// Resolved absolute path to the shared directory. public string SharedPath => _sharedPath; /// /// Loads all DLLs from the shared directory into the Default ALC. /// Registers a Default.Resolving handler to probe the shared path /// for transitive dependencies. /// Safe to call multiple times — skips already-loaded files. /// /// Number of newly loaded assemblies. public int LoadSharedAssemblies() { var scanned = ScanAndLoad(out var loaded); if (scanned.Count > 0) lock (_loadLock) _loadedAssemblies = _loadedAssemblies.AddRange(scanned); // append (incremental-safe) return loaded; } /// /// Scans the shared directory and loads any not-yet-timestamped DLLs into the Default ALC. /// Returns the assemblies to publish (reused-preloaded + newly loaded) and, via , /// the count genuinely loaded here. Updates but does NOT touch the /// published — the caller publishes atomically under the lock. /// private List ScanAndLoad(out int loaded) { loaded = 0; var result = new List(); var fullPath = Path.GetFullPath(_sharedPath); if (!Directory.Exists(fullPath)) { _logger.LogDebug("Shared path {Path} does not exist, skipping", fullPath); return result; } RegisterResolvingHandler(fullPath); // Prepare native lib dirs for per-assembly resolvers var nativeDirs = GetNativeLibraryDirs(fullPath); var dllFiles = Directory.GetFiles(fullPath, "*.dll"); foreach (var dll in dllFiles) { if (_fileTimestamps.ContainsKey(dll)) continue; // Skip anything the early bootstrap (SharedRuntime.InstallEarly) already byte-loaded // — e.g. framework assemblies preloaded before the host was built. Re-loading via // LoadFromStream would create a duplicate Assembly instance. We still record the // timestamp so hot-reload change detection covers these files. Matched by assembly // simple name (file name == assembly name for redb.* framework DLLs). var simpleName = Path.GetFileNameWithoutExtension(dll); if (LoadedAssemblyTracker.TryGet(simpleName, out var preloaded) && preloaded is not null) { result.Add(preloaded); _fileTimestamps[dll] = File.GetLastWriteTimeUtc(dll); // Surface framework/providers that the early bootstrap (SharedRuntime) byte-loaded // before Serilog existed — otherwise they are invisible in the log file, unlike the // connectors loaded below. Logged here (host is up) so redb.Core/redb.SQLite/... show. _logger.LogInformation("Shared assembly {Name} {Version} preloaded from shared (framework)", preloaded.GetName().Name, preloaded.GetName().Version); continue; // not counted as newly loaded by this loader } try { var bytes = File.ReadAllBytes(dll); var assembly = AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(bytes)); result.Add(assembly); _fileTimestamps[dll] = File.GetLastWriteTimeUtc(dll); loaded++; // Track in centralized registry so package/bare-DLL loaders // reuse this instance instead of loading a duplicate LoadedAssemblyTracker.Track(assembly); // Register native library resolver for this assembly if (nativeDirs.Count > 0) RegisterNativeResolverForAssembly(assembly, nativeDirs); _logger.LogInformation("Loaded shared assembly {Name} from {Path}", assembly.GetName().Name, dll); } catch (FileLoadException ex) { // Version/identity mismatch — check if the runtime already provides this assembly. _fileTimestamps[dll] = File.GetLastWriteTimeUtc(dll); var asmName = Path.GetFileNameWithoutExtension(dll); var alreadyLoaded = AssemblyLoadContext.Default.Assemblies .Any(a => string.Equals(a.GetName().Name, asmName, StringComparison.OrdinalIgnoreCase)); if (alreadyLoaded) { // Runtime already has this assembly — the shared/ copy is redundant. // Remove it from shared/ to avoid noise on next startup. _logger.LogInformation( "Shared assembly {Name} conflicts with runtime version — runtime copy will be used. " + "Consider removing {Path} from shared/ (run build-shared.ps1 -Clean)", asmName, dll); } else { // Assembly is NOT available from runtime and failed to load — real error. _logger.LogError(ex, "Failed to load shared assembly {Path} — version conflict and no runtime fallback available", dll); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load shared assembly {Path}", dll); } } if (loaded > 0) _logger.LogInformation("Loaded {Count} shared assemblies from {Path}", loaded, fullPath); return result; } /// /// Checks if any shared DLLs have changed (added, updated, or removed) since last load. /// /// True if changes detected; caller should trigger full context restart. /// /// Re-syncs the tracked timestamps to the CURRENT disk state without loading anything — /// used after reporting a shared-layer change that only a process restart can apply, so the /// report fires once per change instead of on every scan (review 2026-09-02, С22). /// public void AcknowledgeChanges() { var fullPath = Path.GetFullPath(_sharedPath); if (!Directory.Exists(fullPath)) { _fileTimestamps.Clear(); return; } var currentFiles = new HashSet( Directory.GetFiles(fullPath, "*.dll"), StringComparer.OrdinalIgnoreCase); foreach (var stale in _fileTimestamps.Keys.Where(k => !currentFiles.Contains(k)).ToList()) _fileTimestamps.TryRemove(stale, out _); foreach (var dll in currentFiles) _fileTimestamps[dll] = File.GetLastWriteTimeUtc(dll); } public bool DetectChanges() { var fullPath = Path.GetFullPath(_sharedPath); if (!Directory.Exists(fullPath)) return _fileTimestamps.Count > 0; // directory removed = change var currentFiles = new HashSet( Directory.GetFiles(fullPath, "*.dll"), StringComparer.OrdinalIgnoreCase); // Check for new or modified files foreach (var dll in currentFiles) { var lastWrite = File.GetLastWriteTimeUtc(dll); if (!_fileTimestamps.TryGetValue(dll, out var tracked) || tracked != lastWrite) return true; } // Check for removed files foreach (var tracked in _fileTimestamps.Keys) { if (!currentFiles.Contains(tracked)) return true; } return false; } /// /// Reloads all shared assemblies. Since Default ALC can't unload, /// this replaces the assembly list and timestamps. Old assemblies remain in memory /// until process restart. /// /// Number of assemblies in the new load. public int ReloadSharedAssemblies() { _logger.LogInformation("Reloading shared assemblies from {Path}", _sharedPath); _fileTimestamps.Clear(); // Build the fresh set, THEN swap atomically — readers never observe an empty/torn set mid-reload // (review item 3.4). Assemblies stay in the Default ALC (it can't unload); already-tracked ones // are reused via the preloaded path in ScanAndLoad, so no duplicate loads. var scanned = ScanAndLoad(out var loaded); lock (_loadLock) _loadedAssemblies = ImmutableArray.CreateRange(scanned); return loaded; } private void RegisterResolvingHandler(string fullSharedPath) { if (_resolvingHandlerRegistered) return; // Single implementation shared with the early (DI-free) bootstrap so the handler is // installed only once per path — see SharedRuntime.EnsureSharedPathResolver. It performs // exactly what this method used to inline: tracker resolver first, then shared-dir probe // for transitive deps, then version-tolerant forwarding for higher-version references. SharedRuntime.EnsureSharedPathResolver(fullSharedPath, msg => _logger.LogDebug("{Msg}", msg)); _resolvingHandlerRegistered = true; } private static List GetNativeLibraryDirs(string fullSharedPath) { var runtimesPath = Path.Combine(fullSharedPath, "runtimes"); if (!Directory.Exists(runtimesPath)) return []; var rid = RuntimeInformation.RuntimeIdentifier; var nativeDirs = new List(); // Exact RID first (e.g. win-x64, linux-x64) var exactDir = Path.Combine(runtimesPath, rid, "native"); if (Directory.Exists(exactDir)) nativeDirs.Add(exactDir); // Fallback: OS-only RID (e.g. win, linux, osx) var osOnly = rid.Contains('-') ? rid[..rid.IndexOf('-')] : rid; var osDir = Path.Combine(runtimesPath, osOnly, "native"); if (Directory.Exists(osDir) && !nativeDirs.Contains(osDir)) nativeDirs.Add(osDir); return nativeDirs; } /// /// Registers a native library resolver for a loaded shared assembly so its P/Invoke calls /// can find native libraries in Libs/shared/runtimes/{rid}/native/. /// internal void RegisterNativeResolverForAssembly(Assembly assembly, List nativeDirs) { try { NativeLibrary.SetDllImportResolver(assembly, (name, asm, searchPath) => TryLoadNativeFromShared(name, nativeDirs)); } catch (InvalidOperationException) { // Already has a resolver — ignore } } private static IntPtr TryLoadNativeFromShared(string libraryName, List nativeDirs) { foreach (var dir in nativeDirs) { // Try exact name, then with platform extension var candidates = new[] { Path.Combine(dir, libraryName), Path.Combine(dir, libraryName + ".dll"), Path.Combine(dir, libraryName + ".so"), Path.Combine(dir, "lib" + libraryName + ".so"), Path.Combine(dir, libraryName + ".dylib"), Path.Combine(dir, "lib" + libraryName + ".dylib"), }; foreach (var candidate in candidates) { if (NativeLibrary.TryLoad(candidate, out var handle)) return handle; } } return IntPtr.Zero; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/SharedRuntime.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/Modules/SharedRuntime.cs ---- using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; namespace redb.Tsak.Core.Modules; /// /// Early, DI-free entry point to the shared assembly layer (Libs/shared). /// Installed as the very FIRST action in Program.Main — before any redb.* type is /// touched — so that framework assemblies (redb.Core/Route/providers) can live in the /// shared layer instead of the application bin and still be resolved at runtime. /// /// Reuses exactly the same primitives as : /// /// byte-load via LoadFromStream — the DLL file is never locked, so it can be /// swapped for a patch release without rebuilding the host; /// registration — modules (isolated ALCs) /// unify their redb.* types against the single Default-ALC instance; /// per-assembly native resolver over runtimes/<rid>/native; /// version-tolerant forwarding for higher-version transitive references. /// /// This type adds only two things on top: a logger-free early call path, and a required-set /// preload whose "what failed to load" result feeds the caller's fail-fast (stage B2). /// /// This class references ONLY BCL + (also BCL-only), so /// invoking it does not force any redb.* assembly to load. /// public static class SharedRuntime { private static readonly HashSet _resolverPaths = new(StringComparer.OrdinalIgnoreCase); private static readonly object _gate = new(); /// Default shared-layer location: <app-base>/Libs/shared. public static string DefaultSharedPath => Path.Combine(AppContext.BaseDirectory, "Libs", "shared"); /// /// EARLY entry point for Program.Main. Installs the resolver over /// and eagerly byte-loads /// (the framework set) so they are present in the Default ALC before Tsak.Core touches any /// redb type. Returns the names that could NOT be loaded — the caller decides whether that /// is fatal (fail-fast is scoped to this required set; the lazy transitive tail stays soft). /// public static IReadOnlyList InstallEarly( string sharedPath, IReadOnlyCollection requiredNames, Action? log = null) { var full = Path.GetFullPath(sharedPath); if (!Directory.Exists(full)) { log?.Invoke($"[shared] path not found: {full}"); return requiredNames.Where(n => !IsLoaded(n)).ToList(); } EnsureSharedPathResolver(full, log); var nativeDirs = GetNativeLibraryDirs(full); var missing = new List(); foreach (var name in requiredNames) { if (IsLoaded(name)) continue; // already provided (e.g. from bin) var dll = Path.Combine(full, name + ".dll"); if (!File.Exists(dll)) { missing.Add(name); continue; } var asm = LoadAndTrack(dll, nativeDirs, log); if (asm is null && !IsLoaded(name)) missing.Add(name); } return missing; } /// True if an assembly with this simple name is already loaded/tracked. public static bool IsLoaded(string simpleName) => LoadedAssemblyTracker.TryGet(simpleName, out _) || AssemblyLoadContext.Default.Assemblies.Any(a => string.Equals(a.GetName().Name, simpleName, StringComparison.OrdinalIgnoreCase)); /// Version of a loaded assembly by simple name (tracker first, then Default ALC), or null. public static Version? GetLoadedVersion(string simpleName) { if (LoadedAssemblyTracker.TryGet(simpleName, out var tracked) && tracked is not null) return tracked.GetName().Version; return AssemblyLoadContext.Default.Assemblies .FirstOrDefault(a => string.Equals(a.GetName().Name, simpleName, StringComparison.OrdinalIgnoreCase)) ?.GetName().Version; } /// /// Registers the Default ALC resolver over once /// (idempotent per path). Probes the shared dir for not-yet-loaded assemblies and forwards /// higher-version references to an already-loaded lower version. Shared by the early path /// and by so the handler is installed only once per path. /// public static void EnsureSharedPathResolver(string fullSharedPath, Action? log = null) { LoadedAssemblyTracker.EnsureResolverRegistered(); // tracked-assembly handler first lock (_gate) { if (!_resolverPaths.Add(fullSharedPath)) return; // already installed for this path } AssemblyLoadContext.Default.Resolving += (ctx, name) => { // 1. Load a transitive dep from the shared dir on demand (byte-load, no lock). if (name.Name is not null) { var candidate = Path.Combine(fullSharedPath, name.Name + ".dll"); if (File.Exists(candidate)) { try { var loaded = AssemblyLoadContext.Default.LoadFromStream( new MemoryStream(File.ReadAllBytes(candidate))); LoadedAssemblyTracker.Track(loaded); return loaded; } catch (FileLoadException) { /* identity/version mismatch → forward below */ } catch (Exception ex) { // A Resolving handler must NEVER throw — that aborts the runtime's whole // resolution instead of letting it try version-tolerant forwarding or another // handler. A transient IOException (file locked mid-copy by build-shared), // UnauthorizedAccessException, or a partial/corrupt image (BadImageFormatException) // are all soft-skipped here and we fall through to forwarding (review item 3.6). log?.Invoke($"[shared] soft-skip loading '{name.Name}' from shared dir: {ex.GetType().Name}: {ex.Message}"); } } } // 2. Version-tolerant forwarding: a package may reference a higher framework version // than the runtime provides — return the already-loaded lower version. return ctx.Assemblies.FirstOrDefault(a => string.Equals(a.GetName().Name, name.Name, StringComparison.OrdinalIgnoreCase)); }; log?.Invoke($"[shared] resolver installed over {fullSharedPath}"); } /// /// Byte-loads a single DLL into the Default ALC and tracks it (file never locked). Registers /// a native resolver for it when native dirs exist. Returns the assembly, or null when /// the runtime already provides it (graceful — a shared copy of a framework assembly is not /// an error, the runtime one wins). /// public static Assembly? LoadAndTrack(string dllPath, List nativeDirs, Action? log = null) { try { var asm = AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(File.ReadAllBytes(dllPath))); LoadedAssemblyTracker.Track(asm); if (nativeDirs.Count > 0) RegisterNativeResolver(asm, nativeDirs); log?.Invoke($"[shared] loaded {asm.GetName().Name} {asm.GetName().Version}"); return asm; } catch (FileLoadException) { return null; // runtime already supplies this assembly } } /// Native lib dirs under shared/runtimes for the current RID (+ OS-only fallback). public static List GetNativeLibraryDirs(string fullSharedPath) { var runtimesPath = Path.Combine(fullSharedPath, "runtimes"); if (!Directory.Exists(runtimesPath)) return []; var rid = RuntimeInformation.RuntimeIdentifier; var dirs = new List(); var exact = Path.Combine(runtimesPath, rid, "native"); if (Directory.Exists(exact)) dirs.Add(exact); var osOnly = rid.Contains('-') ? rid[..rid.IndexOf('-')] : rid; var osDir = Path.Combine(runtimesPath, osOnly, "native"); if (Directory.Exists(osDir) && !dirs.Contains(osDir)) dirs.Add(osDir); return dirs; } private static void RegisterNativeResolver(Assembly assembly, List nativeDirs) { try { NativeLibrary.SetDllImportResolver(assembly, (name, _, _) => TryLoadNative(name, nativeDirs)); } catch (InvalidOperationException) { /* already has a resolver */ } } private static IntPtr TryLoadNative(string libraryName, List nativeDirs) { foreach (var dir in nativeDirs) { var candidates = new[] { Path.Combine(dir, libraryName), Path.Combine(dir, libraryName + ".dll"), Path.Combine(dir, libraryName + ".so"), Path.Combine(dir, "lib" + libraryName + ".so"), Path.Combine(dir, libraryName + ".dylib"), Path.Combine(dir, "lib" + libraryName + ".dylib"), }; foreach (var c in candidates) if (NativeLibrary.TryLoad(c, out var handle)) return handle; } return IntPtr.Zero; } } Path: redb-tsak/src/redb.Tsak.Core/Modules/StaticMethodModule.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/Modules/StaticMethodModule.cs ---- using System.Reflection; using redb.Route.Abstractions; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Modules; /// /// Adapter wrapping a static InitRoute.main method as an ITsakModule, in either form of the convention /// (): IRouteContext main(IRouteContext) runs through /// , Task<IRouteContext> main(IRouteContext) through /// . An exception from main reaches the caller as the module threw it, not /// wrapped in , so the log and the activation report name the module's /// failure. Module name is derived from the namespace of the InitRoute class. /// public class StaticMethodModule : ITsakModule, IEmbeddedConfigModule { private readonly MethodInfo _mainMethod; private readonly bool _isAsync; public StaticMethodModule(string moduleName, string version, MethodInfo mainMethod, string? sourceDirectory = null, string? embeddedConfigJson = null) { ModuleName = moduleName; Version = version; _mainMethod = mainMethod; _isAsync = InitRouteConvention.Classify(mainMethod) == InitRouteConvention.Form.Async; SourceDirectory = sourceDirectory; EmbeddedConfigJson = embeddedConfigJson; } public string ModuleName { get; } public string Version { get; } /// The assembly the module's InitRoute class comes from. internal Assembly ModuleAssembly => _mainMethod.DeclaringType?.Assembly ?? _mainMethod.Module.Assembly; public string Description => $"Static method module from {_mainMethod.DeclaringType?.FullName}"; public IReadOnlyList Dependencies => []; public bool CanInitialize => true; public TsakModuleStatus Status { get; internal set; } = TsakModuleStatus.Loaded; public string? SourceDirectory { get; } /// /// Raw JSON config from .tpkg package ({moduleName}.config.json), loaded in-memory. /// Null for bare DLL modules (they use config file from disk). /// public string? EmbeddedConfigJson { get; internal set; } /// /// The .tpkg package the module comes from; null for a bare DLL module. Its assemblies resolve the bean types of /// the XML the module loads, ahead of any other assembly of the same name (an earlier version of the package /// after a hot reload). /// internal ModulePackage? Package { get; private set; } /// Binds the module to its package: the package's types for bean resolution and its module config. internal void AttachPackage(ModulePackage package) { Package = package; EmbeddedConfigJson = package.ReadModuleConfigJson(ModuleName); } /// Runs a synchronous main. An async main is refused: it runs only through . public IRouteContext Initialize(IRouteContext context) { if (_isAsync) throw new InvalidOperationException( $"{_mainMethod.DeclaringType?.FullName}.main is async (Task) and cannot run synchronously; " + "initialize the module through InitializeAsync."); var result = Invoke(context); Status = TsakModuleStatus.Initialized; return result as IRouteContext ?? context; } /// Awaits an async main; a synchronous main runs as in . public async Task InitializeAsync(IRouteContext context) { if (!_isAsync) return Initialize(context); var task = Invoke(context) as Task ?? throw new InvalidOperationException( $"{_mainMethod.DeclaringType?.FullName}.main returned no Task."); await task.ConfigureAwait(false); // The result is read through reflection: the declared form may be Task, which is not a // Task. var result = task.GetType().GetProperty(nameof(Task.Result))!.GetValue(task); Status = TsakModuleStatus.Initialized; return result as IRouteContext ?? context; } private object? Invoke(IRouteContext context) { // Before main: XML that main loads () resolves the package's own types, as an XML module does. if (Package is not null) PackageFirstTypeResolver.Install(context, Package); return _mainMethod.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: [context], culture: null); } } Path: redb-tsak/src/redb.Tsak.Core/Modules/XmlRouteModule.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/Modules/XmlRouteModule.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; using redb.Route.Xml; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Modules; /// /// The third module convention (Route-XML Ф5.2): XML route artifacts from the package manifest, /// loaded into the context through the standard — which registers /// routes via AddRoutes by construction, so the issue #3 trap (routes silently never /// compiling) cannot recur. Bean type names resolve package-first (entry-point ALC, then /// companions, then everything the default resolver sees — shared and Default ALC); artifact /// file-references resolve from the package's extracted resources. Discovery order guarantees /// assemblies are scanned before XML, so bean:#name objects registered by module code /// are visible to the artifacts. /// public sealed class XmlRouteModule : ITsakModule, IEmbeddedConfigModule { private readonly ModulePackage _package; private readonly ILogger? _logger; public XmlRouteModule(ModulePackage package, string? sourceDirectory, string? embeddedConfigJson, ILogger? logger = null) { _package = package ?? throw new ArgumentNullException(nameof(package)); SourceDirectory = sourceDirectory; EmbeddedConfigJson = embeddedConfigJson; _logger = logger; } /// The manifest of the package, whose Dependencies order this module's context at start. internal ModuleManifest Manifest => _package.Manifest; /// The package's own code, for its type resolver: the entry points and the companions. internal IEnumerable PackageAssemblies => _package.LoadedAssemblies.Concat(_package.CompanionAssemblies); public string ModuleName => _package.Manifest.Name; public string Version => _package.Manifest.Version; public string Description => $"XML route module: {_package.Manifest.Artifacts.Count} artifact(s) from {Path.GetFileName(_package.PackagePath)}"; public IReadOnlyList Dependencies => _package.Manifest.Dependencies; public bool CanInitialize => true; public TsakModuleStatus Status { get; internal set; } = TsakModuleStatus.Loaded; public string? SourceDirectory { get; } /// public string? EmbeddedConfigJson { get; } public IRouteContext Initialize(IRouteContext context) { if (context is not RouteContext routeContext) { Status = TsakModuleStatus.Faulted; throw new InvalidOperationException( $"XmlRouteModule '{ModuleName}' needs a RouteContext to load its routes, but got " + $"{context?.GetType().FullName ?? "null"}."); } // Fail fast on missing configuration (Ф5.4 / эскиз 11 §1.4): every key the manifest // requires must have a value in the MERGED context configuration — which the // coordinator has already written into the context's properties before Initialize. // Owner decision 2026-09-03: module-isolated failure — this module faults, its routes // never register, the context lives on. var missing = _package.Manifest.RequiredConfigKeys .Where(key => routeContext.GetProperty(key) is null) .ToList(); if (missing.Count > 0) { Status = TsakModuleStatus.Faulted; throw new InvalidOperationException( $"XmlRouteModule '{ModuleName}': the merged context configuration provides no value for " + $"required key(s): {string.Join(", ", missing)}. Supply them via host appsettings, the " + "external context.json, or an Override environment variable."); } if (_package.XmlArtifacts.Count != _package.Manifest.Artifacts.Count) { Status = TsakModuleStatus.Faulted; var found = _package.XmlArtifacts.Select(a => a.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); throw new InvalidOperationException( $"XmlRouteModule '{ModuleName}': artifact(s) listed in the manifest are missing from the package: " + string.Join(", ", _package.Manifest.Artifacts.Where(a => !found.Contains(a)))); } // Package-first resolution, chained over whatever the context already has — several // packages share one context, and each keeps its own package-first view. PackageFirstTypeResolver.Install(routeContext, _package); if (_package is { ResourcesRoot: { } resourcesRoot, PackageRoot: { } packageRoot }) { routeContext.AddService(typeof(IRouteResourceResolver), new PackageFirstResourceResolver(resourcesRoot, packageRoot, routeContext.GetService())); } // Every markup contribution reachable in this worker (Р21): the package's own // assemblies first, then everything the process carries (the shared layer above all — // , , , … ship their elements as contributions). Without this an XML // module could use only the core elements. var options = new XmlRouteLoaderOptions { Extensions = DiscoverContributions() }; var packageSource = Path.GetFileName(_package.PackagePath); // The package's context.xml first (components, beans, onInit, context-level blocks // like ) — route artifacts may rely on all of it. if (_package.ContextXml is { } contextXml) { var contextDocument = System.Xml.Linq.XDocument.Parse(contextXml, System.Xml.Linq.LoadOptions.SetLineInfo); new XmlContextLoader(routeContext, options).Load(contextDocument, $"{packageSource}::context.xml"); } var loader = new XmlRouteLoader(routeContext, options); foreach (var (name, content) in _package.XmlArtifacts) { var document = System.Xml.Linq.XDocument.Parse(content, System.Xml.Linq.LoadOptions.SetLineInfo); loader.Load(document, $"{packageSource}::{name}"); } _logger?.LogInformation("XmlRouteModule {Module}: loaded {Count} artifact(s)", ModuleName, _package.XmlArtifacts.Count); Status = TsakModuleStatus.Initialized; return context; } /// /// Public parameterless implementations from the /// package's assemblies and the whole process (shared layer, host) — mirroring how the /// worker feeds components to a context (everything available is available). Types that /// fail to load are skipped the way the engine's AddComponents skips them. /// private List DiscoverContributions() { var contributions = new List(); var seen = new HashSet(StringComparer.Ordinal); var assemblies = _package.LoadedAssemblies .Concat(_package.CompanionAssemblies) .Concat(AppDomain.CurrentDomain.GetAssemblies() .Where(a => a.GetName().Name?.StartsWith("redb.", StringComparison.Ordinal) == true)); foreach (var assembly in assemblies.Distinct()) { Type[] types; try { types = assembly.GetTypes(); } catch (System.Reflection.ReflectionTypeLoadException ex) { types = [.. ex.Types.Where(t => t is not null)!]; } foreach (var type in types) { if (type.IsAbstract || type.IsInterface || !typeof(IXmlElementContribution).IsAssignableFrom(type) || type.GetConstructor(Type.EmptyTypes) is null || !seen.Add(type.FullName ?? type.Name)) continue; contributions.Add((IXmlElementContribution)Activator.CreateInstance(type)!); } } return contributions; } /// /// The package's extracted resources first, then whatever the context had. A reference is read as the project reads it /// and as the packaging checks accept it: from the resources directory (order.xsd), else from the package root /// (resources/order.xsd); neither may leave the package. /// private sealed class PackageFirstResourceResolver(string resourcesRoot, string packageRoot, IRouteResourceResolver? next) : IRouteResourceResolver { public string? Resolve(string reference) { if (Path.IsPathRooted(reference)) return File.Exists(reference) ? reference : next?.Resolve(reference); return Inside(resourcesRoot, reference) ?? Inside(packageRoot, reference) ?? next?.Resolve(reference); } private static string? Inside(string root, string reference) { var candidate = Path.GetFullPath(Path.Combine(root, reference)); return candidate.StartsWith(root, StringComparison.OrdinalIgnoreCase) && File.Exists(candidate) ? candidate : null; } public string DescribeSearch(string reference) => $"{Path.Combine(resourcesRoot, reference)}; {Path.Combine(packageRoot, reference)}; " + (next?.DescribeSearch(reference) ?? reference); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/AlertDispatcher.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/Monitoring/Alerts/AlertDispatcher.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Fans watchdog / lifecycle alerts out to every enabled . /// /// Fire-and-forget: alerts go through a bounded in-memory queue drained by a background /// pump, so the watchdog scan never blocks on a slow SMTP server, and a broken alert backend can /// never take the node down. Queue overflow drops the oldest (with a warning). /// /// /// Dedup: the same incident () is delivered at most /// once per — the watchdog rebuilds its alert /// snapshot every scan, so without this a hung exchange would re-page on every cycle. /// /// public sealed class AlertDispatcher : IAsyncDisposable { private const int QueueCapacity = 500; private readonly WatchdogAlertOptions _options; private readonly ILogger _logger; private readonly Channel _queue; private readonly ConcurrentDictionary _lastSent = new(); private readonly CancellationTokenSource _shutdown = new(); private readonly Task _pump; private readonly int _minRank; // Copy-on-write so the pump reads a stable snapshot while the endpoint channel may be // attached later (it needs the _system route context, which exists only after startup). private volatile IReadOnlyList _channels; public AlertDispatcher( WatchdogAlertOptions options, IEnumerable channels, ILogger logger) { _options = options; _channels = channels.Where(c => c.IsEnabled).ToList(); _logger = logger; _minRank = RankOf(options.MinLevel); _queue = Channel.CreateBounded(new BoundedChannelOptions(QueueCapacity) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); _pump = Task.Run(PumpAsync); if (IsActive) _logger.LogInformation("Alert delivery enabled — channels: {Channels}, min level: {MinLevel}", string.Join(", ", _channels.Select(c => c.Name)), options.MinLevel); } /// /// Attaches the generic broker endpoint channel once the _system route context is available. /// No-op unless the endpoint channel is enabled and resolves a producer. /// public void AttachEndpointChannel(redb.Route.Abstractions.IRouteContext context) { var endpoint = new EndpointAlertChannel(_options.Endpoint, context); if (!endpoint.IsEnabled) { endpoint.Dispose(); return; } _channels = _channels.Append(endpoint).ToList(); // copy-on-write _logger.LogInformation("Alert endpoint channel attached → {Uri}", _options.Endpoint.Uri); } /// True when alerts are on and at least one channel is enabled. public bool IsActive => _options.Enabled && _channels.Count > 0; /// Names of the enabled channels (for status display). public IReadOnlyList EnabledChannels => _channels.Select(c => c.Name).ToList(); /// /// Enqueues an alert for delivery, applying the min-level filter and dedup window. Never blocks. /// public void Enqueue(AlertNotification alert) { if (!IsActive) return; if (RankOf(alert.Level) < _minRank) return; var now = DateTimeOffset.UtcNow; var window = TimeSpan.FromMinutes(_options.DedupWindowMinutes); var last = _lastSent.GetOrAdd(alert.DedupKey, DateTimeOffset.MinValue); if (now - last < window) return; // still inside the suppression window _lastSent[alert.DedupKey] = now; _queue.Writer.TryWrite(alert); // DropOldest → never fails, never blocks } /// /// Delivers an alert to every enabled channel synchronously, bypassing the queue and the /// dedup window, and returns the per-channel outcome. Used by POST /api/watchdog/test-alert /// so an operator can verify configuration and see exactly which channel failed and why. /// public async Task> TestAsync(AlertNotification alert, CancellationToken ct) { var results = new List(); foreach (var channel in _channels) { try { await channel.SendAsync(alert, ct).ConfigureAwait(false); results.Add(new AlertChannelResult(channel.Name, true, null)); } catch (Exception ex) { results.Add(new AlertChannelResult(channel.Name, false, ex.Message)); } } return results; } private async Task PumpAsync() { try { await foreach (var alert in _queue.Reader.ReadAllAsync(_shutdown.Token).ConfigureAwait(false)) { foreach (var channel in _channels) { try { await channel.SendAsync(alert, _shutdown.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (_shutdown.IsCancellationRequested) { return; } catch (Exception ex) { _logger.LogWarning(ex, "Alert channel {Channel} failed to deliver {Level} alert", channel.Name, alert.Level); } } } } catch (OperationCanceledException) { // shutdown } } private static int RankOf(string level) => level?.Trim().ToLowerInvariant() switch { "suspected" => 1, "hung" => 2, "test" => 0, // test alerts pass the filter regardless of MinLevel _ => 2 }; public async ValueTask DisposeAsync() { _queue.Writer.TryComplete(); try { await _pump.WaitAsync(TimeSpan.FromSeconds(3)); } catch { /* drain best-effort */ } await _shutdown.CancelAsync(); _shutdown.Dispose(); foreach (var channel in _channels) (channel as IDisposable)?.Dispose(); } } /// Per-channel outcome of a test delivery. public sealed record AlertChannelResult(string Channel, bool Success, string? Error); Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/AlertNotification.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/Monitoring/Alerts/AlertNotification.cs ---- using System.Text.Json; using System.Text.Json.Serialization; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// A single alert to deliver. Produced from a WatchdogAlert (a newly detected hung / /// suspected exchange) or from a lifecycle event, and carried to every enabled channel. /// public sealed record AlertNotification { /// Severity: "Suspected" or "Hung" (or "Test" for a manual probe). public required string Level { get; init; } /// Short, human-readable summary line (also the Telegram/webhook title). public required string Title { get; init; } public string? ContextName { get; init; } public string? RouteId { get; init; } public string? ExchangeId { get; init; } public double? ElapsedSeconds { get; init; } public string? NodeId { get; init; } public DateTimeOffset Timestamp { get; init; } = DateTimeOffset.UtcNow; /// /// Stable dedup key: the same incident produces the same key so the dispatcher can suppress /// repeats within the configured window. Test alerts get a unique key so they always deliver. /// [JsonIgnore] public string DedupKey => $"{Level}|{ContextName}|{RouteId}|{ExchangeId}"; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; /// JSON body sent to the webhook / endpoint channels. public string ToJson() => JsonSerializer.Serialize(this, JsonOptions); /// Plain-text rendering for Telegram and email bodies. public string ToText() { var lines = new List { $"[{Level}] {Title}" }; if (NodeId is not null) lines.Add($"Node: {NodeId}"); if (ContextName is not null) lines.Add($"Context: {ContextName}"); if (RouteId is not null) lines.Add($"Route: {RouteId}"); if (ExchangeId is not null) lines.Add($"Exchange: {ExchangeId}"); if (ElapsedSeconds is { } e) lines.Add($"Elapsed: {e:F0}s"); lines.Add($"At: {Timestamp:u}"); return string.Join("\n", lines); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/EmailAlertChannel.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/Monitoring/Alerts/EmailAlertChannel.cs ---- using System.Net; using System.Net.Mail; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Email delivery over SMTP using the BCL — no extra package. Adequate /// for fire-and-forget operational alerts; each send opens and closes its own connection. /// public sealed class EmailAlertChannel : IAlertChannel { private readonly EmailChannelOptions _options; public EmailAlertChannel(EmailChannelOptions options) { _options = options; } public string Name => "email"; public bool IsEnabled => _options.Enabled && !string.IsNullOrWhiteSpace(_options.Host) && !string.IsNullOrWhiteSpace(_options.From) && !string.IsNullOrWhiteSpace(_options.To); public async Task SendAsync(AlertNotification alert, CancellationToken ct) { using var client = new SmtpClient(_options.Host, _options.Port) { EnableSsl = _options.UseSsl, DeliveryMethod = SmtpDeliveryMethod.Network }; if (!string.IsNullOrEmpty(_options.Username)) client.Credentials = new NetworkCredential(_options.Username, _options.Password); using var message = new MailMessage(_options.From, _options.To) { Subject = $"[Tsak {alert.Level}] {alert.Title}", Body = alert.ToText() }; await client.SendMailAsync(message, ct).ConfigureAwait(false); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/EndpointAlertChannel.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/Monitoring/Alerts/EndpointAlertChannel.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Generic route-endpoint channel: sends the alert JSON to any redb.Route producer URI /// (kafka:topic, amqp:queue, mqtt:…) via a . /// /// This is how brokers are supported without Core taking a compile-time dependency on any broker /// connector: the target component must be registered in the host's _system context (Tsak.Worker /// loads connectors as shared assemblies at runtime). If it is not, the send fails and the /// dispatcher logs it — the same as any other misconfigured channel. /// /// public sealed class EndpointAlertChannel : IAlertChannel, IDisposable { private readonly EndpointChannelOptions _options; private readonly ProducerTemplate? _producer; /// Where the alerts are sent and which ones. /// /// The _system route context, or null when alerts run outside a route context (then the /// channel is simply never enabled). /// public EndpointAlertChannel(EndpointChannelOptions options, IRouteContext? context) { _options = options; if (context is not null && options.Enabled && !string.IsNullOrWhiteSpace(options.Uri)) { _producer = new ProducerTemplate(context); if (!_producer.IsStarted) _producer.Start(); } } public string Name => "endpoint"; public bool IsEnabled => _producer is not null; public async Task SendAsync(AlertNotification alert, CancellationToken ct) { if (_producer is null) throw new InvalidOperationException("Endpoint channel is not configured."); var msg = new Message { Body = alert.ToJson() }; msg.Headers["alert.level"] = alert.Level; msg.Headers["Content-Type"] = "application/json"; await _producer.SendAsync(_options.Uri, msg).ConfigureAwait(false); } public void Dispose() { try { if (_producer is { IsStarted: true }) _producer.Stop(); } catch { /* best effort on shutdown */ } } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/IAlertChannel.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/Monitoring/Alerts/IAlertChannel.cs ---- namespace redb.Tsak.Core.Monitoring.Alerts; /// /// A single alert delivery destination (webhook, Telegram, email, broker endpoint). /// Channels are resolved once at startup; only enabled ones are dispatched to. /// public interface IAlertChannel { /// Short stable name, used in logs and the per-channel test result. string Name { get; } /// Whether this channel is turned on and fully configured. bool IsEnabled { get; } /// /// Delivers one alert. Implementations must throw on failure (the dispatcher isolates and /// logs it); they must not swallow errors silently, or a misconfigured channel would look /// healthy. /// Task SendAsync(AlertNotification alert, CancellationToken ct); } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/TelegramAlertChannel.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/Monitoring/Alerts/TelegramAlertChannel.cs ---- using System.Text; using System.Text.Json; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Telegram delivery via the Bot API — a formatted HTTPS POST to /// https://api.telegram.org/bot{token}/sendMessage. Intentionally uses a plain /// rather than a Telegram connector, so it adds nothing to Core's graph. /// public sealed class TelegramAlertChannel : IAlertChannel { private readonly TelegramChannelOptions _options; private readonly HttpClient _http; public TelegramAlertChannel(TelegramChannelOptions options, HttpClient http) { _options = options; _http = http; } public string Name => "telegram"; public bool IsEnabled => _options.Enabled && !string.IsNullOrWhiteSpace(_options.BotToken) && !string.IsNullOrWhiteSpace(_options.ChatId); public async Task SendAsync(AlertNotification alert, CancellationToken ct) { var url = $"https://api.telegram.org/bot{_options.BotToken}/sendMessage"; var payload = JsonSerializer.Serialize(new { chat_id = _options.ChatId, text = alert.ToText() }); using var content = new StringContent(payload, Encoding.UTF8, "application/json"); using var response = await _http.PostAsync(url, content, ct).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/WatchdogAlertOptions.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/Monitoring/Alerts/WatchdogAlertOptions.cs ---- namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Alert delivery configuration, bound from Tsak:Watchdog:Alerts. /// /// Everything is off by default: no channel delivers until it is explicitly enabled and /// given its connection parameters. Enabling alone does nothing — at least /// one channel must also be enabled. /// /// public sealed class WatchdogAlertOptions { /// Master switch. Default: false. public bool Enabled { get; set; } /// /// Minimum severity that triggers delivery: "Suspected" or "Hung". /// Default: "Hung" — only genuinely stuck exchanges page someone. /// public string MinLevel { get; set; } = "Hung"; /// /// Suppression window: the same alert (context+route+exchange+level) is delivered at most once /// per this many minutes, so a persistently hung exchange does not re-page every scan. /// Default: 15. /// public double DedupWindowMinutes { get; set; } = 15; public WebhookChannelOptions Webhook { get; set; } = new(); public TelegramChannelOptions Telegram { get; set; } = new(); public EmailChannelOptions Email { get; set; } = new(); public EndpointChannelOptions Endpoint { get; set; } = new(); } /// Generic outgoing webhook — POSTs the alert JSON to a URL (Slack/Teams/PagerDuty/…). public sealed class WebhookChannelOptions { public bool Enabled { get; set; } /// Target URL. Required when enabled. public string Url { get; set; } = ""; /// Optional extra headers (e.g. an auth token). public Dictionary Headers { get; set; } = new(); } /// Telegram Bot API — a formatted HTTPS POST, no connector needed. public sealed class TelegramChannelOptions { public bool Enabled { get; set; } /// Bot token from @BotFather. Required when enabled. public string BotToken { get; set; } = ""; /// Target chat id. Required when enabled. public string ChatId { get; set; } = ""; } /// Email via SMTP (BCL SmtpClient — no extra package). public sealed class EmailChannelOptions { public bool Enabled { get; set; } public string Host { get; set; } = ""; public int Port { get; set; } = 587; public bool UseSsl { get; set; } = true; public string From { get; set; } = ""; public string To { get; set; } = ""; public string? Username { get; set; } public string? Password { get; set; } } /// /// Generic route endpoint — sends the alert to any redb.Route URI (kafka:topic, /// amqp:queue, mqtt:…) via a ProducerTemplate. Works only when the matching /// component is registered in the host's _system context; it is never a compile-time dependency /// of the Tsak kernel, so brokers add no weight to Core. /// public sealed class EndpointChannelOptions { public bool Enabled { get; set; } /// Route producer URI, e.g. kafka:tsak-alerts. Required when enabled. public string Uri { get; set; } = ""; } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/Alerts/WebhookAlertChannel.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/Monitoring/Alerts/WebhookAlertChannel.cs ---- using System.Net.Http.Headers; using System.Text; namespace redb.Tsak.Core.Monitoring.Alerts; /// /// Generic webhook: POSTs the alert JSON to a configured URL. Covers Slack / Teams / Mattermost / /// PagerDuty and any HTTP collector. Uses a plain — no route component, /// no extra dependency. /// public sealed class WebhookAlertChannel : IAlertChannel { private readonly WebhookChannelOptions _options; private readonly HttpClient _http; public WebhookAlertChannel(WebhookChannelOptions options, HttpClient http) { _options = options; _http = http; } public string Name => "webhook"; public bool IsEnabled => _options.Enabled && !string.IsNullOrWhiteSpace(_options.Url); public async Task SendAsync(AlertNotification alert, CancellationToken ct) { using var request = new HttpRequestMessage(HttpMethod.Post, _options.Url) { Content = new StringContent(alert.ToJson(), Encoding.UTF8, "application/json") }; foreach (var (key, value) in _options.Headers) request.Headers.TryAddWithoutValidation(key, value); using var response = await _http.SendAsync(request, ct).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/ContextMetricsCollector.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/Monitoring/ContextMetricsCollector.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Collects per-context metrics from the context manager. /// Aggregates endpoint statistics via . /// public class ContextMetricsCollector { private readonly ITsakContextManager _contextManager; // Track start times for uptime calculation private readonly Dictionary _startTimes = new(); private readonly object _lock = new(); public ContextMetricsCollector(ITsakContextManager contextManager) { _contextManager = contextManager; } /// /// Notify that a context was started (call from coordinator/hosted service). /// public void TrackStarted(string contextName) { lock (_lock) { _startTimes[contextName] = DateTime.UtcNow; } } /// /// Notify that a context was stopped. /// public void TrackStopped(string contextName) { lock (_lock) { _startTimes.Remove(contextName); } } /// /// Collect current metrics for all known contexts. /// public IReadOnlyList CollectAll() { var contexts = _contextManager.GetAllContexts(); var result = new List(contexts.Count); foreach (var (name, ctx) in contexts) result.Add(BuildSnapshot(name, ctx)); return result; } /// /// Collect metrics for a single context by name. /// public ContextMetricsSnapshot? Collect(string contextName) { var ctx = _contextManager.GetContext(contextName); return ctx is null ? null : BuildSnapshot(contextName, ctx); } private ContextMetricsSnapshot BuildSnapshot(string name, IRouteContext ctx) { DateTime? startedAt; lock (_lock) { _startTimes.TryGetValue(name, out var st); startedAt = st == default ? null : st; } var now = DateTime.UtcNow; long totalMessages = 0; long totalErrors = 0; DateTime? lastActivity = null; var endpoints = ctx.GetEndpoints(); foreach (var ep in endpoints) { if (ep is IEndpointStatistics stats) { totalMessages += stats.MessagesIn; totalErrors += stats.Errors; if (stats.LastActivity is { } la && (lastActivity is null || la > lastActivity)) lastActivity = la; } } return new ContextMetricsSnapshot { ContextName = name, IsRunning = ctx.IsStarted, ComponentCount = ctx.GetComponentNames().Count, EndpointCount = endpoints.Count, StartedAt = startedAt, Uptime = startedAt.HasValue ? now - startedAt.Value : TimeSpan.Zero, MessagesProcessed = totalMessages, ErrorCount = totalErrors, LastActivity = lastActivity, InflightCount = (ctx as RouteContext)?.InflightRepository.Count ?? 0, RoutesWithInflight = CountRoutesWithInflight(ctx as RouteContext), }; } private static int CountRoutesWithInflight(RouteContext? ctx) { if (ctx is null) return 0; var inflight = ctx.InflightRepository; return ctx.Routes.Count(r => inflight.CountByRoute(r.RouteId) > 0); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/ContextMetricsSnapshot.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/Monitoring/ContextMetricsSnapshot.cs ---- namespace redb.Tsak.Core.Monitoring; /// /// A snapshot of a single route context's runtime state, /// including aggregated endpoint statistics from . /// public class ContextMetricsSnapshot { public string ContextName { get; set; } = ""; public bool IsRunning { get; set; } public int ComponentCount { get; set; } public int EndpointCount { get; set; } public DateTime? StartedAt { get; set; } public TimeSpan Uptime { get; set; } /// Sum of MessagesIn across all endpoints with statistics. public long MessagesProcessed { get; set; } /// Sum of Errors across all endpoints with statistics. public long ErrorCount { get; set; } /// Most recent LastActivity across all endpoints. public DateTime? LastActivity { get; set; } /// Total in-flight exchanges across all routes. public int InflightCount { get; set; } /// Number of routes that currently have in-flight exchanges. public int RoutesWithInflight { get; set; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/ControlPlaneHealth.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/Monitoring/ControlPlaneHealth.cs ---- using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Shared flag recording whether the _system control-plane context (REST/management API) started /// successfully. If it failed, the host keeps running the business contexts, but the node is NOT fully /// operational — this must be reflected in readiness rather than silently reported healthy /// (review item 4.1). /// public sealed class ControlPlaneHealth { private volatile bool _failed; private volatile string? _reason; /// True when the _system control-plane failed to start. public bool Failed => _failed; /// Human-readable reason for the failure (if any). public string? Reason => _reason; /// Marks the control-plane as failed to start (called once, by the host). public void MarkFailed(string reason) { _reason = reason; _failed = true; } } /// /// Reports the control-plane as when the _system context /// failed to start, so the readiness probe stops reporting a control-plane-less node as ready. /// internal sealed class ControlPlaneHealthContributor : IHealthContributor { private readonly ControlPlaneHealth _state; public ControlPlaneHealthContributor(ControlPlaneHealth state) => _state = state; public void Contribute(HealthEvaluation result) { result.Checks["control-plane"] = _state.Failed ? HealthStatus.Unhealthy : HealthStatus.Healthy; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/DeployAdvisor.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/Monitoring/DeployAdvisor.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Modules; using redb.Tsak.Core.Services; namespace redb.Tsak.Core.Monitoring; /// /// Adds the reasons for a cold deploy that only a plugin knows: Pro's cluster says whether this node is cordoned. /// public interface IDeployAdviceContributor { /// Adds codes of to . void Contribute(ICollection reasons); } /// /// The deploy advice of every alive node of the cluster (Pro). Without it the cluster form answers for this node alone. /// public interface IClusterDeployAdvisor { /// One advice per alive node; stands for the answering node. Task> AdviseAllAsync(DeployAdviceResponse self, CancellationToken ct = default); } /// /// Says whether a new package can be hot swapped into this node or the node needs a cold deploy (stop, replace the /// packages, start). It reads counts only and changes nothing: the deploy stays with the orchestrator. /// public sealed class DeployAdvisor { private readonly ModuleContextMonitor _moduleContexts; private readonly HotReloadOptions _options; private readonly ITsakContextManager _contexts; private readonly HealthCheckService _health; private readonly IEnumerable _contributors; private readonly string _nodeId; public DeployAdvisor(ModuleContextMonitor moduleContexts, IOptions options, ITsakContextManager contexts, IConfiguration configuration, IEnumerable contributors, HealthCheckService health) { _moduleContexts = moduleContexts; _options = options.Value; _contexts = contexts; _contributors = contributors; _health = health; _nodeId = TsakNodeIdentity.Resolve(configuration); } /// The advice for this node, taken now. public DeployAdviceResponse Advise() => Advise(Environment.WorkingSet / (1024.0 * 1024)); internal DeployAdviceResponse Advise(double workingSetMb) { var orphaned = _moduleContexts.OrphanedModuleContexts; var limit = _moduleContexts.MaxOrphanedContexts; var reasons = new List(); if (!StartupProbe.IsFinished(_contexts, _health)) reasons.Add(DeployReasons.StartupNotFinished); if (orphaned > limit) reasons.Add(DeployReasons.OrphanedContextsAboveLimit); else if (!_options.Collectible && orphaned + 1 > limit) reasons.Add(DeployReasons.NextSwapExceedsLimit); if (_options.MaxWorkingSetMb is { } maxWorkingSet && workingSetMb > maxWorkingSet) reasons.Add(DeployReasons.WorkingSetAboveLimit); foreach (var contributor in _contributors) contributor.Contribute(reasons); return new DeployAdviceResponse { NodeId = _nodeId, Verdict = reasons.Count == 0 ? DeployVerdicts.HotSwap : DeployVerdicts.ColdDeploy, Reasons = reasons.Distinct().ToArray(), ModuleContextsAlive = _moduleContexts.ModuleContextsAlive, OrphanedModuleContexts = orphaned, MaxOrphanedModuleContexts = limit, WorkingSetMb = Math.Round(workingSetMb, 1), MaxWorkingSetMb = _options.MaxWorkingSetMb, Collectible = _options.Collectible, }; } } /// Whether the node finished its start: what GET /api/health/startup answers 200 for. internal static class StartupProbe { /// Null when finished, else why not. internal static string? Pending(ITsakContextManager? contexts, HealthCheckService? health) { if (contexts is null) return "Initializing"; if (contexts.GetAllContexts().Count == 0) return "No contexts loaded"; if (health is not null && health.Evaluate().Checks.TryGetValue("cluster", out var cluster) && cluster != HealthStatus.Healthy) return "Cluster coordinator syncing"; return null; } internal static bool IsFinished(ITsakContextManager? contexts, HealthCheckService? health) => Pending(contexts, health) is null; } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/HealthCheckService.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/Monitoring/HealthCheckService.cs ---- using redb.Route.Core; using redb.Tsak.Core.Contracts; using redb.Tsak.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Result of a health check evaluation (internal mutable model). /// public class HealthEvaluation { public HealthStatus Status { get; set; } public string Description { get; set; } = ""; public Dictionary Checks { get; set; } = new(); /// /// What a check found, by the key it reports under in : set by a check that is not healthy and /// can say why (the schema problems of a redb database, say). A check with nothing to explain leaves no entry. /// public Dictionary Details { get; set; } = new(); public DateTime Timestamp { get; set; } = DateTime.UtcNow; } /// /// Evaluates overall system health based on context state and pluggable checks. /// public class HealthCheckService { private readonly ITsakContextManager _contextManager; private readonly MetricsService _metricsService; private readonly IEnumerable _contributors; private readonly IEnumerable _moduleContributors; private readonly RouteWatchdogService? _watchdog; public HealthCheckService( ITsakContextManager contextManager, MetricsService metricsService, IEnumerable contributors, IEnumerable moduleContributors, RouteWatchdogService? watchdog = null) { _contextManager = contextManager; _metricsService = metricsService; _contributors = contributors; _moduleContributors = moduleContributors; _watchdog = watchdog; } /// /// Backward-compatible constructor without module contributors. New code should pass /// enumerations explicitly. /// public HealthCheckService( ITsakContextManager contextManager, MetricsService metricsService, IEnumerable contributors, RouteWatchdogService? watchdog = null) : this(contextManager, metricsService, contributors, Array.Empty(), watchdog) { } /// /// Run all health checks and return aggregated result. /// /// Note: this synchronous overload does NOT execute /// probes (which are async by contract). Use to include them. /// /// public HealthEvaluation Evaluate() { var result = new HealthEvaluation(); CheckContexts(result); CheckRoutes(result); CheckMetrics(result); foreach (var contributor in _contributors) contributor.Contribute(result); if (_watchdog is not null) CheckWatchdog(result); Aggregate(result); return result; } /// /// Worst status wins. The description names the result and, for each check that is not healthy and explains /// itself, what it found, so a readiness failure (Tsak:Health:DegradedNotReady) says why. /// private static void Aggregate(HealthEvaluation result) { result.Status = result.Checks.Values.DefaultIfEmpty(HealthStatus.Healthy).Max(); var summary = result.Status switch { HealthStatus.Healthy => "All checks passed", HealthStatus.Degraded => "Some checks degraded", HealthStatus.Unhealthy => "One or more checks failed", _ => "Unknown" }; var explained = result.Checks .Where(c => c.Value != HealthStatus.Healthy && result.Details.ContainsKey(c.Key)) .Select(c => $"{c.Key}: {result.Details[c.Key]}") .ToList(); result.Description = explained.Count == 0 ? summary : summary + ". " + string.Join(" ", explained); } /// /// Async variant of that additionally awaits all registered /// probes and merges them under module:{name} /// keys. Probe exceptions are caught and translated to /// — a buggy probe never crashes the health endpoint. /// public async Task EvaluateAsync(CancellationToken ct = default) { var result = Evaluate(); await RunModuleContributorsAsync(result, ct).ConfigureAwait(false); // Re-aggregate after module checks may have added entries. Aggregate(result); return result; } private async Task RunModuleContributorsAsync(HealthEvaluation result, CancellationToken ct) { foreach (var contributor in _moduleContributors) { HealthStatus status; try { status = await contributor.CheckHealthAsync(ct).ConfigureAwait(false); } catch { // Buggy probe → Unhealthy, but don't propagate. status = HealthStatus.Unhealthy; } var key = "module:" + contributor.ModuleName; // Tie-break: worst status wins if two contributors share the same module name. if (result.Checks.TryGetValue(key, out var existing) && existing > status) continue; result.Checks[key] = status; } } private void CheckContexts(HealthEvaluation result) { var contexts = _contextManager.GetAllContexts(); if (contexts.Count == 0) { result.Checks["contexts"] = HealthStatus.Degraded; return; } var running = contexts.Count(c => c.Context.IsStarted); if (running == contexts.Count) result.Checks["contexts"] = HealthStatus.Healthy; else if (running > 0) result.Checks["contexts"] = HealthStatus.Degraded; else result.Checks["contexts"] = HealthStatus.Unhealthy; } /// How many Errored routes the routes check names; the rest are counted. public const int MaxListedRoutes = 10; /// /// A route of a started context that is Errored makes the routes check Unhealthy and is named in its /// details: its consumer failed to start and waits for the context's start retry /// (RedbRoute:ConsumerStartRetry), or the retries ran out, so the route takes no messages. Apache Camel's /// supervising route controller reports such a route DOWN in both phases; as there, /// RedbRoute:ConsumerStartRetry:UnhealthyOnRestarting and UnhealthyOnExhausted set to false /// report the phase Degraded instead. Liveness does not read this check: a broker that is down must not restart the /// node. A stopped context is the contexts check's. /// private void CheckRoutes(HealthEvaluation result) { var errored = new List(); var unhealthy = false; foreach (var (name, context) in _contextManager.GetAllContexts()) { if (!context.IsStarted) continue; foreach (var route in context.Routes) { if (route.Status != RouteStatus.Errored) continue; errored.Add(name + "/" + route.RouteId); unhealthy |= context is not RouteContext routeContext || routeContext.IsErroredRouteUnhealthy(route); } } if (errored.Count == 0) { result.Checks["routes"] = HealthStatus.Healthy; return; } result.Checks["routes"] = unhealthy ? HealthStatus.Unhealthy : HealthStatus.Degraded; var listed = string.Join(", ", errored.Take(MaxListedRoutes)); result.Details["routes"] = errored.Count > MaxListedRoutes ? $"{errored.Count} route(s) Errored: {listed} and {errored.Count - MaxListedRoutes} more." : $"{errored.Count} route(s) Errored: {listed}."; } private void CheckMetrics(HealthEvaluation result) { var latest = _metricsService.GetLatest(); if (latest is null) { // No metrics collected yet — degraded (just started) result.Checks["metrics"] = HealthStatus.Degraded; return; } // Memory pressure check: > 90% of system memory is unhealthy if (latest.Memory.WorkingSetMB > 0 && latest.Memory.SystemMemoryUsageMB > 0) { // This is a rough heuristic; only flags extreme states var gcPressure = GC.CollectionCount(2) > 0 && latest.GarbageCollector.Gen2Collections > 100; result.Checks["metrics"] = gcPressure ? HealthStatus.Degraded : HealthStatus.Healthy; } else { result.Checks["metrics"] = HealthStatus.Healthy; } } private void CheckWatchdog(HealthEvaluation result) { if (!_watchdog!.IsEnabled) { result.Checks["watchdog"] = HealthStatus.Healthy; return; } var state = _watchdog.GetState(); if (state.HungExchanges > 0) result.Checks["watchdog"] = HealthStatus.Unhealthy; else if (state.SuspectedExchanges > 0) result.Checks["watchdog"] = HealthStatus.Degraded; else result.Checks["watchdog"] = HealthStatus.Healthy; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/HotReloadHealthContributor.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/Monitoring/HotReloadHealthContributor.cs ---- using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Modules; namespace redb.Tsak.Core.Monitoring; /// /// Reports the node as while more module load contexts stay in memory after Tsak let /// them go than allows: the node keeps working, but only a /// restart gives that memory back. Reads the count the runtime holds, no collection runs here. /// internal sealed class HotReloadHealthContributor(ModuleContextMonitor monitor) : IHealthContributor { /// The key of this check in . internal const string CheckName = "hotreload"; public void Contribute(HealthEvaluation result) { if (monitor.Notice is { } notice) { result.Checks[CheckName] = HealthStatus.Degraded; result.Details[CheckName] = notice; return; } result.Checks[CheckName] = HealthStatus.Healthy; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/LifecycleAuditService.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/Monitoring/LifecycleAuditService.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Tsak.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Ring-buffer audit trail for route lifecycle events. /// Implements indirectly via per-context wrappers /// and exposes methods for context-level events and manual recording. /// public sealed class LifecycleAuditService { private readonly ConcurrentQueue _events = new(); private readonly ILogger _logger; private readonly int _maxEvents; public LifecycleAuditService(ILogger logger, int maxEvents = 1000) { _logger = logger; _maxEvents = maxEvents; } /// Total events currently stored. public int Count => _events.Count; /// /// Registers the audit trail as a lifecycle listener on a RouteContext. /// Creates a per-context wrapper that maps route events to the context name. /// public void RegisterContext(string contextName, IRouteContext context) { if (context is not Route.Core.RouteContext routeCtx) return; routeCtx.AddLifecycleListener(new ContextLifecycleProxy(this, contextName)); } /// Records a context-level event. public void RecordContextEvent(string contextName, LifecycleEventType eventType, string? details = null) { AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, null, eventType, details)); } /// Records an arbitrary event (e.g., from watchdog). public void Record(LifecycleEvent evt) { AddEvent(evt); } /// /// Returns events matching the filters, newest first. /// public IReadOnlyList GetEvents( string? contextName = null, string? routeId = null, LifecycleEventType? eventType = null, DateTime? since = null, int limit = 100) { IEnumerable query = _events.Reverse(); if (contextName is not null) query = query.Where(e => string.Equals(e.ContextName, contextName, StringComparison.OrdinalIgnoreCase)); if (routeId is not null) query = query.Where(e => string.Equals(e.RouteId, routeId, StringComparison.OrdinalIgnoreCase)); if (eventType.HasValue) query = query.Where(e => e.EventType == eventType.Value); if (since.HasValue) query = query.Where(e => e.Timestamp >= since.Value); return query.Take(limit).ToList(); } // ═════════════════════════════════════════════════════════════════ // Per-context lifecycle proxy // ═════════════════════════════════════════════════════════════════ private sealed class ContextLifecycleProxy(LifecycleAuditService audit, string contextName) : IRouteLifecycleListener { public Task OnRouteStarted(string routeId, CancellationToken ct) { audit.AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, routeId, LifecycleEventType.RouteStarted, null)); return Task.CompletedTask; } public Task OnRouteStopped(string routeId, CancellationToken ct) { audit.AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, routeId, LifecycleEventType.RouteStopped, null)); return Task.CompletedTask; } public Task OnRouteSuspending(string routeId, CancellationToken ct) { audit.AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, routeId, LifecycleEventType.RouteSuspended, null)); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { audit.AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, routeId, LifecycleEventType.RouteErrored, ex.Message)); return Task.CompletedTask; } public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { var details = $"Exchange {exchangeId} timed out after {elapsed.TotalSeconds:F0}s"; audit.AddEvent(new LifecycleEvent(DateTime.UtcNow, contextName, routeId, LifecycleEventType.ExchangeTimedOut, details)); return Task.CompletedTask; } } // ═════════════════════════════════════════════════════════════════ // Private // ═════════════════════════════════════════════════════════════════ private void AddEvent(LifecycleEvent evt) { _events.Enqueue(evt); // Trim ring buffer while (_events.Count > _maxEvents) _events.TryDequeue(out _); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/LogRingBuffer.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/Monitoring/LogRingBuffer.cs ---- using redb.Tsak.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// In-memory circular buffer for recent log entries. /// Each entry gets a monotonic ID for incremental fetch. /// Thread-safe via lock. Capacity configured by Tsak:Logs:BufferSize. /// public sealed class LogRingBuffer { private readonly LogEntry[] _buffer; private int _head; private int _count; private long _nextId; private readonly object _lock = new(); public int Capacity { get; } public LogRingBuffer(int capacity = 2000) { Capacity = capacity; _buffer = new LogEntry[capacity]; } /// Add entry with auto-assigned ID. public void Add(DateTimeOffset timestamp, string level, string message, string? source, string? exception) { lock (_lock) { var entry = new LogEntry { Id = _nextId++, Timestamp = timestamp, Level = level, Message = message, Source = source, Exception = exception }; _buffer[_head] = entry; _head = (_head + 1) % Capacity; if (_count < Capacity) _count++; } } /// Get entries newer than afterId (oldest first). Supports level filter. public IReadOnlyList GetAfter(long afterId, int limit = 500, string? levelFilter = null) { lock (_lock) { var result = new List(Math.Min(limit, _count)); // Walk oldest → newest for (int i = _count - 1; i >= 0 && result.Count < limit; i--) { var idx = (_head - 1 - i + Capacity) % Capacity; var entry = _buffer[idx]; if (entry is null) continue; if (entry.Id <= afterId) continue; if (levelFilter is not null && !string.Equals(entry.Level, levelFilter, StringComparison.OrdinalIgnoreCase)) continue; result.Add(entry); } return result; } } /// Get most recent entries, newest first. Optional limit and level filter. public IReadOnlyList GetRecent(int limit = 100, string? levelFilter = null) { lock (_lock) { var result = new List(Math.Min(limit, _count)); for (int i = 0; i < _count && result.Count < limit; i++) { var idx = (_head - 1 - i + Capacity) % Capacity; var entry = _buffer[idx]; if (entry is null) continue; if (levelFilter is not null && !string.Equals(entry.Level, levelFilter, StringComparison.OrdinalIgnoreCase)) continue; result.Add(entry); } return result; } } /// /// Get entries older than , newest first: the page that precedes one already shown /// ("load older"). Supports level filter. Empty once the buffer holds nothing older. /// public IReadOnlyList GetBefore(long beforeId, int limit = 200, string? levelFilter = null) { lock (_lock) { var result = new List(Math.Min(limit, _count)); for (int i = 0; i < _count && result.Count < limit; i++) { var idx = (_head - 1 - i + Capacity) % Capacity; var entry = _buffer[idx]; if (entry is null) continue; if (entry.Id >= beforeId) continue; if (levelFilter is not null && !string.Equals(entry.Level, levelFilter, StringComparison.OrdinalIgnoreCase)) continue; result.Add(entry); } return result; } } public int Count { get { lock (_lock) return _count; } } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/MemoryUsageEnricher.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/Monitoring/MemoryUsageEnricher.cs ---- using Serilog.Core; using Serilog.Events; namespace redb.Tsak.Core.Monitoring; /// /// Serilog enricher that adds current GC memory usage (KB) to every log event. /// Register via: .Enrich.With<MemoryUsageEnricher>() /// public class MemoryUsageEnricher : ILogEventEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { var memoryKb = GC.GetTotalMemory(false) / 1024; logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("MemoryUsage", memoryKb)); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/MetricsCollectionService.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/Monitoring/MetricsCollectionService.cs ---- using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace redb.Tsak.Core.Monitoring; /// /// Background service that periodically collects process metrics /// and stores them in . /// public class MetricsCollectionService : BackgroundService { private readonly MetricsService _metricsService; private readonly ILogger _logger; private readonly int _intervalSeconds; public MetricsCollectionService( MetricsService metricsService, ILogger logger, IOptions options) { _metricsService = metricsService; _logger = logger; _intervalSeconds = options.Value.CollectionIntervalSeconds; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Metrics collection started, interval: {Interval}s", _intervalSeconds); // Small delay to let the app initialize await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); while (!stoppingToken.IsCancellationRequested) { try { var point = _metricsService.CollectCurrentMetrics(); _metricsService.AddPoint(point); // Log every ~60 seconds var stored = _metricsService.StoredPointsCount; if (stored % Math.Max(1, 60 / _intervalSeconds) == 0) { _logger.LogDebug("Metrics: {Count} points stored, memory: {MemoryMB:F1} MB", stored, point.Memory.WorkingSetMB); } } catch (Exception ex) { _logger.LogError(ex, "Error collecting metrics"); } await Task.Delay(TimeSpan.FromSeconds(_intervalSeconds), stoppingToken); } _logger.LogInformation("Metrics collection stopped"); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/MetricsOptions.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/Monitoring/MetricsOptions.cs ---- namespace redb.Tsak.Core.Monitoring; /// /// Configuration for the metrics collection subsystem. /// Bound from Tsak:Metrics section. /// public class MetricsOptions { /// /// Interval in seconds between metric collection ticks. Default 10. /// public int CollectionIntervalSeconds { get; set; } = 10; /// /// Hours of history to keep in the circular buffer. Default 12. /// Together with CollectionIntervalSeconds determines buffer capacity: /// 12h × 3600 / 10 = 4320 points. /// public int HistoryHours { get; set; } = 12; /// /// Computed max data points for the circular buffer. /// internal int MaxPoints => HistoryHours * 3600 / Math.Max(1, CollectionIntervalSeconds); } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/MetricsPoint.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/Monitoring/MetricsPoint.cs ---- namespace redb.Tsak.Core.Monitoring; /// /// A single snapshot of process and system metrics at a point in time. /// public class MetricsPoint { public DateTime Timestamp { get; set; } public long TimestampMs { get; set; } public CpuMetrics Cpu { get; set; } = new(); public MemoryMetrics Memory { get; set; } = new(); public ThreadingMetrics Threading { get; set; } = new(); public GcMetrics GarbageCollector { get; set; } = new(); } public class CpuMetrics { public double ProcessUsage { get; set; } public double SystemUsage { get; set; } } public class MemoryMetrics { public double WorkingSetMB { get; set; } public double PrivateMemoryMB { get; set; } public double VirtualMemoryMB { get; set; } public double GCMemoryMB { get; set; } public double SystemMemoryUsageMB { get; set; } } public class ThreadingMetrics { public int ActiveThreads { get; set; } public long ThreadPoolPendingWork { get; set; } } public class GcMetrics { public int Gen0Collections { get; set; } public int Gen1Collections { get; set; } public int Gen2Collections { get; set; } public double TotalMemoryMB { get; set; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/MetricsService.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/Monitoring/MetricsService.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Extensions.Options; namespace redb.Tsak.Core.Monitoring; /// /// In-memory metrics store with a circular buffer. /// Provides collection of process/system metrics and history queries. /// Cross-platform: Windows, Linux, macOS. /// public class MetricsService { private readonly ConcurrentQueue _buffer = new(); private readonly object _lock = new(); private readonly int _maxPoints; // Process CPU tracking (static for delta calculation between calls) private DateTime _lastCpuCheck = DateTime.UtcNow; private TimeSpan _lastProcessCpuTime = TimeSpan.Zero; private double _lastProcessCpuUsage; // System CPU tracking (delta between calls) private DateTime _lastSysCpuCheck = DateTime.UtcNow; private long _lastSysCpuTotalTicks; private long _lastSysCpuIdleTicks; private double _lastSysCpuUsage; public MetricsService(IOptions options) { _maxPoints = options.Value.MaxPoints; } /// /// Add a metrics data point to the circular buffer. /// Evicts oldest entries when buffer is full. /// public void AddPoint(MetricsPoint point) { lock (_lock) { _buffer.Enqueue(point); while (_buffer.Count > _maxPoints) _buffer.TryDequeue(out _); } } /// /// Get historical metric data for the given time window. /// public IReadOnlyList GetHistory(int minutes) { var cutoff = DateTime.UtcNow.AddMinutes(-minutes); lock (_lock) { return _buffer .Where(p => p.Timestamp >= cutoff) .OrderBy(p => p.Timestamp) .ToList(); } } /// /// Get the latest (most recent) metrics point, or null if empty. /// public MetricsPoint? GetLatest() { lock (_lock) { return _buffer.LastOrDefault(); } } /// /// Get a full snapshot: latest point + buffer size. /// public (MetricsPoint? Latest, int StoredPoints) GetSnapshot() { lock (_lock) { return (_buffer.LastOrDefault(), _buffer.Count); } } /// /// Number of data points currently stored. /// public int StoredPointsCount => _buffer.Count; /// /// Collect current process and system metrics. /// public MetricsPoint CollectCurrentMetrics() { var process = Process.GetCurrentProcess(); var timestamp = DateTime.UtcNow; return new MetricsPoint { Timestamp = timestamp, TimestampMs = ((DateTimeOffset)timestamp).ToUnixTimeMilliseconds(), Cpu = new CpuMetrics { ProcessUsage = GetProcessCpuUsage(process), SystemUsage = GetSystemCpuUsage() }, Memory = new MemoryMetrics { WorkingSetMB = Math.Round(process.WorkingSet64 / 1024.0 / 1024.0, 1), PrivateMemoryMB = Math.Round(process.PrivateMemorySize64 / 1024.0 / 1024.0, 1), VirtualMemoryMB = Math.Round(process.VirtualMemorySize64 / 1024.0 / 1024.0, 1), GCMemoryMB = Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0, 1), SystemMemoryUsageMB = GetSystemMemoryUsage() }, Threading = new ThreadingMetrics { ActiveThreads = process.Threads.Count, ThreadPoolPendingWork = ThreadPool.PendingWorkItemCount }, GarbageCollector = new GcMetrics { Gen0Collections = GC.CollectionCount(0), Gen1Collections = GC.CollectionCount(1), Gen2Collections = GC.CollectionCount(2), TotalMemoryMB = Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0, 1) } }; } #region CPU measurement private double GetProcessCpuUsage(Process process) { try { var now = DateTime.UtcNow; var currentCpuTime = process.TotalProcessorTime; if (_lastProcessCpuTime == TimeSpan.Zero) { _lastCpuCheck = now; _lastProcessCpuTime = currentCpuTime; return 0; } var timeDiff = now - _lastCpuCheck; var cpuDiff = currentCpuTime - _lastProcessCpuTime; if (timeDiff.TotalMilliseconds > 0) { var usage = cpuDiff.TotalMilliseconds / timeDiff.TotalMilliseconds * 100 / Environment.ProcessorCount; _lastProcessCpuUsage = Math.Round(Math.Clamp(usage, 0, 100), 1); } _lastCpuCheck = now; _lastProcessCpuTime = currentCpuTime; return _lastProcessCpuUsage; } catch { return 0; } } private double GetSystemCpuUsage() { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return GetLinuxSystemCpu(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return GetWindowsSystemCpu(); return 0; } catch { return 0; } } private double GetLinuxSystemCpu() { var lines = File.ReadAllLines("/proc/stat"); var cpuLine = lines.FirstOrDefault(l => l.StartsWith("cpu ")); if (cpuLine is null) return 0; var parts = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 8) return 0; var idle = long.Parse(parts[4]) + long.Parse(parts[5]); var total = parts.Skip(1).Take(7).Sum(long.Parse); var deltaTotal = total - _lastSysCpuTotalTicks; var deltaIdle = idle - _lastSysCpuIdleTicks; _lastSysCpuTotalTicks = total; _lastSysCpuIdleTicks = idle; if (deltaTotal <= 0) return _lastSysCpuUsage; _lastSysCpuUsage = Math.Round(Math.Clamp((double)(deltaTotal - deltaIdle) / deltaTotal * 100, 0, 100), 1); return _lastSysCpuUsage; } private double GetWindowsSystemCpu() { var now = DateTime.UtcNow; var elapsed = (now - _lastSysCpuCheck).TotalMilliseconds; _lastSysCpuCheck = now; if (elapsed < 100) return _lastSysCpuUsage; var processes = Process.GetProcesses(); try { long totalTicks = 0; foreach (var p in processes) { try { totalTicks += p.TotalProcessorTime.Ticks; } catch { /* access denied for some system processes */ } } var deltaTicks = totalTicks - _lastSysCpuTotalTicks; _lastSysCpuTotalTicks = totalTicks; if (deltaTicks <= 0) return _lastSysCpuUsage; // Convert delta ticks to percentage: // deltaTicks is CPU time consumed across all cores during elapsed interval var elapsedTicks = (long)(elapsed * TimeSpan.TicksPerMillisecond); var totalCapacity = elapsedTicks * Environment.ProcessorCount; _lastSysCpuUsage = totalCapacity > 0 ? Math.Round(Math.Clamp((double)deltaTicks / totalCapacity * 100, 0, 100), 1) : 0; return _lastSysCpuUsage; } finally { foreach (var p in processes) p.Dispose(); } } #endregion #region Memory measurement private static double GetSystemMemoryUsage() { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return GetLinuxSystemMemory(); // Windows/macOS: fallback to managed memory return Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0, 1); } catch { return 0; } } private static double GetLinuxSystemMemory() { var lines = File.ReadAllLines("/proc/meminfo"); long memTotal = 0, memAvailable = 0; foreach (var line in lines) { if (line.StartsWith("MemTotal:")) { var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length >= 2 && long.TryParse(parts[1], out var total)) memTotal = total * 1024; // kB → bytes } else if (line.StartsWith("MemAvailable:")) { var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length >= 2 && long.TryParse(parts[1], out var available)) memAvailable = available * 1024; } } if (memTotal > 0) return Math.Round((memTotal - memAvailable) / 1024.0 / 1024.0, 1); return 0; } #endregion } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/NodeStartTime.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/Monitoring/NodeStartTime.cs ---- using System.Diagnostics; namespace redb.Tsak.Core.Monitoring; /// /// When this node started: the start time of its process, read once. GET /api/system/info (start time and /// uptime) and the cluster node registry (StartedAt of the node record) both report this value, so the /// monitoring page and the topology agree, and neither depends on when it was first asked or on a re-registration. /// public static class NodeStartTime { /// The start time of this process, in UTC. public static DateTimeOffset Value { get; } = Read(); private static DateTimeOffset Read() { using var process = Process.GetCurrentProcess(); return new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/RedbSchemaHealthContributor.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/Monitoring/RedbSchemaHealthContributor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models; using redb.Route.RedbCore.Extensions; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Reports the redb databases of the worker as while one of them has schema /// problems that need a person (): the host's own storage and every named /// instance the contexts declare. The service keeps working, but redb logs the problem as an error at every start until /// it is resolved; this check lets monitoring see it too. Degraded as well while a named instance did not start cleanly: /// its schema bootstrap failed (the instance is registered without it), or its database refused the start (the instance /// is not registered), with the kind of the failure; its text is in the node log. /// /// It reads the list the last start or scheme synchronization left, which costs no database round trip; it never runs /// , so a health poll does not query the schema. The list is held per /// database, so any instance of it sees what the start found. /// /// internal sealed class RedbSchemaHealthContributor : IHealthContributor { /// The key of this check in . internal const string CheckName = "redb"; /// Where the fix of a schema problem is described, in the public redb repository. internal const string UpgradingLink = "https://github.com/redbase-app/redb/blob/main/UPGRADING.md#duplicate-root-structures"; // A health response stays readable: the first problems are spelled out, the rest are counted. private const int ShownProblems = 3; private readonly IServiceScopeFactory _scopes; private readonly ITsakContextManager _contexts; private readonly ILogger? _logger; private readonly Services.NamedRedbStartFailures? _startFailures; public RedbSchemaHealthContributor(IServiceScopeFactory scopes, ITsakContextManager contexts, ILogger? logger = null) : this(scopes, contexts, (contexts as Services.TsakContextManager)?.NamedRedbStartFailures, logger) { } internal RedbSchemaHealthContributor(IServiceScopeFactory scopes, ITsakContextManager contexts, Services.NamedRedbStartFailures? startFailures, ILogger? logger = null) { _startFailures = startFailures; _scopes = scopes; _contexts = contexts; _logger = logger; } public void Contribute(HealthEvaluation result) { var databases = 0; var problems = new List<(string Database, RedbSchemaProblem Problem)>(); try { using var scope = _scopes.CreateScope(); if (scope.ServiceProvider.GetService() is { } host) { databases++; problems.AddRange(host.SchemaProblems.Select(p => ("host", p))); } } catch (Exception ex) { // The health endpoint answers whatever the host's redb wiring does; a service that cannot even be built // fails its own start loudly, this check does not repeat that. _logger?.LogDebug(ex, "Health: the host's redb service could not be resolved"); } foreach (var instance in _contexts.GetNamedRedbInstances()) { if (instance.ContextName is not { } contextName || _contexts.GetContext(contextName) is not { } context) continue; try { // No exchange: the instance the context registered. Reading its list opens no connection. var named = context.GetRedbService(instance.Name); databases++; problems.AddRange(named.SchemaProblems.Select(p => ($"{contextName}/{instance.Name}", p))); } catch (InvalidOperationException ex) { // Declared but not registered (its container failed to build): the context manager logged that already. _logger?.LogDebug(ex, "Health: named redb '{Name}' of context {Context} is not registered", instance.Name, contextName); } } // Named instances whose start went wrong: one that is registered without its schema bootstrap, and one that // was not registered at all. The second is in no list above, so it counts as a database here. var startFailures = _startFailures?.Current ?? []; databases += startFailures.Count(f => !f.Registered); if (databases == 0) return; // a worker without redb storage has nothing to report here if (problems.Count == 0 && startFailures.Count == 0) { result.Checks[CheckName] = HealthStatus.Healthy; return; } result.Checks[CheckName] = HealthStatus.Degraded; var parts = new List(2); if (startFailures.Count > 0) { var shownFailures = startFailures.Take(ShownProblems).Select(f => $"[{f.ContextName}/{f.InstanceName}] {(f.Registered ? "not initialized" : "not registered")} ({f.Kind}), see the node log."); var moreFailures = startFailures.Count > ShownProblems ? $" And {startFailures.Count - ShownProblems} more." : ""; parts.Add($"{startFailures.Count} named redb instance(s) did not start cleanly. {string.Join(" ", shownFailures)}{moreFailures}"); } if (problems.Count > 0) { var shown = problems.Take(ShownProblems).Select(p => $"[{p.Database}] {p.Problem.Message}"); var more = problems.Count > ShownProblems ? $" And {problems.Count - ShownProblems} more." : ""; parts.Add($"{problems.Count} schema problem(s) need a person. {string.Join(" ", shown)}{more} See {UpgradingLink}"); } result.Details[CheckName] = string.Join(" ", parts); } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/RingBufferSink.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/Monitoring/RingBufferSink.cs ---- using Serilog.Core; using Serilog.Events; namespace redb.Tsak.Core.Monitoring; /// /// Serilog sink that feeds structured log events into . /// Registered via .WriteTo.Sink() in Program.cs. /// public sealed class RingBufferSink : ILogEventSink { private readonly LogRingBuffer _buffer; public RingBufferSink(LogRingBuffer buffer) { _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); } public void Emit(LogEvent logEvent) { var source = logEvent.Properties.TryGetValue("SourceContext", out var sc) ? sc.ToString().Trim('"') : null; _buffer.Add( logEvent.Timestamp, logEvent.Level.ToShortString(), logEvent.RenderMessage(), source, logEvent.Exception?.ToString()); } } internal static class LogEventLevelExtensions { public static string ToShortString(this LogEventLevel level) => level switch { LogEventLevel.Verbose => "VRB", LogEventLevel.Debug => "DBG", LogEventLevel.Information => "INF", LogEventLevel.Warning => "WRN", LogEventLevel.Error => "ERR", LogEventLevel.Fatal => "FTL", _ => level.ToString() }; } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/RouteWatchdogService.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/Monitoring/RouteWatchdogService.cs ---- using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Monitoring; /// /// Background service that periodically scans all route contexts for /// suspected (long-running) and hung (stale) in-flight exchanges. /// Emits log warnings/errors and maintains a queryable alert state. /// public sealed class RouteWatchdogService : BackgroundService { private readonly ITsakContextManager _contextManager; private readonly ILogger _logger; private readonly WatchdogOptions _options; private readonly Alerts.AlertDispatcher? _alerts; private readonly object _lock = new(); private volatile bool _enabled; private DateTime _lastCheckAt; private int _autoRestartsPerformed; private readonly List _activeAlerts = []; // Keys already reported to the alert dispatcher; lets us fire only on NEW alerts, since the // scan rebuilds the full snapshot every cycle. The dispatcher also dedups by time window. private readonly HashSet _notifiedKeys = []; // Planned waits already written to the log (exchange id and the wait's end): one line per wait, not one per scan. private readonly HashSet _announcedWaits = new(StringComparer.Ordinal); public RouteWatchdogService( ITsakContextManager contextManager, ILogger logger, IOptions options, Alerts.AlertDispatcher? alerts = null) { _contextManager = contextManager; _logger = logger; _options = options.Value; _enabled = _options.Enabled; _alerts = alerts; } /// Enables the watchdog at runtime. public void Enable() { _enabled = true; _logger.LogInformation("Route watchdog enabled"); } /// Disables the watchdog at runtime. public void Disable() { _enabled = false; lock (_lock) _activeAlerts.Clear(); _logger.LogInformation("Route watchdog disabled"); } /// Returns true if the watchdog is currently enabled. public bool IsEnabled => _enabled; /// Returns a snapshot of the current watchdog state. public WatchdogState GetState() { lock (_lock) { return new WatchdogState { LastCheckAt = _lastCheckAt, SuspectedExchanges = _activeAlerts.Count(a => a.Level == "Suspected"), HungExchanges = _activeAlerts.Count(a => a.Level == "Hung"), AutoRestartsPerformed = _autoRestartsPerformed, Enabled = _enabled, ActiveAlerts = _activeAlerts.ToList() }; } } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation( "Route watchdog started, interval: {Interval}s, suspected: {Suspected}m, hung: {Hung}m", _options.CheckIntervalSeconds, _options.SuspectedThresholdMinutes, _options.HungThresholdMinutes); await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken); while (!stoppingToken.IsCancellationRequested) { if (_enabled) { try { await ScanAllContextsAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Error during watchdog scan"); } } await Task.Delay(TimeSpan.FromSeconds(_options.CheckIntervalSeconds), stoppingToken); } _logger.LogInformation("Route watchdog stopped"); } internal async Task ScanAllContextsAsync(CancellationToken ct) { var now = DateTime.UtcNow; var suspectedThreshold = TimeSpan.FromMinutes(_options.SuspectedThresholdMinutes); var hungThreshold = TimeSpan.FromMinutes(_options.HungThresholdMinutes); var newAlerts = new List(); // One restart per context per scan (review 2026-09-02, С20): ten hung exchanges used to // trigger ten back-to-back stop/start cycles of the same context within a single scan, // repeatedly killing freshly arrived in-flight work. var restartedThisScan = new HashSet(StringComparer.OrdinalIgnoreCase); var seenWaits = new HashSet(StringComparer.Ordinal); foreach (var (contextName, context) in _contextManager.GetAllContexts()) { if (context is not RouteContext routeCtx) continue; var inflights = routeCtx.InflightRepository.Browse(); foreach (var inflight in inflights) { // A planned wait (a redelivery delay, a delay step) is not a hang: the exchange is skipped while it lasts, // and afterwards it is measured from the end of the wait, so a redelivered attempt is judged on its own. if (inflight.WaitingUntil is { } waitingUntil && waitingUntil > now) { if (_announcedWaits.Add($"{inflight.ExchangeId}|{waitingUntil.Ticks}")) _logger.LogInformation( "Exchange {ExchangeId} in route {RouteId} (context: {Context}) waits for a planned redelivery or delay until {Until:O}; the watchdog does not count the wait", inflight.ExchangeId, inflight.RouteId, contextName, waitingUntil); seenWaits.Add($"{inflight.ExchangeId}|{waitingUntil.Ticks}"); continue; } var elapsed = now - inflight.BusySince; if (elapsed >= hungThreshold) { _logger.LogError( "Hung exchange {ExchangeId} in route {RouteId} (context: {Context}), elapsed: {Elapsed:F0}s", inflight.ExchangeId, inflight.RouteId, contextName, elapsed.TotalSeconds); newAlerts.Add(new WatchdogAlert { ExchangeId = inflight.ExchangeId, RouteId = inflight.RouteId, ContextName = contextName, Level = "Hung", DetectedAt = now, ElapsedSeconds = elapsed.TotalSeconds }); if (_options.AutoRestartHungRoutes && !ct.IsCancellationRequested && contextName != "_system" // never auto-restart the management API context (С20) && restartedThisScan.Add(contextName)) { await TryAutoRestartRouteAsync(contextName, inflight.RouteId, ct); } } else if (elapsed >= suspectedThreshold) { _logger.LogWarning( "Suspected exchange {ExchangeId} in route {RouteId} (context: {Context}), elapsed: {Elapsed:F0}s", inflight.ExchangeId, inflight.RouteId, contextName, elapsed.TotalSeconds); newAlerts.Add(new WatchdogAlert { ExchangeId = inflight.ExchangeId, RouteId = inflight.RouteId, ContextName = contextName, Level = "Suspected", DetectedAt = now, ElapsedSeconds = elapsed.TotalSeconds }); } } } // Waits that ended are forgotten, so the set holds only the current ones. _announcedWaits.IntersectWith(seenWaits); lock (_lock) { _activeAlerts.Clear(); _activeAlerts.AddRange(newAlerts); _lastCheckAt = now; } NotifyNewAlerts(newAlerts); } /// /// Pushes genuinely new alerts to the dispatcher. The scan rebuilds the whole snapshot each /// cycle, so we track already-notified keys here and let the dispatcher additionally dedup by /// time window. Keys that clear (exchange completed) are forgotten, so a later recurrence /// alerts again. /// private void NotifyNewAlerts(List current) { if (_alerts is null || !_alerts.IsActive) return; var currentKeys = new HashSet(); foreach (var a in current) { var key = $"{a.Level}|{a.ContextName}|{a.RouteId}|{a.ExchangeId}"; currentKeys.Add(key); if (_notifiedKeys.Add(key)) { _alerts.Enqueue(new Alerts.AlertNotification { Level = a.Level, Title = $"{a.Level} exchange in route '{a.RouteId}'", ContextName = a.ContextName, RouteId = a.RouteId, ExchangeId = a.ExchangeId, ElapsedSeconds = a.ElapsedSeconds, Timestamp = a.DetectedAt }); } } _notifiedKeys.IntersectWith(currentKeys); // forget cleared alerts } private async Task TryAutoRestartRouteAsync(string contextName, string routeId, CancellationToken ct) { try { _logger.LogWarning("Auto-restarting context {Context} due to hung route {RouteId}", contextName, routeId); using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(TimeSpan.FromSeconds(_options.AutoRestartTimeoutSeconds)); await _contextManager.RestartContextAsync(contextName, cts.Token); Interlocked.Increment(ref _autoRestartsPerformed); _logger.LogInformation("Auto-restart completed for context {Context}", contextName); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (OperationCanceledException) { // The per-restart timeout elapsed — possibly BETWEEN the stop and the start, leaving // the context down (review 2026-09-02, С20). Try to bring it back once, unbounded by // the elapsed budget; a context left stopped is worse than a slow start. _logger.LogError( "Auto-restart of context {Context} timed out after {Timeout}s — attempting a recovery start", contextName, _options.AutoRestartTimeoutSeconds); try { await _contextManager.StartContextAsync(contextName, ignoreAutoStart: true); _logger.LogInformation("Recovery start completed for context {Context}", contextName); } catch (Exception ex) { _logger.LogError(ex, "Recovery start failed for context {Context} — it may be stopped", contextName); } } catch (Exception ex) { _logger.LogError(ex, "Auto-restart failed for context {Context}", contextName); } } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/TsakMetricsSnapshotProps.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/Monitoring/TsakMetricsSnapshotProps.cs ---- using redb.Core.Attributes; namespace redb.Tsak.Core.Monitoring; /// /// Props class of the per-node metrics snapshots stored in redb. /// Each node writes its snapshot periodically (ClusterReportIntervalSeconds). /// Used for cluster-wide metrics aggregation. /// [RedbScheme("_tsak_metrics")] public class TsakMetricsSnapshotProps { public string NodeId { get; set; } = string.Empty; public DateTimeOffset CollectedAt { get; set; } // CPU public double CpuProcess { get; set; } public double CpuSystem { get; set; } // Memory (MB) public double MemoryWorkingSet { get; set; } public double MemoryGC { get; set; } // Threading public int ActiveThreads { get; set; } // GC public int GcGen0 { get; set; } public int GcGen1 { get; set; } public int GcGen2 { get; set; } // Context summary public int ContextCount { get; set; } public int ContextsRunning { get; set; } // Module load contexts (Modules.ModuleContextMonitor). A node of an older version writes neither: 0 in its record. public int ModuleContextsAlive { get; set; } public int OrphanedModuleContexts { get; set; } } Path: redb-tsak/src/redb.Tsak.Core/Monitoring/WatchdogOptions.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/Monitoring/WatchdogOptions.cs ---- namespace redb.Tsak.Core.Monitoring; /// /// Configuration for the Route Watchdog background service. /// Binds to the Tsak:Watchdog section in appsettings.json. /// public class WatchdogOptions { /// Check interval in seconds. Default: 15. public int CheckIntervalSeconds { get; set; } = 15; /// /// Threshold in minutes for a "suspected" exchange. Default: 5. /// Exchanges older than this emit a WARNING. Supports fractional values (e.g. 0.5 = 30s). /// public double SuspectedThresholdMinutes { get; set; } = 5; /// /// Threshold in minutes for a "hung" exchange. Default: 30. /// Exchanges older than this emit an ERROR and trigger alerts. Supports fractional values. /// public double HungThresholdMinutes { get; set; } = 30; /// /// Whether to auto-restart routes with hung exchanges. Default: false. /// public bool AutoRestartHungRoutes { get; set; } /// /// Timeout in seconds for auto-restart operations. Default: 60. /// public int AutoRestartTimeoutSeconds { get; set; } = 60; /// /// Whether the watchdog is enabled. Default: true. /// Can be toggled at runtime via the API. /// public bool Enabled { get; set; } = true; } Path: redb-tsak/src/redb.Tsak.Core/Quartz/QuartzSchemaInitializer.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/Quartz/QuartzSchemaInitializer.cs ---- using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Audit; namespace redb.Tsak.Core.Quartz; /// /// Ensures Quartz.NET tables exist in the database when AdoJobStore is configured. /// Registered as BEFORE QuartzHostedService so that /// tables are created before Quartz validates the schema. /// Uses raw ADO.NET connection (not redb) because redb may not be initialized yet. The provider's /// connection string, script and ADO factory come from . /// internal sealed class QuartzSchemaInitializer : IHostedService { private readonly IConfiguration _configuration; private readonly ILogger _logger; public QuartzSchemaInitializer(IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { var jobStoreType = _configuration["Quartz:quartz.jobStore.type"]; if (string.IsNullOrEmpty(jobStoreType) || !jobStoreType.Contains("AdoJobStore", StringComparison.OrdinalIgnoreCase)) { _logger.LogDebug("Quartz uses RAMJobStore — skipping schema initialization"); return; } var dialect = TsakSqlDialect.ForQuartz(_configuration); var connStr = _configuration.GetConnectionString(dialect.ConnectionStringName); if (string.IsNullOrEmpty(connStr)) { _logger.LogWarning("No connection string found for Quartz schema initialization"); return; } var resourceName = $"QuartzSchema.{dialect.ScriptSuffix}"; var sql = ReadEmbeddedScript(resourceName); if (sql is null) { _logger.LogWarning("Quartz schema script '{Resource}' not found in embedded resources", resourceName); return; } _logger.LogInformation("Applying Quartz schema ({Provider})...", _configuration["Tsak:Redb:Provider"]?.ToLowerInvariant() ?? "postgres"); await using var conn = AuditStorage.CreateConnection(dialect.Provider, connStr); await conn.OpenAsync(cancellationToken); await ApplyAsync(conn, QuartzSchemaMigration.For(dialect.Provider), sql, _logger, cancellationToken); _logger.LogInformation("Quartz schema applied successfully"); } /// /// Runs the create script and adds the columns newer Quartz releases probe for, both under one lock, so nodes /// starting together neither race on CREATE nor add a column twice. /// internal static async Task ApplyAsync(System.Data.Common.DbConnection connection, QuartzSchemaMigration migration, string createScript, ILogger logger, CancellationToken ct) { var transaction = await migration.LockAsync(connection, ct); var succeeded = false; try { await QuartzSchemaMigration.ExecuteAsync(connection, transaction, createScript, ct); await migration.AddMissingColumnsAsync(connection, transaction, logger, ct); succeeded = true; } finally { await migration.UnlockAsync(connection, transaction, succeeded); } } 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/Quartz/QuartzSchemaMigration.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/Quartz/QuartzSchemaMigration.cs ---- using System.Data.Common; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Audit; namespace redb.Tsak.Core.Quartz; /// /// Brings the Quartz tables of an existing installation up to the columns Quartz.NET 3.22 probes for at start. /// CREATE TABLE IF NOT EXISTS leaves an existing table as it is, so a database created before 3.17 lacks them, /// and Quartz then logs a warning and runs without what they carry: /// /// 3.17 MISFIRE_ORIG_FIRE_TIME: the time a misfired trigger was due, so ScheduledFireTimeUtc /// (the route's CamelQuartzScheduledFireTime) stays that time under the fire-now misfire policies instead of /// becoming the actual fire time. /// 3.18 EXECUTION_GROUP on triggers and fired triggers: the per-node limit of execution groups is /// applied in the acquire query instead of by filtering in memory. /// 3.19 PREFERRED_NODE and PREFERRED_NODE_AUTO: node affinity, only with both. /// /// The 3.20 index alignment drops and creates indexes and is left to the administrator's script. /// /// Every column is looked up again after the lock is taken, so nodes starting together add each column once. A role /// that may not ALTER the tables gets a warning naming the administrator's script and the worker goes on without the /// columns; any other failure propagates. /// /// internal abstract class QuartzSchemaMigration { /// A column a Quartz release added to an existing table. internal sealed record Column(string Table, string Name, string Since, string PostgresType, string SqlServerType, string SqliteType); /// The columns added at start, in the order Quartz introduced them. internal static readonly IReadOnlyList Columns = [ new("QRTZ_TRIGGERS", "MISFIRE_ORIG_FIRE_TIME", "3.17", "BIGINT NULL", "bigint NULL", "INTEGER NULL"), new("QRTZ_TRIGGERS", "EXECUTION_GROUP", "3.18", "VARCHAR(200) NULL", "nvarchar(200) NULL", "NVARCHAR(200) NULL"), new("QRTZ_FIRED_TRIGGERS", "EXECUTION_GROUP", "3.18", "VARCHAR(200) NULL", "nvarchar(200) NULL", "NVARCHAR(200) NULL"), new("QRTZ_TRIGGERS", "PREFERRED_NODE", "3.19", "VARCHAR(200) NULL", "nvarchar(200) NULL", "NVARCHAR(200) NULL"), new("QRTZ_TRIGGERS", "PREFERRED_NODE_AUTO", "3.19", "BOOL NOT NULL DEFAULT FALSE", "bit NOT NULL DEFAULT 0", "BIT NOT NULL DEFAULT 0"), ]; internal static QuartzSchemaMigration For(AuditProvider provider) => provider switch { AuditProvider.SqlServer => new SqlServer(), AuditProvider.Sqlite => new Sqlite(), _ => new Postgres(), }; /// File name of the administrator's script, shipped beside the worker under sql/quartz/. internal abstract string ScriptName { get; } /// Where the administrator's script lies in this installation. internal string ScriptPath => Path.Combine(AppContext.BaseDirectory, "sql", "quartz", ScriptName); /// /// Takes the lock that serializes the schema work of nodes starting together. The returned transaction, when /// there is one, is the lock itself (SQLite) and every command of the migration runs in it. /// internal abstract Task LockAsync(DbConnection connection, CancellationToken ct); /// Releases what took; a lock that is a transaction commits only when the work succeeded. internal abstract Task UnlockAsync(DbConnection connection, DbTransaction? transaction, bool succeeded); internal abstract string ColumnExistsSql(Column column); internal abstract string AddColumnSql(Column column); /// True when the role may not alter the table: the only failure the migration does not propagate. internal abstract bool IsPermissionDenied(Exception exception); /// /// Adds the columns the tables lack. Run under the lock, after the create script. Returns the columns added; when /// the role may not alter the tables, logs a warning, stops and returns what was added before. /// internal async Task> AddMissingColumnsAsync( DbConnection connection, DbTransaction? transaction, ILogger logger, CancellationToken ct) { var added = new List(); for (var i = 0; i < Columns.Count; i++) { var column = Columns[i]; if (await ExistsAsync(connection, transaction, column, ct).ConfigureAwait(false)) continue; try { await ExecuteAsync(connection, transaction, AddColumnSql(column), ct).ConfigureAwait(false); } catch (Exception ex) when (IsPermissionDenied(ex)) { var missing = Columns.Skip(i).Select(c => $"{c.Table}.{c.Name} ({c.Since})"); logger.LogWarning(ex, "Quartz schema: the database role may not alter the Quartz tables, so {Columns} stay missing and " + "Quartz runs without them. Have the administrator run {Script}", string.Join(", ", missing), ScriptPath); return added; } added.Add(column); logger.LogInformation("Quartz schema: added {Table}.{Column} (Quartz {Since})", column.Table, column.Name, column.Since); } return added; } private async Task ExistsAsync(DbConnection connection, DbTransaction? transaction, Column column, CancellationToken ct) { await using var cmd = connection.CreateCommand(); cmd.Transaction = transaction; cmd.CommandText = ColumnExistsSql(column); var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false); return result is not null and not DBNull && Convert.ToInt64(result) > 0; } internal static async Task ExecuteAsync(DbConnection connection, DbTransaction? transaction, string sql, CancellationToken ct) { await using var cmd = connection.CreateCommand(); cmd.Transaction = transaction; cmd.CommandText = sql; await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } private sealed class Postgres : QuartzSchemaMigration { // pg_advisory_lock key of the Quartz schema work: "redb_qrz" in ASCII. private const long LockKey = 0x726564625F71727A; internal override string ScriptName => "quartz_3.22_postgres.sql"; internal override async Task LockAsync(DbConnection connection, CancellationToken ct) { await ExecuteAsync(connection, null, $"SELECT pg_advisory_lock({LockKey})", ct).ConfigureAwait(false); return null; } internal override Task UnlockAsync(DbConnection connection, DbTransaction? transaction, bool succeeded) => ExecuteAsync(connection, null, $"SELECT pg_advisory_unlock({LockKey})", CancellationToken.None); // Tsak creates the tables unqualified, so they are in current_schema(); a namesake in another schema is not ours. internal override string ColumnExistsSql(Column column) => "SELECT count(*) FROM information_schema.columns WHERE table_schema = current_schema() " + $"AND table_name = '{column.Table.ToLowerInvariant()}' AND column_name = '{column.Name.ToLowerInvariant()}'"; internal override string AddColumnSql(Column column) => $"ALTER TABLE {column.Table.ToLowerInvariant()} ADD COLUMN {column.Name.ToLowerInvariant()} {column.PostgresType}"; // 42501 insufficient_privilege: also what ALTER TABLE answers to a role that does not own the table. internal override bool IsPermissionDenied(Exception exception) => exception is Npgsql.PostgresException { SqlState: "42501" }; } private sealed class SqlServer : QuartzSchemaMigration { private const string LockResource = "redb.tsak.quartz.schema"; internal override string ScriptName => "quartz_3.22_sqlServer.sql"; internal override async Task LockAsync(DbConnection connection, CancellationToken ct) { await using var cmd = connection.CreateCommand(); cmd.CommandText = "DECLARE @result int; " + $"EXEC @result = sp_getapplock @Resource = N'{LockResource}', @LockMode = 'Exclusive', " + "@LockOwner = 'Session', @LockTimeout = 120000; SELECT @result;"; var result = Convert.ToInt32(await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false)); if (result < 0) throw new TimeoutException( $"Quartz schema: sp_getapplock on '{LockResource}' returned {result}; another node holds the schema lock."); return null; } internal override Task UnlockAsync(DbConnection connection, DbTransaction? transaction, bool succeeded) => ExecuteAsync(connection, null, $"EXEC sp_releaseapplock @Resource = N'{LockResource}', @LockOwner = 'Session'", CancellationToken.None); internal override string ColumnExistsSql(Column column) => $"SELECT CASE WHEN COL_LENGTH('dbo.{column.Table}', '{column.Name}') IS NULL THEN 0 ELSE 1 END"; internal override string AddColumnSql(Column column) => $"ALTER TABLE [dbo].[{column.Table}] ADD [{column.Name}] {column.SqlServerType}"; internal override bool IsPermissionDenied(Exception exception) => exception is Microsoft.Data.SqlClient.SqlException sql && IsPermissionDeniedNumber(sql.Number); // 229: permission denied on the object; 4902: ALTER TABLE on an object the role cannot see or may not alter. internal static bool IsPermissionDeniedNumber(int number) => number is 229 or 4902; } private sealed class Sqlite : QuartzSchemaMigration { // SQLITE_READONLY: the database file or its directory is read-only to the worker. private const int ReadOnly = 8; internal override string ScriptName => "quartz_3.22_sqlite.sql"; // One file, one writer: an immediate transaction is the lock. internal override Task LockAsync(DbConnection connection, CancellationToken ct) => Task.FromResult(((Microsoft.Data.Sqlite.SqliteConnection)connection).BeginTransaction(deferred: false)); internal override async Task UnlockAsync(DbConnection connection, DbTransaction? transaction, bool succeeded) { if (transaction is null) return; if (succeeded) await transaction.CommitAsync().ConfigureAwait(false); await transaction.DisposeAsync().ConfigureAwait(false); } internal override string ColumnExistsSql(Column column) => $"SELECT count(*) FROM pragma_table_info('{column.Table}') WHERE name = '{column.Name}' COLLATE NOCASE"; internal override string AddColumnSql(Column column) => $"ALTER TABLE {column.Table} ADD COLUMN {column.Name} {column.SqliteType}"; internal override bool IsPermissionDenied(Exception exception) => exception is Microsoft.Data.Sqlite.SqliteException { SqliteErrorCode: ReadOnly }; } } Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/migrations/quartz_3.22_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/Quartz/Scripts/migrations/quartz_3.22_postgres.sql ---- -- Quartz.NET 3.22 schema migration for redb.Tsak (postgres), for the administrator. -- -- The Tsak worker adds the columns below itself at start (QuartzSchemaInitializer), under a lock, when its -- database role may ALTER the Quartz tables. Run this script when it may not (the worker then logs a warning -- naming this file), or to apply the index alignment, which the worker never does on its own. -- -- 3.17 MISFIRE_ORIG_FIRE_TIME: ScheduledFireTimeUtc keeps the time a misfired trigger was due. -- 3.18 EXECUTION_GROUP: the per-node limit of execution groups is applied in the acquire query. -- 3.19 PREFERRED_NODE, PREFERRED_NODE_AUTO: node affinity in a cluster (both or neither). -- 3.20 index alignment: performance only; drops and creates indexes, so run it in a quiet window. -- -- Every statement checks first, so the script is safe to run more than once. Columns are looked up in current_schema(), where Tsak creates the tables. -- Tables carry the QRTZ_ prefix Tsak configures. Taken from the Quartz.NET 3.x migrations (Apache License 2.0), -- database/migrations/3.17 to 3.20 of github.com/quartznet/quartznet. -- -- !! FIRST RUN IN A TEST ENVIRONMENT AGAINST A COPY OF YOUR PRODUCTION DATABASE !! -- ==== 3.17 add misfire orig fire time ==== DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'qrtz_triggers' AND column_name = 'misfire_orig_fire_time') THEN ALTER TABLE qrtz_triggers ADD COLUMN misfire_orig_fire_time bigint null; END IF; END $$; -- ==== 3.18 add execution group ==== DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'qrtz_triggers' AND column_name = 'execution_group') THEN ALTER TABLE qrtz_triggers ADD COLUMN execution_group varchar(200) null; END IF; END $$; DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'qrtz_fired_triggers' AND column_name = 'execution_group') THEN ALTER TABLE qrtz_fired_triggers ADD COLUMN execution_group varchar(200) null; END IF; END $$; -- ==== 3.19 add preferred node ==== DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'qrtz_triggers' AND column_name = 'preferred_node') THEN ALTER TABLE qrtz_triggers ADD COLUMN preferred_node varchar(200) null; END IF; END $$; DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'qrtz_triggers' AND column_name = 'preferred_node_auto') THEN ALTER TABLE qrtz_triggers ADD COLUMN preferred_node_auto bool not null default false; END IF; END $$; -- ==== 3.20 index alignment ==== -- === Drop the indexes whose columns changed but whose name did not ============ -- These have to go first: CREATE INDEX IF NOT EXISTS below would find the name -- already taken and silently keep the old, wrong column order. DROP INDEX IF EXISTS idx_qrtz_j_req_recovery; DROP INDEX IF EXISTS idx_qrtz_t_next_fire_time; DROP INDEX IF EXISTS idx_qrtz_t_nft_st; -- === Create the indexes this version expects =================================== CREATE INDEX IF NOT EXISTS idx_qrtz_j_req_recovery ON qrtz_job_details (sched_name, requests_recovery); CREATE INDEX IF NOT EXISTS idx_qrtz_j_g_n ON qrtz_job_details (sched_name, job_group, job_name); CREATE INDEX IF NOT EXISTS idx_qrtz_t_j ON qrtz_triggers (sched_name, job_name, job_group); CREATE INDEX IF NOT EXISTS idx_qrtz_t_c ON qrtz_triggers (sched_name, calendar_name); CREATE INDEX IF NOT EXISTS idx_qrtz_t_g_n ON qrtz_triggers (sched_name, trigger_group, trigger_name); CREATE INDEX IF NOT EXISTS idx_qrtz_t_next_fire_time ON qrtz_triggers (sched_name, next_fire_time); CREATE INDEX IF NOT EXISTS idx_qrtz_t_nft_st ON qrtz_triggers (sched_name, trigger_state, next_fire_time); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_inst_job_req_rcvry ON qrtz_fired_triggers (sched_name, instance_name, requests_recovery); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_j_g ON qrtz_fired_triggers (sched_name, job_name, job_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_t_g ON qrtz_fired_triggers (sched_name, trigger_name, trigger_group); -- === Drop the ones it no longer uses ========================================== -- Guarded, so each is a no-op when that index is not present. DROP INDEX IF EXISTS idx_qrtz_j_grp; DROP INDEX IF EXISTS idx_qrtz_t_g_j; DROP INDEX IF EXISTS idx_qrtz_t_jg; DROP INDEX IF EXISTS idx_qrtz_t_g; DROP INDEX IF EXISTS idx_qrtz_t_state; DROP INDEX IF EXISTS idx_qrtz_t_n_state; DROP INDEX IF EXISTS idx_qrtz_t_n_g_state; DROP INDEX IF EXISTS idx_qrtz_t_nft_misfire; DROP INDEX IF EXISTS idx_qrtz_t_nft_st_misfire_grp; DROP INDEX IF EXISTS idx_qrtz_t_nft_st_misfire; DROP INDEX IF EXISTS idx_qrtz_ft_g_j; DROP INDEX IF EXISTS idx_qrtz_ft_g_t; DROP INDEX IF EXISTS idx_qrtz_ft_jg; DROP INDEX IF EXISTS idx_qrtz_ft_tg; DROP INDEX IF EXISTS idx_qrtz_ft_trig_inst_name; DROP INDEX IF EXISTS idx_qrtz_ft_trig_nm_gp; DROP INDEX IF EXISTS idx_qrtz_ft_trig_name; DROP INDEX IF EXISTS idx_qrtz_ft_trig_group; DROP INDEX IF EXISTS idx_qrtz_ft_job_name; DROP INDEX IF EXISTS idx_qrtz_ft_job_group; DROP INDEX IF EXISTS idx_qrtz_ft_job_req_recovery; Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/migrations/quartz_3.22_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/Quartz/Scripts/migrations/quartz_3.22_sqlServer.sql ---- -- Quartz.NET 3.22 schema migration for redb.Tsak (sqlServer), for the administrator. -- -- The Tsak worker adds the columns below itself at start (QuartzSchemaInitializer), under a lock, when its -- database role may ALTER the Quartz tables. Run this script when it may not (the worker then logs a warning -- naming this file), or to apply the index alignment, which the worker never does on its own. -- -- 3.17 MISFIRE_ORIG_FIRE_TIME: ScheduledFireTimeUtc keeps the time a misfired trigger was due. -- 3.18 EXECUTION_GROUP: the per-node limit of execution groups is applied in the acquire query. -- 3.19 PREFERRED_NODE, PREFERRED_NODE_AUTO: node affinity in a cluster (both or neither). -- 3.20 index alignment: performance only; drops and creates indexes, so run it in a quiet window. -- -- Every statement checks first, so the script is safe to run more than once. Run it with sqlcmd or SSMS (it uses GO). -- Tables carry the QRTZ_ prefix Tsak configures. Taken from the Quartz.NET 3.x migrations (Apache License 2.0), -- database/migrations/3.17 to 3.20 of github.com/quartznet/quartznet. -- -- !! FIRST RUN IN A TEST ENVIRONMENT AGAINST A COPY OF YOUR PRODUCTION DATABASE !! -- ==== 3.17 add misfire orig fire time ==== IF COL_LENGTH('dbo.QRTZ_TRIGGERS','MISFIRE_ORIG_FIRE_TIME') IS NULL BEGIN ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD [MISFIRE_ORIG_FIRE_TIME] bigint NULL; END GO -- ==== 3.18 add execution group ==== IF COL_LENGTH('dbo.QRTZ_TRIGGERS','EXECUTION_GROUP') IS NULL BEGIN ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD [EXECUTION_GROUP] nvarchar(200) NULL; END GO IF COL_LENGTH('dbo.QRTZ_FIRED_TRIGGERS','EXECUTION_GROUP') IS NULL BEGIN ALTER TABLE [dbo].[QRTZ_FIRED_TRIGGERS] ADD [EXECUTION_GROUP] nvarchar(200) NULL; END GO -- ==== 3.19 add preferred node ==== IF COL_LENGTH('dbo.QRTZ_TRIGGERS','PREFERRED_NODE') IS NULL BEGIN ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD [PREFERRED_NODE] nvarchar(200) NULL; END GO IF COL_LENGTH('dbo.QRTZ_TRIGGERS','PREFERRED_NODE_AUTO') IS NULL BEGIN ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD [PREFERRED_NODE_AUTO] bit NOT NULL DEFAULT 0; END GO -- ==== 3.20 index alignment ==== -- === Create the indexes this version expects =================================== IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_G_J' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_G_J] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, JOB_GROUP, JOB_NAME); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_C' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_C] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, CALENDAR_NAME); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_N_G_STATE' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_N_G_STATE] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, TRIGGER_GROUP, TRIGGER_STATE); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_N_STATE' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_N_STATE] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, TRIGGER_NAME, TRIGGER_GROUP, TRIGGER_STATE); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NEXT_FIRE_TIME' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_NEXT_FIRE_TIME] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, NEXT_FIRE_TIME); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_NFT_ST] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, TRIGGER_STATE, NEXT_FIRE_TIME); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST_MISFIRE' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_NFT_ST_MISFIRE] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, MISFIRE_INSTR, NEXT_FIRE_TIME, TRIGGER_STATE); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST_MISFIRE_GRP' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_T_NFT_ST_MISFIRE_GRP] ON [dbo].[QRTZ_TRIGGERS](SCHED_NAME, MISFIRE_INSTR, NEXT_FIRE_TIME, TRIGGER_GROUP, TRIGGER_STATE); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_INST_JOB_REQ_RCVRY' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_FT_INST_JOB_REQ_RCVRY] ON [dbo].[QRTZ_FIRED_TRIGGERS](SCHED_NAME, INSTANCE_NAME, REQUESTS_RECOVERY); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_G_J' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_FT_G_J] ON [dbo].[QRTZ_FIRED_TRIGGERS](SCHED_NAME, JOB_GROUP, JOB_NAME); END GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_G_T' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN CREATE INDEX [IDX_QRTZ_FT_G_T] ON [dbo].[QRTZ_FIRED_TRIGGERS](SCHED_NAME, TRIGGER_GROUP, TRIGGER_NAME); END GO -- === Drop the ones it no longer uses ========================================== -- Guarded, so each is a no-op when that index is not present. IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_J_GRP' AND object_id = OBJECT_ID('dbo.QRTZ_JOB_DETAILS')) BEGIN DROP INDEX [IDX_QRTZ_J_GRP] ON [dbo].[QRTZ_JOB_DETAILS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_J_REQ_RECOVERY' AND object_id = OBJECT_ID('dbo.QRTZ_JOB_DETAILS')) BEGIN DROP INDEX [IDX_QRTZ_J_REQ_RECOVERY] ON [dbo].[QRTZ_JOB_DETAILS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_JG' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_T_JG] ON [dbo].[QRTZ_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_G' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_T_G] ON [dbo].[QRTZ_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_STATE' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_T_STATE] ON [dbo].[QRTZ_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_MISFIRE' AND object_id = OBJECT_ID('dbo.QRTZ_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_T_NFT_MISFIRE] ON [dbo].[QRTZ_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_JG' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_JG] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TG' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_TG] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TRIG_INST_NAME' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_TRIG_INST_NAME] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TRIG_NM_GP' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_TRIG_NM_GP] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TRIG_NAME' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_TRIG_NAME] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TRIG_GROUP' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_TRIG_GROUP] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_JOB_NAME' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_JOB_NAME] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_JOB_GROUP' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_JOB_GROUP] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_JOB_REQ_RECOVERY' AND object_id = OBJECT_ID('dbo.QRTZ_FIRED_TRIGGERS')) BEGIN DROP INDEX [IDX_QRTZ_FT_JOB_REQ_RECOVERY] ON [dbo].[QRTZ_FIRED_TRIGGERS]; END GO Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/migrations/quartz_3.22_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/Quartz/Scripts/migrations/quartz_3.22_sqlite.sql ---- -- Quartz.NET 3.22 schema migration for redb.Tsak (sqlite), for the administrator. -- -- The Tsak worker adds the columns below itself at start (QuartzSchemaInitializer), under a lock, when its -- database role may ALTER the Quartz tables. Run this script when it may not (the worker then logs a warning -- naming this file), or to apply the index alignment, which the worker never does on its own. -- -- 3.17 MISFIRE_ORIG_FIRE_TIME: ScheduledFireTimeUtc keeps the time a misfired trigger was due. -- 3.18 EXECUTION_GROUP: the per-node limit of execution groups is applied in the acquire query. -- 3.19 PREFERRED_NODE, PREFERRED_NODE_AUTO: node affinity in a cluster (both or neither). -- 3.20 index alignment: performance only; drops and creates indexes, so run it in a quiet window. -- -- RUN ONCE. SQLite has no conditional ADD COLUMN: the column part fails with a duplicate-column error when run again. Check PRAGMA table_info(QRTZ_TRIGGERS) and PRAGMA table_info(QRTZ_FIRED_TRIGGERS) first and skip the columns that are there. The index part checks first. -- Tables carry the QRTZ_ prefix Tsak configures. Taken from the Quartz.NET 3.x migrations (Apache License 2.0), -- database/migrations/3.17 to 3.20 of github.com/quartznet/quartznet. -- -- !! FIRST RUN IN A TEST ENVIRONMENT AGAINST A COPY OF YOUR PRODUCTION DATABASE !! -- ==== 3.17 add misfire orig fire time ==== ALTER TABLE QRTZ_TRIGGERS ADD COLUMN MISFIRE_ORIG_FIRE_TIME INTEGER NULL; -- ==== 3.18 add execution group ==== ALTER TABLE QRTZ_TRIGGERS ADD COLUMN EXECUTION_GROUP NVARCHAR(200) NULL; ALTER TABLE QRTZ_FIRED_TRIGGERS ADD COLUMN EXECUTION_GROUP NVARCHAR(200) NULL; -- ==== 3.19 add preferred node ==== ALTER TABLE QRTZ_TRIGGERS ADD COLUMN PREFERRED_NODE NVARCHAR(200) NULL; ALTER TABLE QRTZ_TRIGGERS ADD COLUMN PREFERRED_NODE_AUTO BIT NOT NULL DEFAULT 0; -- ==== 3.20 index alignment ==== -- === Create the indexes this version expects =================================== CREATE INDEX IF NOT EXISTS IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY); CREATE INDEX IF NOT EXISTS IDX_QRTZ_J_G_N ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP,JOB_NAME); CREATE INDEX IF NOT EXISTS IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); CREATE INDEX IF NOT EXISTS IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME); CREATE INDEX IF NOT EXISTS IDX_QRTZ_T_G_N ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP,TRIGGER_NAME); CREATE INDEX IF NOT EXISTS IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME); CREATE INDEX IF NOT EXISTS IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME); CREATE INDEX IF NOT EXISTS IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY); CREATE INDEX IF NOT EXISTS IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); CREATE INDEX IF NOT EXISTS IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP); -- === Drop the ones it no longer uses ========================================== -- Guarded, so each is a no-op when that index is not present. DROP INDEX IF EXISTS IDX_QRTZ_J_GRP; DROP INDEX IF EXISTS IDX_QRTZ_T_G_J; DROP INDEX IF EXISTS IDX_QRTZ_T_JG; DROP INDEX IF EXISTS IDX_QRTZ_T_G; DROP INDEX IF EXISTS IDX_QRTZ_T_STATE; DROP INDEX IF EXISTS IDX_QRTZ_T_N_STATE; DROP INDEX IF EXISTS IDX_QRTZ_T_N_G_STATE; DROP INDEX IF EXISTS IDX_QRTZ_T_NFT_MISFIRE; DROP INDEX IF EXISTS IDX_QRTZ_T_NFT_ST_MISFIRE_GRP; DROP INDEX IF EXISTS IDX_QRTZ_T_NFT_ST_MISFIRE; DROP INDEX IF EXISTS IDX_QRTZ_FT_G_J; DROP INDEX IF EXISTS IDX_QRTZ_FT_G_T; DROP INDEX IF EXISTS IDX_QRTZ_FT_JG; DROP INDEX IF EXISTS IDX_QRTZ_FT_TG; DROP INDEX IF EXISTS IDX_QRTZ_FT_TRIG_INST_NAME; DROP INDEX IF EXISTS IDX_QRTZ_FT_TRIG_NM_GP; DROP INDEX IF EXISTS IDX_QRTZ_FT_TRIG_NAME; DROP INDEX IF EXISTS IDX_QRTZ_FT_TRIG_GROUP; DROP INDEX IF EXISTS IDX_QRTZ_FT_JOB_NAME; DROP INDEX IF EXISTS IDX_QRTZ_FT_JOB_GROUP; DROP INDEX IF EXISTS IDX_QRTZ_FT_JOB_REQ_RECOVERY; Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/tables_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/Quartz/Scripts/tables_postgres.sql ---- -- Quartz.NET schema for PostgreSQL -- Auto-applied by TsakHostedService when AdoJobStore is configured. -- Idempotent: uses CREATE TABLE IF NOT EXISTS. CREATE TABLE IF NOT EXISTS qrtz_job_details ( sched_name TEXT NOT NULL, job_name TEXT NOT NULL, job_group TEXT NOT NULL, description TEXT NULL, job_class_name TEXT NOT NULL, is_durable BOOL NOT NULL, is_nonconcurrent BOOL NOT NULL, is_update_data BOOL NOT NULL, requests_recovery BOOL NOT NULL, job_data BYTEA NULL, PRIMARY KEY (sched_name, job_name, job_group) ); CREATE TABLE IF NOT EXISTS qrtz_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, job_name TEXT NOT NULL, job_group TEXT NOT NULL, description TEXT NULL, next_fire_time BIGINT NULL, prev_fire_time BIGINT NULL, priority INTEGER NULL, trigger_state TEXT NOT NULL, trigger_type TEXT NOT NULL, start_time BIGINT NOT NULL, end_time BIGINT NULL, calendar_name TEXT NULL, misfire_instr SMALLINT NULL, misfire_orig_fire_time BIGINT NULL, execution_group VARCHAR(200) NULL, preferred_node VARCHAR(200) NULL, preferred_node_auto BOOL NOT NULL DEFAULT FALSE, job_data BYTEA NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, job_name, job_group) REFERENCES qrtz_job_details (sched_name, job_name, job_group) ); CREATE TABLE IF NOT EXISTS qrtz_simple_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, repeat_count BIGINT NOT NULL, repeat_interval BIGINT NOT NULL, times_triggered BIGINT NOT NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_simprop_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, str_prop_1 TEXT NULL, str_prop_2 TEXT NULL, str_prop_3 TEXT NULL, int_prop_1 INTEGER NULL, int_prop_2 INTEGER NULL, long_prop_1 BIGINT NULL, long_prop_2 BIGINT NULL, dec_prop_1 NUMERIC NULL, dec_prop_2 NUMERIC NULL, bool_prop_1 BOOL NULL, bool_prop_2 BOOL NULL, time_zone_id TEXT NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_cron_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, cron_expression TEXT NOT NULL, time_zone_id TEXT, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_blob_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, blob_data BYTEA NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_calendars ( sched_name TEXT NOT NULL, calendar_name TEXT NOT NULL, calendar BYTEA NOT NULL, PRIMARY KEY (sched_name, calendar_name) ); CREATE TABLE IF NOT EXISTS qrtz_paused_trigger_grps ( sched_name TEXT NOT NULL, trigger_group TEXT NOT NULL, PRIMARY KEY (sched_name, trigger_group) ); CREATE TABLE IF NOT EXISTS qrtz_fired_triggers ( sched_name TEXT NOT NULL, entry_id TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, instance_name TEXT NOT NULL, fired_time BIGINT NOT NULL, sched_time BIGINT NOT NULL, priority INTEGER NOT NULL, state TEXT NOT NULL, job_name TEXT NULL, job_group TEXT NULL, is_nonconcurrent BOOL NOT NULL, requests_recovery BOOL NULL, execution_group VARCHAR(200) NULL, PRIMARY KEY (sched_name, entry_id) ); CREATE TABLE IF NOT EXISTS qrtz_scheduler_state ( sched_name TEXT NOT NULL, instance_name TEXT NOT NULL, last_checkin_time BIGINT NOT NULL, checkin_interval BIGINT NOT NULL, PRIMARY KEY (sched_name, instance_name) ); CREATE TABLE IF NOT EXISTS qrtz_locks ( sched_name TEXT NOT NULL, lock_name TEXT NOT NULL, PRIMARY KEY (sched_name, lock_name) ); -- Indexes CREATE INDEX IF NOT EXISTS idx_qrtz_j_req_recovery ON qrtz_job_details (requests_recovery); CREATE INDEX IF NOT EXISTS idx_qrtz_t_next_fire_time ON qrtz_triggers (next_fire_time); CREATE INDEX IF NOT EXISTS idx_qrtz_t_state ON qrtz_triggers (trigger_state); CREATE INDEX IF NOT EXISTS idx_qrtz_t_nft_st ON qrtz_triggers (next_fire_time, trigger_state); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_name ON qrtz_fired_triggers (trigger_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_group ON qrtz_fired_triggers (trigger_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_nm_gp ON qrtz_fired_triggers (sched_name, trigger_name, trigger_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_inst_name ON qrtz_fired_triggers (instance_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_name ON qrtz_fired_triggers (job_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_group ON qrtz_fired_triggers (job_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_req_recovery ON qrtz_fired_triggers (requests_recovery); Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/tables_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/Quartz/Scripts/tables_sqlServer.sql ---- -- Quartz.NET schema for SQL Server / Azure SQL -- Auto-applied by TsakHostedService when AdoJobStore is configured. -- Idempotent: each CREATE is guarded by OBJECT_ID check. IF OBJECT_ID(N'[dbo].[QRTZ_JOB_DETAILS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_JOB_DETAILS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [JOB_NAME] nvarchar(150) NOT NULL, [JOB_GROUP] nvarchar(150) NOT NULL, [DESCRIPTION] nvarchar(250) NULL, [JOB_CLASS_NAME] nvarchar(250) NOT NULL, [IS_DURABLE] bit NOT NULL, [IS_NONCONCURRENT] bit NOT NULL, [IS_UPDATE_DATA] bit NOT NULL, [REQUESTS_RECOVERY] bit NOT NULL, [JOB_DATA] varbinary(max) NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [JOB_NAME] nvarchar(150) NOT NULL, [JOB_GROUP] nvarchar(150) NOT NULL, [DESCRIPTION] nvarchar(250) NULL, [NEXT_FIRE_TIME] bigint NULL, [PREV_FIRE_TIME] bigint NULL, [PRIORITY] int NULL, [TRIGGER_STATE] nvarchar(16) NOT NULL, [TRIGGER_TYPE] nvarchar(8) NOT NULL, [START_TIME] bigint NOT NULL, [END_TIME] bigint NULL, [CALENDAR_NAME] nvarchar(200) NULL, [MISFIRE_INSTR] int NULL, [MISFIRE_ORIG_FIRE_TIME] bigint NULL, [EXECUTION_GROUP] nvarchar(200) NULL, [PREFERRED_NODE] nvarchar(200) NULL, [PREFERRED_NODE_AUTO] bit NOT NULL DEFAULT 0, [JOB_DATA] varbinary(max) NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_SIMPLE_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [REPEAT_COUNT] int NOT NULL, [REPEAT_INTERVAL] bigint NOT NULL, [TIMES_TRIGGERED] int NOT NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_SIMPROP_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [STR_PROP_1] nvarchar(512) NULL, [STR_PROP_2] nvarchar(512) NULL, [STR_PROP_3] nvarchar(512) NULL, [INT_PROP_1] int NULL, [INT_PROP_2] int NULL, [LONG_PROP_1] bigint NULL, [LONG_PROP_2] bigint NULL, [DEC_PROP_1] numeric(13,4) NULL, [DEC_PROP_2] numeric(13,4) NULL, [BOOL_PROP_1] bit NULL, [BOOL_PROP_2] bit NULL, [TIME_ZONE_ID] nvarchar(80) NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_CRON_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_CRON_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [CRON_EXPRESSION] nvarchar(120) NOT NULL, [TIME_ZONE_ID] nvarchar(80) ); IF OBJECT_ID(N'[dbo].[QRTZ_BLOB_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_BLOB_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [BLOB_DATA] varbinary(max) NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_CALENDARS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_CALENDARS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [CALENDAR_NAME] nvarchar(200) NOT NULL, [CALENDAR] varbinary(max) NOT NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_PAUSED_TRIGGER_GRPS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_PAUSED_TRIGGER_GRPS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_FIRED_TRIGGERS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_FIRED_TRIGGERS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [ENTRY_ID] nvarchar(140) NOT NULL, [TRIGGER_NAME] nvarchar(150) NOT NULL, [TRIGGER_GROUP] nvarchar(150) NOT NULL, [INSTANCE_NAME] nvarchar(200) NOT NULL, [FIRED_TIME] bigint NOT NULL, [SCHED_TIME] bigint NOT NULL, [PRIORITY] int NOT NULL, [STATE] nvarchar(16) NOT NULL, [JOB_NAME] nvarchar(150) NULL, [JOB_GROUP] nvarchar(150) NULL, [IS_NONCONCURRENT] bit NULL, [REQUESTS_RECOVERY] bit NULL, [EXECUTION_GROUP] nvarchar(200) NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_SCHEDULER_STATE]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_SCHEDULER_STATE] ( [SCHED_NAME] nvarchar(120) NOT NULL, [INSTANCE_NAME] nvarchar(200) NOT NULL, [LAST_CHECKIN_TIME] bigint NOT NULL, [CHECKIN_INTERVAL] bigint NOT NULL ); IF OBJECT_ID(N'[dbo].[QRTZ_LOCKS]', N'U') IS NULL CREATE TABLE [dbo].[QRTZ_LOCKS] ( [SCHED_NAME] nvarchar(120) NOT NULL, [LOCK_NAME] nvarchar(40) NOT NULL ); -- Primary keys (idempotent via NOT EXISTS on sys.key_constraints) IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_JOB_DETAILS') ALTER TABLE [dbo].[QRTZ_JOB_DETAILS] ADD CONSTRAINT [PK_QRTZ_JOB_DETAILS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [JOB_NAME], [JOB_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_TRIGGERS') ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_SIMPLE_TRIGGERS') ALTER TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_SIMPLE_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_SIMPROP_TRIGGERS') ALTER TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_SIMPROP_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_CRON_TRIGGERS') ALTER TABLE [dbo].[QRTZ_CRON_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_CRON_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_BLOB_TRIGGERS') ALTER TABLE [dbo].[QRTZ_BLOB_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_BLOB_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_CALENDARS') ALTER TABLE [dbo].[QRTZ_CALENDARS] ADD CONSTRAINT [PK_QRTZ_CALENDARS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [CALENDAR_NAME]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_PAUSED_TRIGGER_GRPS') ALTER TABLE [dbo].[QRTZ_PAUSED_TRIGGER_GRPS] ADD CONSTRAINT [PK_QRTZ_PAUSED_TRIGGER_GRPS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_FIRED_TRIGGERS') ALTER TABLE [dbo].[QRTZ_FIRED_TRIGGERS] ADD CONSTRAINT [PK_QRTZ_FIRED_TRIGGERS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [ENTRY_ID]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_SCHEDULER_STATE') ALTER TABLE [dbo].[QRTZ_SCHEDULER_STATE] ADD CONSTRAINT [PK_QRTZ_SCHEDULER_STATE] PRIMARY KEY CLUSTERED ([SCHED_NAME], [INSTANCE_NAME]); IF NOT EXISTS (SELECT 1 FROM sys.key_constraints WHERE name = 'PK_QRTZ_LOCKS') ALTER TABLE [dbo].[QRTZ_LOCKS] ADD CONSTRAINT [PK_QRTZ_LOCKS] PRIMARY KEY CLUSTERED ([SCHED_NAME], [LOCK_NAME]); -- Foreign keys (idempotent) IF OBJECT_ID(N'[dbo].[FK_QRTZ_TRIGGERS_QRTZ_JOB_DETAILS]', N'F') IS NULL ALTER TABLE [dbo].[QRTZ_TRIGGERS] ADD CONSTRAINT [FK_QRTZ_TRIGGERS_QRTZ_JOB_DETAILS] FOREIGN KEY ([SCHED_NAME],[JOB_NAME],[JOB_GROUP]) REFERENCES [dbo].[QRTZ_JOB_DETAILS] ([SCHED_NAME],[JOB_NAME],[JOB_GROUP]); IF OBJECT_ID(N'[dbo].[FK_QRTZ_CRON_TRIGGERS_QRTZ_TRIGGERS]', N'F') IS NULL ALTER TABLE [dbo].[QRTZ_CRON_TRIGGERS] ADD CONSTRAINT [FK_QRTZ_CRON_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) REFERENCES [dbo].[QRTZ_TRIGGERS] ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) ON DELETE CASCADE; IF OBJECT_ID(N'[dbo].[FK_QRTZ_SIMPLE_TRIGGERS_QRTZ_TRIGGERS]', N'F') IS NULL ALTER TABLE [dbo].[QRTZ_SIMPLE_TRIGGERS] ADD CONSTRAINT [FK_QRTZ_SIMPLE_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) REFERENCES [dbo].[QRTZ_TRIGGERS] ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) ON DELETE CASCADE; IF OBJECT_ID(N'[dbo].[FK_QRTZ_SIMPROP_TRIGGERS_QRTZ_TRIGGERS]', N'F') IS NULL ALTER TABLE [dbo].[QRTZ_SIMPROP_TRIGGERS] ADD CONSTRAINT [FK_QRTZ_SIMPROP_TRIGGERS_QRTZ_TRIGGERS] FOREIGN KEY ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) REFERENCES [dbo].[QRTZ_TRIGGERS] ([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]) ON DELETE CASCADE; -- Indexes (idempotent via IF NOT EXISTS on sys.indexes) IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_J') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_J] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[JOB_NAME],[JOB_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_JG') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_JG] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[JOB_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_C') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_C] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[CALENDAR_NAME]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_G') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_G] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_STATE') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_STATE] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[TRIGGER_STATE]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_N_STATE') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_N_STATE] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP],[TRIGGER_STATE]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_N_G_STATE') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_N_G_STATE] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[TRIGGER_GROUP],[TRIGGER_STATE]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NEXT_FIRE_TIME') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_NEXT_FIRE_TIME] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[NEXT_FIRE_TIME]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_NFT_ST] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[TRIGGER_STATE],[NEXT_FIRE_TIME]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_MISFIRE') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_NFT_MISFIRE] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[MISFIRE_INSTR],[NEXT_FIRE_TIME]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST_MISFIRE') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_NFT_ST_MISFIRE] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[MISFIRE_INSTR],[NEXT_FIRE_TIME],[TRIGGER_STATE]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_T_NFT_ST_MISFIRE_GRP') CREATE NONCLUSTERED INDEX [IDX_QRTZ_T_NFT_ST_MISFIRE_GRP] ON [dbo].[QRTZ_TRIGGERS]([SCHED_NAME],[MISFIRE_INSTR],[NEXT_FIRE_TIME],[TRIGGER_GROUP],[TRIGGER_STATE]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TRIG_INST_NAME') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_TRIG_INST_NAME] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[INSTANCE_NAME]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_INST_JOB_REQ_RCVRY') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_INST_JOB_REQ_RCVRY] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[INSTANCE_NAME],[REQUESTS_RECOVERY]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_J_G') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_J_G] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[JOB_NAME],[JOB_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_JG') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_JG] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[JOB_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_T_G') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_T_G] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[TRIGGER_NAME],[TRIGGER_GROUP]); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IDX_QRTZ_FT_TG') CREATE NONCLUSTERED INDEX [IDX_QRTZ_FT_TG] ON [dbo].[QRTZ_FIRED_TRIGGERS]([SCHED_NAME],[TRIGGER_GROUP]); Path: redb-tsak/src/redb.Tsak.Core/Quartz/Scripts/tables_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/Quartz/Scripts/tables_sqlite.sql ---- -- Quartz.NET AdoJobStore schema for SQLite. -- Idempotent: uses CREATE TABLE/TRIGGER IF NOT EXISTS — applied on every startup, -- existing Quartz state is preserved (same semantics as tables_postgres.sql). CREATE TABLE IF NOT EXISTS QRTZ_JOB_DETAILS ( SCHED_NAME NVARCHAR(120) NOT NULL, JOB_NAME NVARCHAR(150) NOT NULL, JOB_GROUP NVARCHAR(150) NOT NULL, DESCRIPTION NVARCHAR(250) NULL, JOB_CLASS_NAME NVARCHAR(250) NOT NULL, IS_DURABLE BIT NOT NULL, IS_NONCONCURRENT BIT NOT NULL, IS_UPDATE_DATA BIT NOT NULL, REQUESTS_RECOVERY BIT NOT NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) ); CREATE TABLE IF NOT EXISTS QRTZ_TRIGGERS ( SCHED_NAME NVARCHAR(120) NOT NULL, TRIGGER_NAME NVARCHAR(150) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, JOB_NAME NVARCHAR(150) NOT NULL, JOB_GROUP NVARCHAR(150) NOT NULL, DESCRIPTION NVARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT NULL, PREV_FIRE_TIME BIGINT NULL, PRIORITY INTEGER NULL, TRIGGER_STATE NVARCHAR(16) NOT NULL, TRIGGER_TYPE NVARCHAR(8) NOT NULL, START_TIME BIGINT NOT NULL, END_TIME BIGINT NULL, CALENDAR_NAME NVARCHAR(200) NULL, MISFIRE_INSTR INTEGER NULL, MISFIRE_ORIG_FIRE_TIME INTEGER NULL, EXECUTION_GROUP NVARCHAR(200) NULL, PREFERRED_NODE NVARCHAR(200) NULL, PREFERRED_NODE_AUTO BIT NOT NULL DEFAULT 0, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP) ); CREATE TABLE IF NOT EXISTS QRTZ_SIMPLE_TRIGGERS ( SCHED_NAME NVARCHAR(120) NOT NULL, TRIGGER_NAME NVARCHAR(150) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, REPEAT_COUNT BIGINT NOT NULL, REPEAT_INTERVAL BIGINT NOT NULL, TIMES_TRIGGERED BIGINT NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) ON DELETE CASCADE ); CREATE TRIGGER IF NOT EXISTS DELETE_SIMPLE_TRIGGER DELETE ON QRTZ_TRIGGERS BEGIN DELETE FROM QRTZ_SIMPLE_TRIGGERS WHERE SCHED_NAME=OLD.SCHED_NAME AND TRIGGER_NAME=OLD.TRIGGER_NAME AND TRIGGER_GROUP=OLD.TRIGGER_GROUP; END ; CREATE TABLE IF NOT EXISTS QRTZ_SIMPROP_TRIGGERS ( SCHED_NAME NVARCHAR (120) NOT NULL , TRIGGER_NAME NVARCHAR (150) NOT NULL , TRIGGER_GROUP NVARCHAR (150) NOT NULL , STR_PROP_1 NVARCHAR (512) NULL, STR_PROP_2 NVARCHAR (512) NULL, STR_PROP_3 NVARCHAR (512) NULL, INT_PROP_1 INT NULL, INT_PROP_2 INT NULL, LONG_PROP_1 BIGINT NULL, LONG_PROP_2 BIGINT NULL, DEC_PROP_1 NUMERIC NULL, DEC_PROP_2 NUMERIC NULL, BOOL_PROP_1 BIT NULL, BOOL_PROP_2 BIT NULL, TIME_ZONE_ID NVARCHAR(80) NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) ON DELETE CASCADE ); CREATE TRIGGER IF NOT EXISTS DELETE_SIMPROP_TRIGGER DELETE ON QRTZ_TRIGGERS BEGIN DELETE FROM QRTZ_SIMPROP_TRIGGERS WHERE SCHED_NAME=OLD.SCHED_NAME AND TRIGGER_NAME=OLD.TRIGGER_NAME AND TRIGGER_GROUP=OLD.TRIGGER_GROUP; END ; CREATE TABLE IF NOT EXISTS QRTZ_CRON_TRIGGERS ( SCHED_NAME NVARCHAR(120) NOT NULL, TRIGGER_NAME NVARCHAR(150) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, CRON_EXPRESSION NVARCHAR(250) NOT NULL, TIME_ZONE_ID NVARCHAR(80), PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) ON DELETE CASCADE ); CREATE TRIGGER IF NOT EXISTS DELETE_CRON_TRIGGER DELETE ON QRTZ_TRIGGERS BEGIN DELETE FROM QRTZ_CRON_TRIGGERS WHERE SCHED_NAME=OLD.SCHED_NAME AND TRIGGER_NAME=OLD.TRIGGER_NAME AND TRIGGER_GROUP=OLD.TRIGGER_GROUP; END ; CREATE TABLE IF NOT EXISTS QRTZ_BLOB_TRIGGERS ( SCHED_NAME NVARCHAR(120) NOT NULL, TRIGGER_NAME NVARCHAR(150) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) ON DELETE CASCADE ); CREATE TRIGGER IF NOT EXISTS DELETE_BLOB_TRIGGER DELETE ON QRTZ_TRIGGERS BEGIN DELETE FROM QRTZ_BLOB_TRIGGERS WHERE SCHED_NAME=OLD.SCHED_NAME AND TRIGGER_NAME=OLD.TRIGGER_NAME AND TRIGGER_GROUP=OLD.TRIGGER_GROUP; END ; CREATE TABLE IF NOT EXISTS QRTZ_CALENDARS ( SCHED_NAME NVARCHAR(120) NOT NULL, CALENDAR_NAME NVARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (SCHED_NAME,CALENDAR_NAME) ); CREATE TABLE IF NOT EXISTS QRTZ_PAUSED_TRIGGER_GRPS ( SCHED_NAME NVARCHAR(120) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP) ); CREATE TABLE IF NOT EXISTS QRTZ_FIRED_TRIGGERS ( SCHED_NAME NVARCHAR(120) NOT NULL, ENTRY_ID NVARCHAR(140) NOT NULL, TRIGGER_NAME NVARCHAR(150) NOT NULL, TRIGGER_GROUP NVARCHAR(150) NOT NULL, INSTANCE_NAME NVARCHAR(200) NOT NULL, FIRED_TIME BIGINT NOT NULL, SCHED_TIME BIGINT NOT NULL, PRIORITY INTEGER NOT NULL, STATE NVARCHAR(16) NOT NULL, JOB_NAME NVARCHAR(150) NULL, JOB_GROUP NVARCHAR(150) NULL, IS_NONCONCURRENT BIT NULL, REQUESTS_RECOVERY BIT NULL, EXECUTION_GROUP NVARCHAR(200) NULL, PRIMARY KEY (SCHED_NAME,ENTRY_ID) ); CREATE TABLE IF NOT EXISTS QRTZ_SCHEDULER_STATE ( SCHED_NAME NVARCHAR(120) NOT NULL, INSTANCE_NAME NVARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT NOT NULL, CHECKIN_INTERVAL BIGINT NOT NULL, PRIMARY KEY (SCHED_NAME,INSTANCE_NAME) ); CREATE TABLE IF NOT EXISTS QRTZ_LOCKS ( SCHED_NAME NVARCHAR(120) NOT NULL, LOCK_NAME NVARCHAR(40) NOT NULL, PRIMARY KEY (SCHED_NAME,LOCK_NAME) ); Path: redb-tsak/src/redb.Tsak.Core/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/src/redb.Tsak.Core/README.md ---- # redb.Tsak.Core > Documentation and articles: The server-side engine of [redb.Tsak](../../README.md). Contains the REST API controllers, all runtime services (hot-reload, context management, coordinator, watchdog, metrics), the module system (assembly loading, isolated ALCs), security middleware (API key auth with HMAC-SHA256), and storage abstractions. This project is referenced by the Worker host (`redb.Tsak.Worker`) and the Pro variant (`redb.Tsak.Core.Pro`). It is not meant to be consumed directly by application code — use `redb.Tsak.Client` for programmatic access. ## Project structure ``` redb.Tsak.Core/ ├── Contracts/ ← Interfaces (ITsakModule, ITsakContextManager, ITsakCoordinator, …) ├── Controllers/ ← redb.Route controllers (14 here + 1 from Core.Pro, 57 endpoints) ├── Extensions/ ← DI registration helpers ├── Models/ ← Internal models (not exposed as API DTOs) ├── Modules/ ← Assembly loading: ALC, hot-swap, manifest, packages ├── Monitoring/ ← Watchdog, metrics, health, lifecycle audit, log ring-buffer ├── Security/ ← API key service, stores, audit filter └── Services/ ← Business logic: context manager, coordinator, hot-reload, storage ``` ## Core concepts ### Module A **module** is a deployable unit — a directory of DLLs or a `.tpkg` archive — that contains one or more `redb.Route` route builders. The core module contract is `ITsakModule`: | Status | Meaning | |---|---| | `Discovered` | Directory/package found by `HotReloadService`, not yet loaded | | `Loaded` | Assembly loaded into isolated ALC | | `Initialized` | `InitRoute.main()` or the module's own initialization has run | | `Running` | Context started, transports connected | | `Stopped` | Graceful stop completed | | `Faulted` | Error during load or initialization | The loader scans each module assembly for two shapes: - a concrete public type implementing `ITsakModule`, used as is; - a public static class `InitRoute` with `static IRouteContext main(IRouteContext ctx)` or its async form `static Task main(IRouteContext ctx)`, wrapped in `StaticMethodModule`. A `RouteBuilder` subclass alone is not a module: register it from `main` with `ctx.AddRoutes(...)`. ### Context A **context** is a named `IRouteContext` instance that groups one or more modules into a shared lifecycle, property bag, and redb instance. Contexts are either: - **Named** — declared in `appsettings.json` under `Tsak:Contexts:{name}:Modules`, may host multiple modules. - **Anonymous** — created automatically for any module not assigned to a named context; one module = one context. ### 5-layer configuration merge Every context's property bag is built by `ConfigMergeHelper.DeepMerge` across five layers (outer layers win): | Layer | Source | Who controls | |---|---|---| | 1 (base) | `Tsak:Contexts:default` | DevOps default | | 2 | `Tsak:Contexts:{name}` | DevOps per-context | | 3 | `context.json` (module dir) | Module developer | | 4 | `{Module}.config.json` | Module developer | | 5 (override) | `Tsak:Contexts:{name}:Override` | DevOps override (highest prio) | ## Services ### `HotReloadService` Background service that periodically scans `Tsak:Modules:AssemblyPaths` for: - Directories containing `*.dll` → loads via per-module `ModuleAssemblyLoadContext` - `*.tpkg` ZIP archives → unpacks into `ModulePackage` with its own isolated ALC Tracks file timestamps and performs graceful hot-swap: 1. New DLL/package detected → load new module into new ALC 2. Stop old module (drain in-flight exchanges) 3. Register new module, start context 4. Optionally unload old ALC (requires `Collectible = true`) 5. Check in the background that the contexts let go leave memory (`ModuleContextMonitor`) Key configuration (`Tsak:HotReload`): | Key | Default | Description | |---|---|---| | `ScanIntervalSeconds` | `10` | How often to scan `Libs/` | | `Collectible` | `false` | Unload replaced module versions for GC reclamation; one still in memory after the unload check is logged and counted | | `MaxOrphanedContexts` | `KeepVersions + 3` | Module contexts left in memory after their modules went before the `hotreload` health check turns Degraded | | `KeepVersions` | `2` | Old versions kept for rollback | | `StartupTimeoutSeconds` | `60` | New version must settle within this window | | `RollingUpdate` | `false` | RESERVED — not implemented; nodes reload independently | | `RemovalDebounceScans` | `2` | Scan cycles a missing file must persist before triggering unload | ### `TsakContextManager` Manages the lifecycle of all `IRouteContext` instances: - Creates named and anonymous contexts from config + merged property bag - Starts/stops/restarts contexts and individual routes - Serializes lifecycle operations via `SemaphoreSlim` to prevent races - Maintains isolated mini-DI containers per named `IRedbService` instance (created by `RedbInstanceFactory`) - Persists autostart state in `ITsakStateStore` - Publishes events to `LifecycleAuditService` ### `TsakCoordinator` Bridges the module registry and the context manager. Subscribes to `ITsakModuleRegistry` events (`ModuleAdded`, `ModuleRemoved`, `ModuleUpdated`, `ModulesBatchAdded`) and orchestrates context creation/teardown: - Groups modules by target context (named vs anonymous) - Per-context locks prevent races when multiple modules arrive concurrently - On module removal, decides whether to destroy the whole context or just remove one module from a named context ### `TsakModuleRegistry` In-memory registry of all currently known `ITsakModule` instances. Raises typed events consumed by `TsakCoordinator`. Backed by `ITsakModuleStore` for persistence across restarts (optional). ### `RedbInstanceFactory` Creates isolated `IRedbService` instances (Postgres or MSSql, open or Pro) from a config dictionary. Each instance lives in its own `ServiceProvider` mini-container that the context manager disposes when the context is removed. ### `SystemContextBuilder` Builds the global `system` context that hosts Tsak's own REST API and monitoring endpoints. Configured by `ISystemContextPlugin` contributors (Pro variant adds cluster leadership, metrics retention, etc.). ## Monitoring subsystem ### `RouteWatchdogService` Background service (`IHostedService`) that periodically scans all routes for: - **Suspected** exchanges — in-flight longer than `Tsak:Watchdog:SuspectedThresholdSeconds` - **Hung** exchanges — in-flight longer than `Tsak:Watchdog:HungThresholdSeconds` Maintains a queryable `WatchdogState` with `ActiveAlerts`. Can auto-restart hung routes when configured. Enable/disable at runtime via `RouteWatchdogService.Enable()` / `.Disable()`, or via the REST API / CLI. ### `MetricsCollectionService` Background service that samples CPU, memory, thread pool, and GC metrics on a configurable interval and stores them in a ring buffer. The ring buffer is queryable via `/api/system/metrics` and `/api/system/metrics/history`. ### `HealthCheckService` Aggregates `IHealthContributor` registrations (from Core, Pro, and module-contributed) into a single `/api/system/health` response. ### `LifecycleAuditService` Maintains an append-only audit log of context/route lifecycle events, queryable via `/api/diagnostics/lifecycle`. Persisted to `ITsakStateStore` in Redb-backed mode. ### `LogRingBuffer` / `RingBufferSink` Serilog sink that captures recent log entries into a fixed-capacity ring buffer. Accessible via `/api/logs`. Enabled when `Tsak:Logging:RingBuffer:Enabled = true`. ## Security ### `ApiKeyService` - Keys are stored as HMAC-SHA256 hashes (never raw). - Validation uses `CryptographicOperations.FixedTimeEquals` to prevent timing attacks. - Validated results are cached for `CacheTtl` (default 5 min) to reduce store round-trips. ### `IApiKeyStore` implementations | Implementation | Storage | Use case | |---|---|---| | `ConfigApiKeyStore` | `appsettings.json` (static list) | Single-node dev/simple deployments | | `RedbApiKeyStore` | redb-backed schema | Multi-node, runtime key management | ### `AdminAuditFilter` Controller action filter that records every mutating API call (marked `[AuditAdminAction]`) to the registered `IAdminAuditService`. The effective sink is `RouteAdminAuditService`, which persists events to the flat `tsak_audit_log` table (via `direct://tsak-audit`) and falls back to `LogAdminAuditService` (a `[tsak-audit]`-anchored JSON log line) when no database is configured. See `Audit/` for the schema initializer, writer route, query service and retention job. ## Controllers | Controller | Path | Operations | |---|---|---| | `AuthController` | `/api/auth` | Create/list/revoke API keys | | `ContextsController` | `/api/contexts` | CRUD + lifecycle for contexts | | `RoutesController` | `/api/contexts/{ctx}/routes` | Route lifecycle, inflight, force-stop, per-route metrics | | `ModulesController` | `/api/modules` | List, get, remove modules | | `SchedulerController` | `/api/scheduler` | Quartz status, jobs, start/standby/pause/resume | | `ClusterController` | `/api/cluster` | Cluster status, nodes, rebalance (ships in `Core.Pro`, contributed via `ISystemContextPlugin`) | | `WatchdogController` | `/api/watchdog` | State, alerts, enable/disable | | `DiagnosticsController` | `/api/diagnostics` | System dump, route-level dump | | `LogsController` | `/api/logs` | Ring-buffer entries, log files, download | | `LifecycleController` | `/api/lifecycle` | Recent lifecycle events (filtered) | | `AuditController` | `/api/audit` | Persisted admin-action trail (filtered, paged; `admin` role) | | `SystemController` | `/api/system` | Health, info, metrics, metrics history | | `UsersController` | `/api/users` | User CRUD (Pro) | | `DashboardController` | `/api/dashboard` | Aggregated snapshot | | `HealthProbeController` | `/api/health` | Kubernetes probes: `startup`, `live`, `ready` (auth-exempt) | 57 endpoints in total. Request path, auth model and the full per-endpoint map live in [API_GUIDE.md](../../API_GUIDE.md). ## Module assembly loading ### `ModuleAssemblyLoadContext` Per-module isolated `AssemblyLoadContext`. Resolution order: 1. Module's own directory (private DLLs) 2. Shared loader (`SharedAssemblyLoader` — common assemblies provided by the host) 3. Default ALC (host assemblies) `Collectible = true` enables `Unload()` for GC reclamation after a hot-swap. The context leaves memory once nothing outside the module refers to it; `ModuleContextMonitor` checks that after each scan and counts the contexts that stay (`OrphanedModuleContexts`, the `hotreload` health check). ### `ModulePackage` Manages `.tpkg` ZIP archives. On load, extracts the archive to a temp directory, resolves entry-point DLLs, loads them into a dedicated isolated ALC. On unload (atomic package removal), tears down all modules from the package simultaneously. ### `ModuleManifest` Deserialized from `manifest.json` inside each module directory or `.tpkg`: ```json { "Name": "Orders", "Version": "2026.05.06.1430", "EntryPoints": ["Orders.dll"], "Dependencies": ["redb.Route.Kafka"] } ``` `EntryPoints` lists DLLs containing route builders. Other DLLs in the package are companion dependencies loaded into the same ALC. ### `SharedAssemblyLoader` Coordinates assembly resolution across multiple module ALCs to avoid loading the same host-provided DLL multiple times. Modules that resolve via the shared loader get the host's singleton instance (same type identity, no interface mismatch). ### `LoadedAssemblyTracker` Prevents duplicate DLL loads when multiple modules in the same ALC reference the same assembly file. ## Storage abstractions Two storage areas are abstracted behind interfaces: | Interface | In-Memory impl | Redb-backed impl | |---|---|---| | `ITsakModuleStore` | `InMemoryTsakModuleStore` | `RedbTsakModuleStore` | | `ITsakStateStore` | `InMemoryTsakStateStore` | `RedbTsakStateStore` | `ITsakModuleStore` — persists module registrations across restarts. `ITsakStateStore` — persists context autostart flags and lifecycle audit events. Configure via `Tsak:Storage:Mode`: - `InMemory` — default; stateless restarts, no database required. - `Redb` — persistent; requires a configured `IRedbService` (Postgres or MSSql). ## Extension points | Interface | Description | |---|---| | `IContextCustomizer` | Runs after a context is created — inject custom properties or routes | | `IHealthContributor` | Contributes checks to `/api/system/health` | | `IModuleHealthContributor` | Per-module health contribution | | `IStaticModuleProvider` | Provides in-process modules without hot-reload (e.g. for testing or embedding) | | `ISystemContextPlugin` | Adds system-context routes (used by Pro for cluster endpoints) | | `ITsakLifecycleHook` | Called on context/route start/stop events | ## Key dependencies | Dependency | Purpose | |---|---| | `redb.Tsak.Contracts` | Shared DTO types for API responses | | `redb.Core` / `redb.Core.Pro` | typed object store (state + key storage) | | `redb.Route.Core` | Route context, builders, exchange model | | `redb.Route.Http` | HTTP transport for route endpoints | | `redb.Route.Quartz` | Quartz scheduler integration | | `redb.Postgres` / `redb.MSSql` | Database providers | | `Serilog` | Structured logging + ring-buffer sink | ## Related projects | Project | Role | |---|---| | [redb.Tsak.Contracts](../redb.Tsak.Contracts/README.md) | DTO models exposed by this project's controllers | | [redb.Tsak.Client](../redb.Tsak.Client/README.md) | Typed HTTP client for consuming this project's API | | [redb.Tsak.CLI](../redb.Tsak.CLI/README.md) | CLI that talks to this project via the client | | [redb.Tsak.Worker](../redb.Tsak.Worker/) | ASP.NET Core host that wires up this project | | [redb.Tsak](../../README.md) | Full project overview | Path: redb-tsak/src/redb.Tsak.Core/Security/AdminAuditEvent.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/Security/AdminAuditEvent.cs ---- namespace redb.Tsak.Core.Security; /// /// Snapshot of a single audited admin operation. /// Produced by and dispatched to . /// All fields are immutable post-construction. /// public sealed class AdminAuditEvent { /// UTC timestamp at which the action completed. public required DateTimeOffset Timestamp { get; init; } /// Logical action name (e.g. RestartContext, RevokeKey). public required string Action { get; init; } /// Controller type that owns the action. public required string ControllerType { get; init; } /// Resolved actor (principal) name from the API key, if available. public string? ActorPrincipalName { get; init; } /// API key identifier used for the request, if available. public string? ActorApiKeyId { get; init; } /// Remote IP address of the caller, if available. public string? RemoteIp { get; init; } /// Request User-Agent header, if available. public string? UserAgent { get; init; } /// HTTP method (GET, POST, …). public string? HttpMethod { get; init; } /// Request path. public string? RequestPath { get; init; } /// Identifier of the target resource (resolved from TargetParam), if any. public string? TargetResource { get; init; } /// Sanitized JSON payload of the action arguments (sensitive fields redacted). public string? Payload { get; init; } /// HTTP-style status code returned by the action. public int StatusCode { get; init; } /// Action invocation duration in milliseconds. public double DurationMs { get; init; } /// Exception type name, if the action threw. public string? ExceptionType { get; init; } /// Exception message, if the action threw. public string? ExceptionMessage { get; init; } } /// /// SPI for delivering admin audit events to a sink. The effective implementation is /// , which persists events into the flat /// tsak_audit_log table via the direct://tsak-audit route; it falls back to /// (a [tsak-audit]-anchored JSON log line) whenever /// no database is configured. /// /// Implementations MUST NOT throw — failures must be logged internally; the audit /// pipeline is best-effort and must not affect the primary action result. /// /// public interface IAdminAuditService { Task RecordAsync(AdminAuditEvent @event, CancellationToken ct); } Path: redb-tsak/src/redb.Tsak.Core/Security/AdminAuditFilter.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/Security/AdminAuditFilter.cs ---- using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using Microsoft.Extensions.Logging; using redb.Route.Controllers; using redb.Route.Http; using redb.Tsak.Contracts; namespace redb.Tsak.Core.Security; /// /// Cross-cutting filter that emits an for every action /// marked with . Runs at very high priority /// (Order = -1000) so audit metadata is captured before any other filter can mutate it. /// public sealed class AdminAuditFilter : IControllerActionFilter { private readonly IAdminAuditService _sink; private readonly ILogger _logger; private const string ItemsKey = "tsak.admin-audit.attr"; private static readonly JsonSerializerOptions PayloadJsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { ApplySensitiveModifier } } }; public AdminAuditFilter(IAdminAuditService sink, ILogger logger) { _sink = sink; _logger = logger; } public int Order => -1000; public Task BeforeAsync(ControllerActionContext context, CancellationToken ct) { // Resolve attribute once and stash for AfterAsync. var attr = context.Action.Method.GetCustomAttribute(); if (attr is not null) context.Items[ItemsKey] = attr; return Task.CompletedTask; } public async Task AfterAsync(ControllerActionContext context, CancellationToken ct) { if (!context.Items.TryGetValue(ItemsKey, out var raw) || raw is not AuditAdminActionAttribute attr) return; try { var ev = BuildEvent(context, attr); await _sink.RecordAsync(ev, ct); } catch (Exception ex) { // Best-effort: never propagate audit failures to the request. _logger.LogError(ex, "Failed to record admin audit event for action {Action}", context.Action.Method.Name); } } private static AdminAuditEvent BuildEvent(ControllerActionContext context, AuditAdminActionAttribute attr) { var actionName = attr.ActionName ?? context.Action.Method.Name; var ex = context.Exchange; string? GetProp(string key) => ex.Properties.TryGetValue(key, out var v) ? v?.ToString() : null; string? GetHeader(string key) => ex.In.Headers.TryGetValue(key, out var v) ? v?.ToString() : null; string? targetResource = null; if (!string.IsNullOrEmpty(attr.TargetParam)) { // First check route params (path tokens), then resolved arguments by name. if (context.RouteParams.TryGetValue(attr.TargetParam, out var tp)) { targetResource = tp; } else { var paramInfos = context.Action.Method.GetParameters(); for (var i = 0; i < paramInfos.Length && i < context.Arguments.Length; i++) { if (string.Equals(paramInfos[i].Name, attr.TargetParam, StringComparison.Ordinal)) { targetResource = context.Arguments[i]?.ToString(); break; } } } } var payload = SerializePayload(context.Action.Method, context.Arguments); return new AdminAuditEvent { Timestamp = DateTimeOffset.UtcNow, Action = actionName, ControllerType = context.Action.ControllerType.FullName ?? context.Action.ControllerType.Name, ActorPrincipalName = GetProp("auth.user-id") ?? GetProp("auth.key-name"), ActorApiKeyId = GetProp("auth.key-id"), RemoteIp = GetHeader(HttpHeaders.RemoteAddress), UserAgent = GetHeader("User-Agent"), HttpMethod = GetHeader(HttpHeaders.Method), RequestPath = GetHeader(HttpHeaders.Path), TargetResource = targetResource, Payload = payload, StatusCode = context.StatusCode, DurationMs = context.Elapsed.TotalMilliseconds, ExceptionType = context.Exception?.GetType().FullName, ExceptionMessage = context.Exception?.Message }; } private static string? SerializePayload(MethodInfo method, object?[] arguments) { if (arguments is null || arguments.Length == 0) return null; var paramInfos = method.GetParameters(); var dict = new Dictionary(arguments.Length, StringComparer.Ordinal); for (var i = 0; i < paramInfos.Length && i < arguments.Length; i++) { var name = paramInfos[i].Name ?? $"arg{i}"; // A raw byte[] argument (module upload: up to the 100 MB cap) must not be base64-inlined // into the audit payload — it was the one unbounded field and ballooned the audit store // by ~1.3x the package size per upload (review 2026-09-02, С25). dict[name] = arguments[i] is byte[] bytes ? $"byte[{bytes.Length}]" : arguments[i]; } try { return JsonSerializer.Serialize(dict, PayloadJsonOptions); } catch { // Defensive: never fail audit because payload couldn't serialize. return null; } } /// /// JSON contract modifier that replaces the value of any property/field marked with /// with the literal string "***". As /// defense-in-depth a property whose NAME says it is a secret (password/secret/token/keyhash) /// is masked even without the attribute — a future DTO that forgets the mark must not leak /// credentials into the trail (review 2026-09-02, К2). /// private static void ApplySensitiveModifier(JsonTypeInfo typeInfo) { if (typeInfo.Kind != JsonTypeInfoKind.Object) return; foreach (var prop in typeInfo.Properties) { var attrs = prop.AttributeProvider?.GetCustomAttributes(typeof(AuditSensitiveAttribute), inherit: true); if ((attrs is not null && attrs.Length > 0) || IsSensitiveName(prop.Name)) { prop.CustomConverter = SensitiveConverter.Instance; } } } private static bool IsSensitiveName(string name) => name.Contains("password", StringComparison.OrdinalIgnoreCase) || name.Contains("secret", StringComparison.OrdinalIgnoreCase) || name.Contains("token", StringComparison.OrdinalIgnoreCase) || name.Contains("keyhash", StringComparison.OrdinalIgnoreCase); private sealed class SensitiveConverter : JsonConverter { public static readonly SensitiveConverter Instance = new(); public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { reader.Skip(); return null; } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { writer.WriteStringValue("***"); } } } Path: redb-tsak/src/redb.Tsak.Core/Security/ApiKeyConfigReader.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/Security/ApiKeyConfigReader.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Security; /// /// Reads Tsak:Auth:Keys into s. The one place both stores use, so a key /// written in configuration behaves the same whether Tsak keeps its keys in redb or in the file. /// /// Two shapes of the same entry used to fail silently and cost a first-time user an evening. /// /// Hash case. produces UPPERCASE hex, and the stored value /// was whatever the configuration said. A lowercase hash was seeded, logged as seeded, and then matched /// nothing: the redb store looks the hash up by an exact ValueUnique comparison, which is /// case-sensitive on PostgreSQL and case-insensitive on SQL Server's default collation — the same /// configuration behaved differently per database. The hash is normalised here, once, for both stores. /// Roles as an array. Keys:0:Roles:0=admin (the shape environment variables force: /// Tsak__Auth__Keys__0__Roles__0) reads as a section, not a value, so child["Roles"] was null /// and the key ended up with no roles at all. With Tsak:Auth:EnforceRoles=true that key is refused /// everywhere, with a message about permissions rather than about its own configuration. /// /// /// internal static class ApiKeyConfigReader { /// Length of an HMAC-SHA256 hash in hex characters. private const int HashLength = 64; /// /// The records of Tsak:Auth:Keys. An entry Tsak cannot use is skipped with an error naming it — /// never in silence, because a skipped key is indistinguishable from a wrong one at the API. /// public static IReadOnlyList Read(IConfiguration configuration, ILogger logger) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(logger); var section = configuration.GetSection("Tsak:Auth:Keys"); if (!section.Exists()) return []; var records = new List(); foreach (var child in section.GetChildren()) { var id = child["Id"]; var keyHash = child["KeyHash"]; if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(keyHash)) { logger.LogError( "API key at {Path} is ignored: both Id and KeyHash are required (Id={Id}, KeyHash={HasHash}).", child.Path, id ?? "", string.IsNullOrWhiteSpace(keyHash) ? "" : "set"); continue; } var normalized = NormalizeHash(keyHash); if (normalized is null) { logger.LogError( "API key '{Id}' is ignored: KeyHash must be {Length} hexadecimal characters (an HMAC-SHA256 hash, " + "as 'tsak auth create' prints it), got {Actual} character(s).", id, HashLength, keyHash.Trim().Length); continue; } records.Add(new ApiKeyRecord { Id = id, KeyHash = normalized, Name = child["Name"] ?? "", UserId = child["UserId"], Roles = ReadRoles(child, id, logger), Revoked = bool.TryParse(child["Revoked"], out var r) && r, ExpiresAt = DateTimeOffset.TryParse(child["ExpiresAt"], out var exp) ? exp : null, CreatedAt = DateTimeOffset.TryParse(child["CreatedAt"], out var cr) ? cr : DateTimeOffset.UtcNow }); } return records; } /// /// The stored form of a key hash: trimmed, uppercase. Returns null when the value is not a hash, so the /// caller can refuse it loudly instead of storing something no lookup will ever match. /// public static string? NormalizeHash(string? keyHash) { if (string.IsNullOrWhiteSpace(keyHash)) return null; var trimmed = keyHash.Trim(); if (trimmed.Length != HashLength) return null; foreach (var c in trimmed) { var isHex = c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F'; if (!isHex) return null; } return trimmed.ToUpperInvariant(); } /// /// Roles of one key, comma-separated. Accepts both the scalar form (Roles=admin,ops) and the array /// form (Roles:0=admin, Roles:1=ops) — environment variables can only express the latter. /// private static string ReadRoles(IConfigurationSection child, string id, ILogger logger) { var scalar = child["Roles"]; if (!string.IsNullOrWhiteSpace(scalar)) return scalar; var rolesSection = child.GetSection("Roles"); if (!rolesSection.Exists()) return ""; var roles = rolesSection.GetChildren() .Select(c => c.Value) .Where(v => !string.IsNullOrWhiteSpace(v)) .Select(v => v!.Trim()) .ToList(); if (roles.Count == 0) { logger.LogWarning( "API key '{Id}' has a Roles section that yields no role. With Tsak:Auth:EnforceRoles=true such a " + "key is refused everywhere. Write roles as 'admin,ops' or as an array of values.", id); return ""; } return string.Join(",", roles); } } Path: redb-tsak/src/redb.Tsak.Core/Security/ApiKeyRecord.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/Security/ApiKeyRecord.cs ---- namespace redb.Tsak.Core.Security; /// /// Represents a stored API key with associated metadata. /// The stores HMAC-SHA256(key) — the raw key is NEVER persisted. /// public sealed record ApiKeyRecord { /// Unique identifier for this key (for revocation / listing). public required string Id { get; init; } /// HMAC-SHA256 hash of the API key. Raw key is never stored. public required string KeyHash { get; init; } /// Display name for this key (e.g., "ci-deploy", "admin-portal"). public string Name { get; init; } = ""; /// User ID the key belongs to (nullable in standalone mode). public string? UserId { get; init; } /// Comma-separated roles (e.g., "admin", "reader", "operator"). public string Roles { get; init; } = ""; /// When the key was created. public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow; /// Optional expiration. Null = never expires. public DateTimeOffset? ExpiresAt { get; init; } /// Whether this key has been revoked. public bool Revoked { get; init; } /// Checks if the key is currently valid (not expired, not revoked). public bool IsValid => !Revoked && (ExpiresAt is null || ExpiresAt > DateTimeOffset.UtcNow); /// Parsed role set for authorization checks. public IReadOnlySet GetRoles() => string.IsNullOrWhiteSpace(Roles) ? (IReadOnlySet)new HashSet() : new HashSet(Roles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); } Path: redb-tsak/src/redb.Tsak.Core/Security/ApiKeyService.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/Security/ApiKeyService.cs ---- using System.Collections.Concurrent; using System.Security.Cryptography; using System.Text; using redb.Core.Providers; namespace redb.Tsak.Core.Security; /// /// Validates API keys against . /// - Keys are hashed with HMAC-SHA256 before lookup. /// - Validated results are cached for to avoid repeated store calls. /// - Comparison uses constant-time equality via . /// public sealed class ApiKeyService { private sealed class CacheEntry { public required ApiKeyRecord Record; public DateTimeOffset CachedAt; public DateTimeOffset LastCheck; } private readonly IApiKeyStore _store; private readonly byte[] _hmacSecret; private readonly IUserProvider? _userProvider; private readonly Func _now; private readonly ConcurrentDictionary _cache = new(); /// Full cache lifetime for a validated key. After this the key is fully re-validated /// (including the linked-user enabled check). Default 5 min. public TimeSpan CacheTtl { get; set; } = TimeSpan.FromMinutes(5); /// /// How often a still-cached key is cheaply re-checked against the store for revocation/expiry /// (review item 2.7). This bounds how long a key revoked on ANOTHER node — or directly in the /// database — stays accepted here, independent of the full . Default 30s. /// Set to to re-check on every request (no revocation window, at the /// cost of a store read per hit). /// public TimeSpan RevocationCheckInterval { get; set; } = TimeSpan.FromSeconds(30); public ApiKeyService(IApiKeyStore store, byte[] hmacSecret, IUserProvider? userProvider = null, Func? now = null) { _store = store ?? throw new ArgumentNullException(nameof(store)); _hmacSecret = hmacSecret ?? throw new ArgumentNullException(nameof(hmacSecret)); if (_hmacSecret.Length < 16) throw new ArgumentException("HMAC secret must be at least 16 bytes.", nameof(hmacSecret)); _userProvider = userProvider; _now = now ?? (() => DateTimeOffset.UtcNow); } /// /// Hash a raw API key to its HMAC-SHA256 hex representation. /// This is the value stored in . /// public string HashKey(string rawKey) { ArgumentException.ThrowIfNullOrWhiteSpace(rawKey); using var hmac = new HMACSHA256(_hmacSecret); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(rawKey)); return Convert.ToHexString(hash); } /// /// Validate a raw API key. Returns the matching if valid, null otherwise. /// Uses cache + constant-time comparison. /// public async Task ValidateAsync(string rawKey, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(rawKey)) return null; var keyHash = HashKey(rawKey); var now = _now(); // Check cache first if (_cache.TryGetValue(keyHash, out var cached)) { if (now - cached.CachedAt < CacheTtl) { // Within the full lifetime, but periodically re-confirm the key was not revoked or // expired elsewhere in the cluster (or straight in the DB) — bounds the revocation // window to RevocationCheckInterval instead of the whole CacheTtl. if (now - cached.LastCheck >= RevocationCheckInterval) { var fresh = await _store.GetByHashAsync(keyHash, ct); if (fresh is null || !fresh.IsValid) { _cache.TryRemove(keyHash, out _); return null; } cached.Record = fresh; cached.LastCheck = now; } return cached.Record.IsValid ? cached.Record : null; } _cache.TryRemove(keyHash, out _); } var record = await _store.GetByHashAsync(keyHash, ct); if (record is null) return null; // Constant-time comparison of the hash to prevent timing attacks var storedBytes = Encoding.UTF8.GetBytes(record.KeyHash); var computedBytes = Encoding.UTF8.GetBytes(keyHash); if (!CryptographicOperations.FixedTimeEquals(storedBytes, computedBytes)) return null; if (!record.IsValid) return null; // If key is linked to a user and IUserProvider is available, verify the user is still enabled if (_userProvider is not null && record.UserId is not null && long.TryParse(record.UserId, out var userId)) { var user = await _userProvider.GetUserByIdAsync(userId); if (user is null || !user.Enabled) return null; } // Cache the valid record _cache[keyHash] = new CacheEntry { Record = record, CachedAt = now, LastCheck = now }; return record; } /// /// Create a new API key, store its hash, and return the raw key (shown only once). /// public async Task<(string RawKey, ApiKeyRecord Record)> CreateKeyAsync( string name, string? userId = null, string? roles = null, DateTimeOffset? expiresAt = null, CancellationToken ct = default) { var rawKey = GenerateRawKey(); var keyHash = HashKey(rawKey); var record = new ApiKeyRecord { Id = Guid.NewGuid().ToString("N"), KeyHash = keyHash, Name = name ?? "", UserId = userId, Roles = roles ?? "", CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = expiresAt, Revoked = false }; await _store.SaveAsync(record, ct); return (rawKey, record); } /// Revoke a key and remove it from cache. public async Task RevokeKeyAsync(string id, CancellationToken ct = default) { var result = await _store.RevokeAsync(id, ct); if (result) { // Evict any cached entries for revoked key foreach (var kvp in _cache) { if (kvp.Value.Record.Id == id) { _cache.TryRemove(kvp.Key, out _); break; } } } return result; } /// List all keys (admin). public Task> ListKeysAsync(CancellationToken ct = default) => _store.GetAllAsync(ct); /// Clear the validation cache (e.g., after bulk revocation). public void ClearCache() => _cache.Clear(); private static string GenerateRawKey() { var bytes = RandomNumberGenerator.GetBytes(32); return $"tsak_{Convert.ToBase64String(bytes).Replace("+", "").Replace("/", "").Replace("=", "")}"; } } Path: redb-tsak/src/redb.Tsak.Core/Security/ApiResponse.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/Security/ApiResponse.cs ---- using redb.Route.Abstractions; using redb.Route.Controllers; namespace redb.Tsak.Core.Security; /// /// Unified API error/success response helpers for all Tsak controllers. /// Uses from redb.Route.Core for consistency. /// public static class ApiResponse { private const string StatusCodeHeader = "status.code"; private const string ContentTypeHeader = "Content-Type"; private const string JsonContentType = "application/json"; /// Write a success response to exchange.Out. public static void Ok(IExchange exchange, object? body = null) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = body; exchange.Out.Headers[StatusCodeHeader] = 200; exchange.Out.Headers[ContentTypeHeader] = JsonContentType; } /// Write a 201 Created response. public static void Created(IExchange exchange, object? body = null) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = body; exchange.Out.Headers[StatusCodeHeader] = 201; exchange.Out.Headers[ContentTypeHeader] = JsonContentType; } /// Write a JSON body with any status code: an answer whose status code is part of the answer. public static void Respond(IExchange exchange, int statusCode, object body) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = body; exchange.Out.Headers[StatusCodeHeader] = statusCode; exchange.Out.Headers[ContentTypeHeader] = JsonContentType; } /// Write a 204 No Content response. public static void NoContent(IExchange exchange) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = null; exchange.Out.Headers[StatusCodeHeader] = 204; } /// Write an error response using the standard ControllerErrorResponse format. public static void Error(IExchange exchange, int statusCode, string error, string message) { exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = new ControllerErrorResponse { Error = error, Message = message, StatusCode = statusCode }; exchange.Out.Headers[StatusCodeHeader] = statusCode; exchange.Out.Headers[ContentTypeHeader] = JsonContentType; } /// 400 Bad Request. public static void BadRequest(IExchange exchange, string message) => Error(exchange, 400, "BadRequest", message); /// 401 Unauthorized. public static void Unauthorized(IExchange exchange, string message = "Unauthorized") => Error(exchange, 401, "Unauthorized", message); /// 403 Forbidden. public static void Forbidden(IExchange exchange, string message = "Forbidden") => Error(exchange, 403, "Forbidden", message); /// 404 Not Found. public static void NotFound(IExchange exchange, string message) => Error(exchange, 404, "NotFound", message); /// 429 Too Many Requests. public static void TooManyRequests(IExchange exchange, string message = "Too many requests") => Error(exchange, 429, "TooManyRequests", message); /// 409 Conflict. public static void Conflict(IExchange exchange, string message) => Error(exchange, 409, "Conflict", message); /// 500 Internal Server Error. public static void InternalError(IExchange exchange, string message = "Internal server error") => Error(exchange, 500, "InternalError", message); /// 503 Service Unavailable. public static void ServiceUnavailable(IExchange exchange, string message = "Service unavailable") => Error(exchange, 503, "ServiceUnavailable", message); } Path: redb-tsak/src/redb.Tsak.Core/Security/AuditAttributes.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/Security/AuditAttributes.cs ---- namespace redb.Tsak.Core.Security; /// /// Marks a controller action as an audited admin operation. /// When applied, records an /// through the registered /// after the action completes (success or failure). /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class AuditAdminActionAttribute : Attribute { /// /// Optional logical action name. If not specified, the controller method name is used. /// public string? ActionName { get; init; } /// /// Optional name of the action parameter that identifies the target resource /// (e.g. contextName, routeId, userId). When set, the filter /// records the resolved argument value into . /// public string? TargetParam { get; init; } } // AuditSensitiveAttribute moved to redb.Tsak.Contracts (2026-09-02): the DTOs that need the mark // live there, and Contracts cannot reference Core — which is why the attribute was applied to // nothing while it lived here (review К2). Path: redb-tsak/src/redb.Tsak.Core/Security/AuthorizeProcessor.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/Security/AuthorizeProcessor.cs ---- using redb.Route.Abstractions; using Serilog; namespace redb.Tsak.Core.Security; /// /// Route pipeline processor that enforces API key authentication. /// Extracts key from Authorization header (Bearer tsak_...) or X-Api-Key header, /// validates via , and sets auth properties on the exchange. /// On failure, writes 401/403 to exchange.Out and stops the pipeline. /// public sealed class AuthorizeProcessor : IProcessor { private static readonly ILogger Log = Serilog.Log.ForContext(); private readonly ApiKeyService _keyService; private readonly string[]? _requiredRoles; public AuthorizeProcessor(ApiKeyService keyService, string[]? requiredRoles = null) { _keyService = keyService ?? throw new ArgumentNullException(nameof(keyService)); _requiredRoles = requiredRoles; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var rawKey = ExtractApiKey(exchange); if (string.IsNullOrWhiteSpace(rawKey)) { Log.Warning("API request rejected: missing API key"); ApiResponse.Unauthorized(exchange, "Missing API key. Provide via Authorization: Bearer or X-Api-Key header."); exchange.Stop(); return; } var record = await _keyService.ValidateAsync(rawKey, ct); if (record is null) { Log.Warning("API request rejected: invalid or expired API key"); ApiResponse.Unauthorized(exchange, "Invalid or expired API key."); exchange.Stop(); return; } // Check required roles if specified if (_requiredRoles is { Length: > 0 }) { var userRoles = record.GetRoles(); var hasRole = false; foreach (var role in _requiredRoles) { if (userRoles.Contains(role)) { hasRole = true; break; } } if (!hasRole) { Log.Warning("API request rejected: insufficient roles for key {KeyId}. Required: {Required}, Has: {Has}", record.Id, string.Join(",", _requiredRoles), record.Roles); ApiResponse.Forbidden(exchange, "Insufficient permissions."); exchange.Stop(); return; } } // Auth passed — set properties for downstream processors/controllers exchange.Properties["auth.key-id"] = record.Id; exchange.Properties["auth.key-name"] = record.Name; exchange.Properties["auth.user-id"] = record.UserId; exchange.Properties["auth.roles"] = record.Roles; exchange.Properties["auth.authenticated"] = true; Log.Debug("API key authenticated: {KeyName} ({KeyId}), roles: {Roles}", record.Name, record.Id, record.Roles); } private static string? ExtractApiKey(IExchange exchange) { // Try Authorization: Bearer var auth = exchange.In.getHeader("Authorization")?.ToString(); if (!string.IsNullOrWhiteSpace(auth)) { const string bearerPrefix = "Bearer "; if (auth.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase)) return auth[bearerPrefix.Length..].Trim(); } // Fallback: X-Api-Key header var apiKey = exchange.In.getHeader("X-Api-Key")?.ToString(); if (!string.IsNullOrWhiteSpace(apiKey)) return apiKey; return null; } } Path: redb-tsak/src/redb.Tsak.Core/Security/ConfigApiKeyStore.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/Security/ConfigApiKeyStore.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace redb.Tsak.Core.Security; /// /// API key store backed by IConfiguration (appsettings). /// Reads pre-hashed keys from Tsak:Auth:Keys[] section. /// Suitable for standalone / headless deployments without a database. /// /// Config format: /// /// "Tsak": { /// "Auth": { /// "Keys": [ /// { "Id": "key1", "KeyHash": "A1B2...", "Name": "admin", "Roles": "admin", "UserId": "u1" } /// ] /// } /// } /// /// public sealed class ConfigApiKeyStore : IApiKeyStore { private readonly List _keys; /// Host configuration carrying Tsak:Auth:Keys. /// /// Takes the reader's report on entries it had to refuse. Optional so a host that builds the store by hand /// keeps working; in DI the logger is always there. /// public ConfigApiKeyStore(IConfiguration configuration, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(configuration); _keys = [.. ApiKeyConfigReader.Read(configuration, logger ?? NullLogger.Instance)]; } public Task GetByHashAsync(string keyHash, CancellationToken ct = default) { var record = _keys.Find(k => string.Equals(k.KeyHash, keyHash, StringComparison.OrdinalIgnoreCase)); return Task.FromResult(record); } public Task> GetAllAsync(CancellationToken ct = default) => Task.FromResult>(_keys.AsReadOnly()); public Task SaveAsync(ApiKeyRecord record, CancellationToken ct = default) { var idx = _keys.FindIndex(k => k.Id == record.Id); if (idx >= 0) _keys[idx] = record; else _keys.Add(record); return Task.CompletedTask; } public Task RevokeAsync(string id, CancellationToken ct = default) { var idx = _keys.FindIndex(k => k.Id == id); if (idx < 0) return Task.FromResult(false); _keys[idx] = _keys[idx] with { Revoked = true }; return Task.FromResult(true); } } Path: redb-tsak/src/redb.Tsak.Core/Security/ConfigRedactor.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/Security/ConfigRedactor.cs ---- using System.Text.RegularExpressions; namespace redb.Tsak.Core.Security; /// /// Redacts secrets from effective-configuration output (GET /api/system/config). /// /// Three layers, applied in order: /// /// Sensitive key — the value is masked wholesale when any segment of the key path /// (not just the leaf) looks sensitive: password / secret / token / apikey / authorization / /// webhook / … . A webhook URL is itself a bearer credential, so the whole value goes. /// Embedded connection-string password — a Password=/Pwd= segment is /// masked inside any value, not only under the ConnectionStrings: prefix, so the /// host/database stay visible for diagnostics while the password does not. /// URI userinfo — scheme://user:pass@host in any value has its userinfo masked /// (scheme://***@host), catching broker/endpoint URIs like amqp://u:p@host. /// /// Fail-closed bias: the key-path check errs toward over-masking (a benign value under a sensitive- /// looking path is masked) rather than leaking. /// /// public static partial class ConfigRedactor { // Matched against the WHOLE key path (case-insensitive substring), so e.g. // "Tsak:Alerts:Webhook:Url" masks on "webhook" even though its leaf is "Url", and // "…:Headers:Authorization" masks on "authorization". Deliberately NOT including a bare // "connectionstring" marker: real connection strings are scrubbed partially (rule 2) so their // host/database stay visible. private static readonly string[] SensitiveKeyMarkers = { "password", "pwd", "passwd", "secret", "token", "apikey", "keyhash", "privatekey", "credential", "authorization", "accountkey", "sastoken", "webhook", }; /// Redacts one key/value pair. Returns (value, wasRedacted). public static (string? value, bool redacted) Redact(string key, string? value) { if (value is null) return (null, false); // Rule 1: sensitive key path → mask the value wholesale (empty stays empty, nothing to hide). foreach (var marker in SensitiveKeyMarkers) if (key.Contains(marker, StringComparison.OrdinalIgnoreCase)) return (value.Length == 0 ? value : "***", value.Length != 0); // Rules 2 & 3: scrub embedded secrets inside the value, wherever the value lives. var scrubbed = PasswordAssignment().Replace(value, m => m.Groups[1].Value + "***"); scrubbed = UriUserInfo().Replace(scrubbed, m => m.Groups[1].Value + "***@"); return (scrubbed, scrubbed != value); } // "Password=" / "Pwd=" up to the next ';' or end — connection-string style, in any value. [GeneratedRegex(@"(?i)(\b(?:password|pwd)\s*=\s*)[^;]*", RegexOptions.Compiled)] private static partial Regex PasswordAssignment(); // "scheme://userinfo@" — the userinfo (user[:pass]) of a URI authority. [^/@\s] keeps the match // inside the authority so an '@' later in a path/query is never mistaken for userinfo. [GeneratedRegex(@"(?i)([a-z][a-z0-9+.\-]*://)[^/@\s]*@", RegexOptions.Compiled)] private static partial Regex UriUserInfo(); } Path: redb-tsak/src/redb.Tsak.Core/Security/FailedAttemptThrottle.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/Security/FailedAttemptThrottle.cs ---- using System.Collections.Concurrent; namespace redb.Tsak.Core.Security; /// /// Per-key failed-attempt throttle (review item 4.5). After failures within /// the key is locked out for , defeating online guessing. /// A success clears the counter, so a legitimate caller with a valid credential never accumulates state. /// /// This is the API-key analogue of the dashboard's LoginThrottle (review item 2.6): the same /// failure-count-and-lockout semantics and the same per-entry lock discipline (see the concurrency note in /// ). It gates the ACTUAL authentication surface — every API request carries a /// key, so the throttle keys on the client IP and counts key-auth failures across all endpoints, not just a /// single path prefix (which was the 4.5 defect: a path-limited request-count gate that key-guessing simply /// routed around). /// /// Pure and clock-injectable so lockout timing is unit-testable without waiting. /// Known limitation (F3): because a success clears the key's counter, principals that share /// one key (NAT / corporate egress / a single reverse-proxy IP when TrustProxyHeaders is off) can /// let a legitimate user's success reset an attacker's failure count. Key on the real per-client IP /// (enable TrustProxyHeaders behind a proxy) to avoid the shared-bucket weakening. /// public sealed class FailedAttemptThrottle { // Above this many tracked keys, RecordFailure opportunistically evicts expired entries so a burst of // distinct source IPs (e.g. an IPv6 /64) cannot grow the map without bound (review item 4.5 / F4). private const int SweepThreshold = 10_000; private sealed class Entry { public int Failures; public DateTimeOffset WindowStart; public DateTimeOffset LockedUntil; } private readonly ConcurrentDictionary _entries = new(StringComparer.OrdinalIgnoreCase); private readonly Func _now; public int MaxAttempts { get; } public TimeSpan Window { get; } public TimeSpan LockoutDuration { get; } public FailedAttemptThrottle( int maxAttempts = 10, TimeSpan? window = null, TimeSpan? lockoutDuration = null, Func? now = null) { MaxAttempts = maxAttempts < 1 ? 1 : maxAttempts; Window = window ?? TimeSpan.FromSeconds(60); LockoutDuration = lockoutDuration ?? TimeSpan.FromSeconds(120); _now = now ?? (() => DateTimeOffset.UtcNow); } /// True when is currently locked out. public bool IsLockedOut(string key) { if (string.IsNullOrEmpty(key)) return false; if (!_entries.TryGetValue(key, out var e)) return false; lock (e) { return _now() < e.LockedUntil; } } /// Record a failed attempt; may transition the key into lockout. public void RecordFailure(string key) { if (string.IsNullOrEmpty(key)) return; var now = _now(); // GetOrAdd hands back a single shared Entry; the read-modify-write below MUST be under the entry // lock. A mutate-in-place AddOrUpdate returns the same reference, so ConcurrentDictionary does a // no-op reference "update" with no serialization — two concurrent failures both do a non-atomic // Failures++ and one increment is lost, letting concurrent guessing slip under the lockout // threshold (same class of bug fixed for LoginThrottle — cookie-auth finding #1). var entry = _entries.GetOrAdd(key, _ => new Entry { WindowStart = now }); lock (entry) { // Fresh window if the previous one elapsed (and we are not already locked). if (now >= entry.LockedUntil && now - entry.WindowStart > Window) { entry.Failures = 0; entry.WindowStart = now; } entry.Failures++; if (entry.Failures >= MaxAttempts) { entry.LockedUntil = now + LockoutDuration; entry.Failures = 0; // reset so the next lockout needs a fresh burst entry.WindowStart = now + LockoutDuration; } } // Opportunistic eviction: only pays the O(n) scan once the map is large, keeping steady-state // RecordFailure O(1) while bounding memory against a flood of distinct source IPs (F4). if (_entries.Count > SweepThreshold) SweepExpired(now); } /// Removes entries whose lockout has elapsed and whose failure window has rolled off — i.e. /// keys that would report as not-locked and would /// treat as a fresh window anyway. Dropping them changes no observable behaviour. private void SweepExpired(DateTimeOffset now) { foreach (var kv in _entries) { var e = kv.Value; bool dead; lock (e) { dead = now >= e.LockedUntil && now - e.WindowStart > Window; } if (dead) _entries.TryRemove(kv.Key, out _); } } /// Clear any failure/lockout state for after a success. public void RecordSuccess(string key) { if (string.IsNullOrEmpty(key)) return; _entries.TryRemove(key, out _); } } Path: redb-tsak/src/redb.Tsak.Core/Security/IApiKeyStore.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/Security/IApiKeyStore.cs ---- namespace redb.Tsak.Core.Security; /// /// Persistent store for API keys. Implementations: config-based, redb-backed, etc. /// public interface IApiKeyStore { /// Find a key record by its hash. Returns null if not found. Task GetByHashAsync(string keyHash, CancellationToken ct = default); /// Get all key records (for admin listing). Task> GetAllAsync(CancellationToken ct = default); /// Save (insert or update) a key record. Task SaveAsync(ApiKeyRecord record, CancellationToken ct = default); /// Revoke a key by its Id. Task RevokeAsync(string id, CancellationToken ct = default); } Path: redb-tsak/src/redb.Tsak.Core/Security/LogAdminAuditService.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/Security/LogAdminAuditService.cs ---- using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Security; /// /// Fallback used when Tsak runs without a database /// (Tsak:Storage:Type=InMemory / no Tsak:Redb:Provider) or when audit /// persistence is switched off. /// /// The event is written as a single line: the literal anchor [tsak-audit] followed by /// one JSON object. The anchor sits at the start of the message so a standalone deployment can /// grep the line and parse everything after the anchor with any JSON reader — no log-format /// parsing, no multi-line handling. /// /// /// When a provider IS configured, takes over and writes to /// tsak_audit_log; this sink then only receives events the database rejected. /// /// public sealed class LogAdminAuditService : IAdminAuditService { /// Line prefix that makes audit events greppable in a plain log file. public const string Anchor = "[tsak-audit]"; private static readonly JsonSerializerOptions JsonOptions = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, WriteIndented = false }; private readonly ILogger _logger; public LogAdminAuditService(ILogger logger) { _logger = logger; } public Task RecordAsync(AdminAuditEvent @event, CancellationToken ct) { string json; try { json = JsonSerializer.Serialize(new AuditLogLine(@event), JsonOptions); } catch (Exception ex) { // Serialization must never cost us the event — fall back to a flat line. _logger.LogWarning(ex, "{Anchor} failed to serialize audit event {Action}", Anchor, @event.Action); return Task.CompletedTask; } // WRN so events stand out against an INF baseline. The anchor is a literal, not a // placeholder, so it is identical in both the rendered line and structured sinks. _logger.LogWarning("[tsak-audit] {AuditJson}", json); return Task.CompletedTask; } /// Wire shape of the JSON that follows the anchor — camelCase, nulls omitted. private sealed record AuditLogLine { public AuditLogLine(AdminAuditEvent e) { Ts = e.Timestamp; Action = e.Action; Controller = e.ControllerType; Actor = e.ActorPrincipalName; KeyId = e.ActorApiKeyId; Ip = e.RemoteIp; UserAgent = e.UserAgent; Method = e.HttpMethod; Path = e.RequestPath; Target = e.TargetResource; Status = e.StatusCode; DurationMs = Math.Round(e.DurationMs, 1); ExceptionType = e.ExceptionType; ExceptionMessage = e.ExceptionMessage; // The payload was the one untruncated field of the log line (review 2026-09-02, С25/К2): // an oversized argument dump must not flood the ring buffer and log files. Payload = e.Payload is { Length: > 4096 } p ? p[..4096] + "…(truncated)" : e.Payload; } [JsonPropertyName("ts")] public DateTimeOffset Ts { get; } [JsonPropertyName("action")] public string Action { get; } [JsonPropertyName("controller")] public string? Controller { get; } [JsonPropertyName("actor")] public string? Actor { get; } [JsonPropertyName("keyId")] public string? KeyId { get; } [JsonPropertyName("ip")] public string? Ip { get; } [JsonPropertyName("userAgent")] public string? UserAgent { get; } [JsonPropertyName("method")] public string? Method { get; } [JsonPropertyName("path")] public string? Path { get; } [JsonPropertyName("target")] public string? Target { get; } [JsonPropertyName("status")] public int Status { get; } [JsonPropertyName("durationMs")] public double DurationMs { get; } [JsonPropertyName("exceptionType")] public string? ExceptionType { get; } [JsonPropertyName("exceptionMessage")] public string? ExceptionMessage { get; } [JsonPropertyName("payload")] public string? Payload { get; } } } Path: redb-tsak/src/redb.Tsak.Core/Security/RedbApiKeyStore.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/Security/RedbApiKeyStore.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Attributes; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tsak.Contracts; namespace redb.Tsak.Core.Security; /// /// Props class for API key entries stored as redb objects. /// public class ApiKeyProps { public string KeyHash { get; set; } = string.Empty; /// /// Public identifier for revocation/listing. Unique per scheme via [RedbUnique] /// (a duplicate id in config surfaces loudly at seeding); nullable so legacy rows /// without an id stay outside the unique index. Mirrored to note for display. /// [RedbUnique] public string? Id { get; set; } public string Name { get; set; } = string.Empty; public string? UserId { get; set; } public string Roles { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? ExpiresAt { get; set; } public bool Revoked { get; set; } } /// /// Redb-backed API key store. Persists keys across restarts and cluster nodes. /// The hash lives in ValueUnique — one record per key is enforced by the database /// (concurrent seeding on several nodes cannot duplicate), and the lookup on every request /// is a single probe of the unique index. Props.Id carries its own /// [RedbUnique] key, so revocation resolves the record by one indexed probe too; /// rotating a key's secret in config (same id, new hash) updates the id's record in place. /// value_string still mirrors the hash for compatibility. /// public sealed class RedbApiKeyStore : IApiKeyStore { private readonly IServiceScopeFactory _scopeFactory; private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly SemaphoreSlim _seedLock = new(1, 1); private volatile bool _seeded; public RedbApiKeyStore(IServiceScopeFactory scopeFactory, IConfiguration configuration, ILogger logger) { _scopeFactory = scopeFactory; _configuration = configuration; _logger = logger; } /// /// One-time per process: scheme sync, V4 legacy-key backfill, then seeding of pre-hashed /// keys from Tsak:Auth:Keys. Serialized and latched only AFTER success — the old code set /// the flag first, so a concurrent first request skipped ahead to key lookups that could /// not see un-backfilled legacy rows, and one mid-seed exception disabled legacy keys /// until restart (review 2026-09-02, В3). /// private async Task EnsureSeededAsync(CancellationToken ct = default) { if (_seeded) return; await _seedLock.WaitAsync(ct); try { if (_seeded) return; using (var scope = _scopeFactory.CreateScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await BackfillLegacyKeysAsync(redb, _logger); } foreach (var record in ApiKeyConfigReader.Read(_configuration, _logger)) { var existing = await GetByHashInternalAsync(record.KeyHash, ct); if (existing is not null) continue; await SaveCoreAsync(record, ct); _logger.LogInformation("Seeded API key '{Name}' (id={Id}) from config", record.Name, record.Id); } _seeded = true; } finally { _seedLock.Release(); } } /// /// The ONE home of the api-key legacy migration rule: stamp the hash into ValueUnique and /// the id from note into Props.Id. Called from the store's own ensure step /// (hosts without TsakHostedService) and from TsakHostedService startup. /// internal static Task BackfillLegacyKeysAsync(IRedbService redb, ILogger logger) => Services.Storage.TsakUniqueBackfill.RunAsync( redb, o => o.ValueString ?? o.Props?.KeyHash, Services.Storage.TsakUniqueBackfill.DuplicatePolicy.DeleteLosers, logger, winner => { if (winner.Props is not null && string.IsNullOrEmpty(winner.Props.Id)) winner.Props.Id = winner.note; }); public async Task GetByHashAsync(string keyHash, CancellationToken ct = default) { await EnsureSeededAsync(ct); return await GetByHashInternalAsync(keyHash, ct); } private async Task GetByHashInternalAsync(string keyHash, CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); // The lookup is an exact comparison — case-sensitive on PostgreSQL, case-insensitive on SQL Server's // default collation. Both sides are normalised to the stored form so the same key behaves the same on // every provider: ApiKeyService.HashKey produces uppercase, and so does the config reader. keyHash = ApiKeyConfigReader.NormalizeHash(keyHash) ?? keyHash; var obj = await redb.Query() .WhereRedb(o => o.ValueUnique == keyHash) .FirstOrDefaultAsync(); return obj is not null ? ToRecord(obj) : null; } public async Task> GetAllAsync(CancellationToken ct = default) { await EnsureSeededAsync(ct); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var objects = await redb.Query().ToListAsync(); return objects.Select(ToRecord).ToList(); } public async Task SaveAsync(ApiKeyRecord record, CancellationToken ct = default) { await EnsureSeededAsync(ct); await SaveCoreAsync(record, ct); } private async Task SaveCoreAsync(ApiKeyRecord record, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); RedbObject Compose() => new() { name = record.Name, ValueUnique = record.KeyHash, value_string = record.KeyHash, value_long = record.Revoked ? 1 : 0, note = record.Id, Props = ToProps(record) }; try { await redb.SaveByUniqueAsync(Compose()); } catch (RedbUniqueViolationException uve) when (uve.Kind == RedbUniqueViolationKind.Property) { // First-class discrimination since BR-8 closed: an ObjectKey race is retried by the // core itself, so what reaches us classified as Property is the [RedbUnique] Id // index — the id already exists under a DIFFERENT hash, i.e. key rotation (same id, // new secret in config). Update the id's record in place — the row swaps its hash // key; pre-fix this threw into the auth path and the rotated key never worked // (review 2026-09-02, К5). var existing = string.IsNullOrEmpty(record.Id) ? null : await redb.GetByUniqueAsync(p => p.Id, record.Id); if (existing is null) throw; _logger.LogInformation("API key id '{Id}' rotated: replacing its stored hash", record.Id); var updated = Compose(); updated.id = existing.id; await redb.SaveAsync(updated); } } public async Task RevokeAsync(string id, CancellationToken ct = default) { // Revocation of a legacy key depends on the backfill having stamped Props.Id — this was // the one method that skipped the ensure step (review 2026-09-02, С8). await EnsureSeededAsync(ct); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = await redb.GetByUniqueAsync(p => p.Id, id); if (obj is null) return false; obj.Props!.Revoked = true; obj.value_long = 1; await redb.SaveAsync(obj); return true; } // ── Mapping helpers ────────────────────────────────────────────── private static ApiKeyRecord ToRecord(RedbObject obj) { var props = obj.Props!; return new ApiKeyRecord { Id = props.Id ?? obj.note ?? "", KeyHash = props.KeyHash, Name = props.Name, UserId = props.UserId, Roles = props.Roles, CreatedAt = props.CreatedAt, ExpiresAt = props.ExpiresAt, Revoked = props.Revoked }; } private static ApiKeyProps ToProps(ApiKeyRecord record) => new() { KeyHash = record.KeyHash, Id = string.IsNullOrEmpty(record.Id) ? null : record.Id, Name = record.Name, UserId = record.UserId, Roles = record.Roles, CreatedAt = record.CreatedAt, ExpiresAt = record.ExpiresAt, Revoked = record.Revoked }; } Path: redb-tsak/src/redb.Tsak.Core/Security/RoleAttributes.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/Security/RoleAttributes.cs ---- namespace redb.Tsak.Core.Security; /// /// Well-known Tsak roles, ordered by privilege: < /// < . A key holding a higher role /// satisfies a requirement for a lower one — admin can do everything /// operator can, and so on. /// /// Roles outside this ladder (custom roles on a key) are matched by exact name only. /// /// public static class TsakRoles { /// Read-only access: every GET endpoint. public const string Viewer = "viewer"; /// Day-to-day operations: context / route / scheduler lifecycle. public const string Operator = "operator"; /// Full control: keys, users, module removal, force-stop, cluster surgery. public const string Admin = "admin"; /// /// Privilege rank of a well-known role (higher wins). Returns 0 for /// custom roles, which therefore only ever satisfy an exact-name requirement. /// public static int RankOf(string role) => role?.Trim().ToLowerInvariant() switch { "viewer" or "reader" or "read" => 1, "operator" or "ops" => 2, "admin" or "administrator" => 3, _ => 0 }; /// /// True when satisfies — either by /// exact name (case-insensitive) or by outranking it on the well-known ladder. /// public static bool Satisfies(IReadOnlySet held, IReadOnlyList required) { foreach (var need in required) { if (held.Contains(need)) return true; var needRank = RankOf(need); if (needRank == 0) continue; // custom role — exact match only foreach (var have in held) if (RankOf(have) >= needRank) return true; } return false; } } /// /// Declares the role(s) required to invoke a controller action. Applied to a method it /// governs that action; applied to a controller it governs every action the controller /// declares (a method-level attribute wins over the controller-level one). /// /// Multiple roles are OR-ed: [RequiresRole(TsakRoles.Operator, "release-bot")] admits /// a key holding either. Enforcement happens in , /// which runs only for authenticated requests — auth-exempt technical endpoints /// (Kubernetes probes) are never gated. /// /// /// Actions with no attribute fall back to a method-based default: GET and HEAD /// require , everything else requires /// . A new endpoint is therefore never open by accident. /// /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class RequiresRoleAttribute : Attribute { /// Roles that satisfy this requirement (OR semantics). public string[] Roles { get; } public RequiresRoleAttribute(params string[] roles) { Roles = roles is { Length: > 0 } ? roles : throw new ArgumentException("At least one role must be specified.", nameof(roles)); } } /// /// Marks an action (or a whole controller) as requiring no particular role — a valid API key /// is enough. Intended for technical endpoints: Kubernetes probes, echo-style /// reachability checks, and anything a load balancer or orchestrator calls. /// /// Those endpoints are normally auth-exempt altogether (Tsak:Api:AuthExempt), so the /// role check never even reaches them. This attribute is the second line of defence: if an /// operator narrows the exempt list, the endpoint starts requiring a key but still must not /// start demanding privileges — a probe that answers 403 would take the pod out of /// rotation for the wrong reason. /// /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class NoRoleRequiredAttribute : Attribute { } Path: redb-tsak/src/redb.Tsak.Core/Security/RoleAuthorizationProcessor.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/Security/RoleAuthorizationProcessor.cs ---- using System.Collections.Concurrent; using System.Reflection; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; using Serilog; namespace redb.Tsak.Core.Security; /// /// Enforces on controller actions. /// Runs after and before /// : it resolves the action the request would /// hit, works out the required role, and answers 403 when the caller's key does not /// hold it. /// /// Technical endpoints are never gated. The processor no-ops unless the exchange /// carries auth.authenticated = true, so auth-exempt paths (Kubernetes probes under /// /api/health/*) pass straight through, as do all requests when auth is disabled. /// The echo and Prometheus routes have their own pipelines and never reach this processor /// at all. On top of that, an action marked is skipped /// even when it *is* authenticated. /// /// /// Actions without an explicit attribute fall back to a safe default derived from the HTTP /// method: reads need , writes need /// . /// /// public sealed class RoleAuthorizationProcessor : IProcessor { private static readonly ILogger Log = Serilog.Log.ForContext(); /// Sentinel stored in the cache for actions that must not be gated. private static readonly string[] NoGate = Array.Empty(); private readonly ControllerRegistry _registry; private readonly bool _rolelessKeysAreAdmin; /// Resolved requirement per action method — attribute lookup is reflection, cache it. private readonly ConcurrentDictionary _cache = new(); /// Key ids already warned about, so a legacy key logs once, not once per request. private readonly ConcurrentDictionary _warnedKeys = new(); /// The same registry the dispatcher uses, so both resolve identically. /// /// Back-compat switch (Tsak:Auth:RolelessKeysAreAdmin, default false = fail-closed): /// a key with no roles is DENIED role-gated endpoints. Set to true only to keep pre-RBAC keys /// (issued before roles were enforced, carrying no roles) working as admin during migration. /// public RoleAuthorizationProcessor(ControllerRegistry registry, bool rolelessKeysAreAdmin = false) { _registry = registry ?? throw new ArgumentNullException(nameof(registry)); _rolelessKeysAreAdmin = rolelessKeysAreAdmin; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { // Anonymous request. Either auth is off, or this is an auth-exempt technical // endpoint (k8s probes). Nothing to authorize — never gate those. if (exchange.Properties.TryGetValue("auth.authenticated", out var authenticated) is false || authenticated is not true) return Task.CompletedTask; var path = exchange.In.Headers.TryGetValue(ControllerDispatcherProcessor.PathHeader, out var p) ? p?.ToString() : null; var method = exchange.In.Headers.TryGetValue(ControllerDispatcherProcessor.MethodHeader, out var m) ? m?.ToString() : null; if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(method)) return Task.CompletedTask; // dispatcher will answer 400 var action = _registry.Resolve(method, path, out _); if (action is null) return Task.CompletedTask; // dispatcher will answer 404 — do not leak existence via 403 var required = RequiredRolesFor(action); if (ReferenceEquals(required, NoGate)) return Task.CompletedTask; var held = ParseRoles(exchange.Properties.TryGetValue("auth.roles", out var r) ? r?.ToString() : null); if (held.Count == 0) { var keyId = exchange.Properties.TryGetValue("auth.key-id", out var k) ? k?.ToString() ?? "?" : "?"; if (_rolelessKeysAreAdmin) { if (_warnedKeys.TryAdd(keyId, 0)) Log.Warning( "API key {KeyId} carries no roles — treated as '{Admin}' for compatibility. " + "Re-issue it with explicit roles, or set Tsak:Auth:RolelessKeysAreAdmin=false to deny.", keyId, TsakRoles.Admin); return Task.CompletedTask; } Log.Warning("API request rejected: key {KeyId} carries no roles, required {Required}", keyId, string.Join(" or ", required)); Deny(exchange, required); return Task.CompletedTask; } if (TsakRoles.Satisfies(held, required)) return Task.CompletedTask; Log.Warning( "API request rejected: insufficient role for {Method} {Path}. Required: {Required}, has: {Held}", method, path, string.Join(" or ", required), string.Join(",", held)); Deny(exchange, required); return Task.CompletedTask; } private static void Deny(IExchange exchange, IReadOnlyList required) { ApiResponse.Forbidden(exchange, $"Insufficient permissions. Required role: {string.Join(" or ", required)}."); exchange.Stop(); } /// /// Requirement for an action: method attribute → controller attribute → default by HTTP method. /// Returns when the action opts out via . /// private string[] RequiredRolesFor(ControllerAction action) => _cache.GetOrAdd(action.Method, _ => { if (action.Method.GetCustomAttribute(inherit: true) is not null || action.ControllerType.GetCustomAttribute(inherit: true) is not null) return NoGate; var attr = action.Method.GetCustomAttribute(inherit: true) ?? action.ControllerType.GetCustomAttribute(inherit: true); if (attr is not null) return attr.Roles; // No attribute — safe default so a new endpoint is never open by accident. return action.HttpMethod is HttpMethodType.Get ? new[] { TsakRoles.Viewer } : new[] { TsakRoles.Operator }; }); private static IReadOnlySet ParseRoles(string? raw) => string.IsNullOrWhiteSpace(raw) ? (IReadOnlySet)new HashSet(StringComparer.OrdinalIgnoreCase) : new HashSet( raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); } Path: redb-tsak/src/redb.Tsak.Core/Security/RouteAdminAuditService.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/Security/RouteAdminAuditService.cs ---- using System.Globalization; using System.Threading.Channels; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Tsak.Core.Audit; namespace redb.Tsak.Core.Security; /// /// Persistent admin audit sink: hands each event to the direct://tsak-audit route, /// which writes it into tsak_audit_log. /// /// Fire-and-forget by design. Events go through a bounded in-memory queue drained by a /// background pump, so an API call never waits for the database and a broken audit backend can /// never take the node down. The trade-off is explicit: on a hard kill the queued tail is lost, /// and under a sustained flood the oldest queued events are dropped (with a warning) rather /// than growing memory without bound. /// /// /// Until is called — and permanently when Tsak runs without a database — /// events fall through to the fallback the constructor takes, the log sink. /// /// public sealed class RouteAdminAuditService : IAdminAuditService, IAsyncDisposable { /// Queue depth before the oldest events start being dropped. private const int QueueCapacity = 1000; private readonly IAdminAuditService _fallback; private readonly ILogger _logger; private readonly Channel _queue; private readonly CancellationTokenSource _shutdown = new(); private ProducerTemplate? _producer; private Task? _pump; private long _dropped; private bool _disposed; public RouteAdminAuditService(IAdminAuditService fallback, ILogger logger) { _fallback = fallback; _logger = logger; _queue = Channel.CreateBounded(new BoundedChannelOptions(QueueCapacity) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); } /// True once a route context is attached and events are being persisted. public bool IsPersisting => _producer is not null; /// /// Binds the sink to the route context that hosts the audit writer route. Called by /// SystemContextBuilder after the route is registered and the context is started. /// public void Attach(IRouteContext context) { if (_disposed || _producer is not null) return; var producer = new ProducerTemplate(context); if (!producer.IsStarted) producer.Start(); _producer = producer; _pump = Task.Run(PumpAsync); _logger.LogInformation("Admin audit events are persisted via {Endpoint}", AuditStorage.AuditEndpoint); } /// public Task RecordAsync(AdminAuditEvent @event, CancellationToken ct) { if (_disposed || _producer is null) return _fallback.RecordAsync(@event, ct); // DropOldest never blocks and never fails — TryWrite returning false is not expected, // but treat it as a drop rather than losing the event silently. if (!_queue.Writer.TryWrite(@event)) ReportDrop(); return Task.CompletedTask; } private async Task PumpAsync() { try { await foreach (var @event in _queue.Reader.ReadAllAsync(_shutdown.Token)) { try { await _producer!.SendAsync(AuditStorage.AuditEndpoint, BuildMessage(@event)); } catch (Exception ex) { // The audit backend is unreachable or the table is missing. Keep the event // visible through the log sink and carry on — never break the pump. _logger.LogWarning(ex, "Failed to persist admin audit event {Action}", @event.Action); await SafeFallbackAsync(@event); } } } catch (OperationCanceledException) { // Shutdown. } } private async Task SafeFallbackAsync(AdminAuditEvent @event) { try { await _fallback.RecordAsync(@event, CancellationToken.None); } catch { // The fallback is a logger; if even that throws there is nowhere left to report. } } private void ReportDrop() { var dropped = Interlocked.Increment(ref _dropped); // Log the first drop and then every thousandth — a flood must not turn into a log flood. if (dropped == 1 || dropped % 1000 == 0) _logger.LogWarning( "Admin audit queue is saturated — {Dropped} event(s) dropped. " + "The audit backend cannot keep up with the request rate.", dropped); } /// Maps an event onto the headers the writer route binds its parameters from. internal static IMessage BuildMessage(AdminAuditEvent @event) { var msg = new Message { // Body is the sanitized argument JSON; the payload column is nullable, but an // empty object keeps the column shape uniform for consumers. Body = string.IsNullOrWhiteSpace(@event.Payload) ? "{}" : @event.Payload }; msg.Headers[AuditHeaders.EventId] = Guid.NewGuid().ToString(); // Round-trip format ("o"): ISO-8601 with offset — accepted verbatim by all three // providers and lexicographically sortable in the SQLite TEXT column. msg.Headers[AuditHeaders.Timestamp] = @event.Timestamp.ToString("o", CultureInfo.InvariantCulture); msg.Headers[AuditHeaders.Action] = @event.Action; msg.Headers[AuditHeaders.ControllerType] = @event.ControllerType; msg.Headers[AuditHeaders.ActorPrincipal] = @event.ActorPrincipalName; msg.Headers[AuditHeaders.ActorKeyId] = @event.ActorApiKeyId; msg.Headers[AuditHeaders.RemoteIp] = @event.RemoteIp; msg.Headers[AuditHeaders.UserAgent] = Truncate(@event.UserAgent, 500); msg.Headers[AuditHeaders.HttpMethod] = @event.HttpMethod; msg.Headers[AuditHeaders.RequestPath] = Truncate(@event.RequestPath, 500); msg.Headers[AuditHeaders.TargetResource] = Truncate(@event.TargetResource, 300); msg.Headers[AuditHeaders.StatusCode] = @event.StatusCode; msg.Headers[AuditHeaders.DurationMs] = @event.DurationMs; msg.Headers[AuditHeaders.ExceptionType] = @event.ExceptionType; msg.Headers[AuditHeaders.ExceptionMessage] = Truncate(@event.ExceptionMessage, 2000); return msg; } /// Keeps values inside the declared column widths — an over-long User-Agent /// must not turn into a failed INSERT and a lost audit record. private static string? Truncate(string? value, int max) => value is null || value.Length <= max ? value : value[..max]; public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; _queue.Writer.TryComplete(); try { // Give the pump a moment to drain what is already queued. if (_pump is not null) await _pump.WaitAsync(TimeSpan.FromSeconds(5)); } catch (Exception ex) { _logger.LogDebug(ex, "Admin audit pump did not drain cleanly on shutdown"); } await _shutdown.CancelAsync(); _shutdown.Dispose(); try { if (_producer is { IsStarted: true }) _producer.Stop(); } catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop the admin audit ProducerTemplate"); } } } Path: redb-tsak/src/redb.Tsak.Core/Services/ConfigMergeHelper.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/Services/ConfigMergeHelper.cs ---- namespace redb.Tsak.Core.Services; /// /// Deep-merges configuration dictionaries. Source wins on leaf conflicts. /// Nested dictionaries are merged recursively. /// internal static class ConfigMergeHelper { /// /// Merges into in-place. /// For conflicting leaf keys, source value wins. /// For nested dictionaries, values merge recursively. /// public static void DeepMerge(IDictionary target, IDictionary source) { foreach (var (key, sourceValue) in source) { if (sourceValue is IDictionary sourceDict && target.TryGetValue(key, out var existing) && existing is IDictionary targetDict) { // Both sides are nested dicts — recurse DeepMerge(targetDict, sourceDict); } else { // Leaf or type mismatch — source wins target[key] = sourceValue; } } } } Path: redb-tsak/src/redb.Tsak.Core/Services/ContextInfoCollector.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/Services/ContextInfoCollector.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Models; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services; /// /// Collects rich context/route/endpoint info from live RouteContext instances. /// Uses for per-endpoint telemetry and /// for route metadata. /// Called from heartbeat (every 15s) and on-demand by API controllers. /// public class ContextInfoCollector { private readonly ITsakContextManager _contextManager; public ContextInfoCollector(ITsakContextManager contextManager) { _contextManager = contextManager; } /// Collect info for all contexts. public IReadOnlyList CollectAll() { var contexts = _contextManager.GetAllContexts(); var result = new List(contexts.Count); foreach (var (name, ctx) in contexts) result.Add(BuildContextDetail(name, ctx)); return result; } /// Collect info for a single context. public ContextDetail? Collect(string contextName) { var ctx = _contextManager.GetContext(contextName); return ctx is null ? null : BuildContextDetail(contextName, ctx); } /// Collect detailed info for a single route within a context. public RouteDetail? CollectRoute(string contextName, string routeId) { var ctx = _contextManager.GetContext(contextName) as RouteContext; if (ctx is null) return null; var route = ctx.GetRoute(routeId); if (route is null) return null; var inflight = ctx.InflightRepository; var endpoints = ctx.GetEndpoints(); var consumerKey = route.Endpoint.Uri.NormalizedKey; // Collect endpoints associated with this route var routeEndpoints = endpoints .Where(ep => ep.Uri.NormalizedKey.Equals(consumerKey, StringComparison.OrdinalIgnoreCase)) .Select(ep => BuildEndpointInfo(ep, isConsumer: true)) .ToArray(); return new RouteDetail { RouteId = route.RouteId, FromUri = route.Endpoint.Uri.ToMaskedUriString(), Status = route.Status.ToString(), AutoStart = route.AutoStart, InflightCount = inflight.CountByRoute(route.RouteId), Endpoints = routeEndpoints, PolicyMetadata = route.Policy?.GetMetadata() }; } /// Browse in-flight exchanges for a specific route in a context. public IReadOnlyList? BrowseInflight(string contextName, string? routeId = null) { var ctx = _contextManager.GetContext(contextName) as RouteContext; if (ctx is null) return null; var entries = routeId is not null ? ctx.InflightRepository.Browse(routeId) : ctx.InflightRepository.Browse(); var now = DateTime.UtcNow; return entries.Select(e => new InflightExchangeDto { ExchangeId = e.ExchangeId, RouteId = e.RouteId, StartedAt = e.StartedAt, ElapsedMs = (now - e.StartedAt).TotalMilliseconds, ThreadId = e.ManagedThreadId, FromEndpoint = e.FromEndpoint }).ToArray(); } /// Collect redb-compatible snapshots for heartbeat propagation. Async so the periodic /// heartbeat path never blocks a pool thread on the store-backed auto-start read (review item 3.8). public async Task> CollectSnapshotsAsync() { var contexts = _contextManager.GetAllContexts(); var result = new Dictionary(contexts.Count, StringComparer.OrdinalIgnoreCase); foreach (var (name, ctx) in contexts) result[name] = await BuildSnapshotAsync(name, ctx).ConfigureAwait(false); return result; } private async Task BuildSnapshotAsync(string name, IRouteContext ctx) { var endpoints = ctx.GetEndpoints(); var components = ctx.GetComponentNames(); var routes = (ctx as RouteContext)?.Routes ?? []; var consumerKeys = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var route in routes) consumerKeys.Add(route.Endpoint.Uri.NormalizedKey); var routeSnapshots = new Dictionary(routes.Count, StringComparer.OrdinalIgnoreCase); foreach (var r in routes) { routeSnapshots[r.RouteId] = new TsakRouteSnapshot { RouteId = r.RouteId, FromUri = r.Endpoint.Uri.ToMaskedUriString(), Status = r.Status.ToString(), AutoStart = r.AutoStart }; } var endpointSnapshots = new Dictionary(endpoints.Count, StringComparer.OrdinalIgnoreCase); foreach (var ep in endpoints) { var isConsumer = consumerKeys.Contains(ep.Uri.NormalizedKey); var stats = ep as IEndpointStatistics; endpointSnapshots[ep.Uri.NormalizedKey] = new TsakEndpointSnapshot { Uri = ep.Uri.ToMaskedUriString(), Scheme = ep.Uri.Scheme, IsConsumer = isConsumer, IsProducer = !isConsumer, MessagesIn = stats?.MessagesIn ?? 0, MessagesOut = stats?.MessagesOut ?? 0, Errors = stats?.Errors ?? 0, Warnings = stats?.Warnings ?? 0, BytesIn = stats?.BytesIn ?? 0, ThroughputPerSecond = stats?.ThroughputPerSecond ?? 0, HealthStatus = stats?.HealthStatus.ToString() ?? "Healthy", HealthReason = stats?.HealthReason, LastActivity = stats?.LastActivity is { } la ? new DateTimeOffset(la, TimeSpan.Zero) : null, StartedAt = stats != null ? new DateTimeOffset(stats.StartTime, TimeSpan.Zero) : null, UptimeSeconds = stats?.Uptime.TotalSeconds ?? 0, AverageProcessingTimeMs = stats?.AverageProcessingTime.TotalMilliseconds ?? 0, LastErrorMessage = stats?.LastErrorMessage is { Length: > 0 } msg ? msg : null, LastErrorTime = stats?.LastErrorTime is { } let ? new DateTimeOffset(let, TimeSpan.Zero) : null, LastWarningMessage = stats?.LastWarningMessage is { Length: > 0 } wmsg ? wmsg : null, LastWarningTime = stats?.LastWarningTime is { } lwt ? new DateTimeOffset(lwt, TimeSpan.Zero) : null, }; } return new TsakContextInfo { ContextName = name, Status = ctx.IsStarted ? "Running" : "Stopped", IsAnonymous = name.Contains("_dyn_", StringComparison.Ordinal), AutoStart = await _contextManager.ShouldAutoStartAsync(name).ConfigureAwait(false), StartedAt = ctx.IsStarted ? DateTimeOffset.UtcNow : null, ModuleNames = [], // filled by caller if needed Components = components.ToArray(), RouteCount = routes.Count, EndpointCount = endpoints.Count, Routes = routeSnapshots, Endpoints = endpointSnapshots }; } private ContextDetail BuildContextDetail(string name, IRouteContext ctx) { var endpoints = ctx.GetEndpoints(); var components = ctx.GetComponentNames(); // Get compiled routes (only available via RouteContext) var routeCtx = ctx as RouteContext; var routes = routeCtx?.Routes ?? []; var inflight = routeCtx?.InflightRepository; // Build set of consumer endpoint keys for role detection var consumerKeys = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var route in routes) consumerKeys.Add(route.Endpoint.Uri.NormalizedKey); var routeInfos = routes.Select(r => new TsakRouteInfo { RouteId = r.RouteId, FromUri = r.Endpoint.Uri.ToMaskedUriString(), Status = r.Status.ToString(), AutoStart = r.AutoStart, InflightCount = inflight?.CountByRoute(r.RouteId) ?? 0, IsCluster = r.Policy?.GetMetadata()?.ContainsKey("cluster") == true, Policy = new RoutePolicyInfo { RequestedCluster = r.PolicyDescriptor.RequestedCluster, EffectivePolicy = r.PolicyDescriptor.EffectivePolicy, PolicyFactoryType = r.PolicyDescriptor.PolicyFactoryType, Reason = r.PolicyDescriptor.Reason } }).ToArray(); var endpointInfos = endpoints.Select(ep => { var isConsumer = consumerKeys.Contains(ep.Uri.NormalizedKey); return BuildEndpointInfo(ep, isConsumer); }).ToArray(); return new ContextDetail { Name = name, Status = ctx.IsStarted ? "Running" : "Stopped", EndpointCount = endpoints.Count, AutoStart = _contextManager.ShouldAutoStart(name), IsAnonymous = name.Contains("_dyn_", StringComparison.Ordinal), Components = components.ToArray(), Routes = routeInfos, Endpoints = endpointInfos, StartedAt = ctx.IsStarted ? DateTimeOffset.UtcNow : null, // approximate; enriched by heartbeat tracker }; } private static TsakEndpointInfo BuildEndpointInfo(IEndpoint ep, bool isConsumer) { var stats = ep as IEndpointStatistics; return new TsakEndpointInfo { Uri = ep.Uri.ToMaskedUriString(), Scheme = ep.Uri.Scheme, IsConsumer = isConsumer, IsProducer = !isConsumer, MessagesIn = stats?.MessagesIn ?? 0, MessagesOut = stats?.MessagesOut ?? 0, Errors = stats?.Errors ?? 0, Warnings = stats?.Warnings ?? 0, BytesIn = stats?.BytesIn ?? 0, BytesOut = stats?.BytesOut ?? 0, Rejected = stats?.Rejected ?? 0, Refused = stats?.Refused ?? 0, LastRefusalTime = stats?.LastRefusalTime is { } lrt ? new DateTimeOffset(lrt, TimeSpan.Zero) : null, LastRefusalMessage = stats?.LastRefusalMessage is { Length: > 0 } rmsg ? rmsg : null, ThroughputPerSecond = stats?.ThroughputPerSecond ?? 0, HealthStatus = stats?.HealthStatus.ToString() ?? "Healthy", HealthReason = stats?.HealthReason, LastActivity = stats?.LastActivity is { } la ? new DateTimeOffset(la, TimeSpan.Zero) : null, StartedAt = stats != null ? new DateTimeOffset(stats.StartTime, TimeSpan.Zero) : null, Uptime = stats?.Uptime ?? TimeSpan.Zero, AverageProcessingTime = stats?.AverageProcessingTime ?? TimeSpan.Zero, LastErrorMessage = stats?.LastErrorMessage is { Length: > 0 } msg ? msg : null, LastErrorTime = stats?.LastErrorTime is { } let ? new DateTimeOffset(let, TimeSpan.Zero) : null, LastWarningMessage = stats?.LastWarningMessage is { Length: > 0 } wmsg ? wmsg : null, LastWarningTime = stats?.LastWarningTime is { } lwt ? new DateTimeOffset(lwt, TimeSpan.Zero) : null, }; } /// Builds a per-route metrics summary from the route's consumer endpoint stats. public RouteMetricsSummary? CollectRouteMetrics(string contextName, string routeId) { var ctx = _contextManager.GetContext(contextName) as RouteContext; if (ctx is null) return null; var route = ctx.GetRoute(routeId); if (route is null) return null; return BuildRouteMetrics(contextName, ctx, route); } /// Collects per-route metrics for all routes across all contexts. public IReadOnlyList CollectAllRouteMetrics() { var result = new List(); foreach (var (name, context) in _contextManager.GetAllContexts()) { if (context is not RouteContext ctx) continue; foreach (var route in ctx.Routes) result.Add(BuildRouteMetrics(name, ctx, route)); } return result; } private static RouteMetricsSummary BuildRouteMetrics(string contextName, RouteContext ctx, CompiledRoute route) { var stats = route.Endpoint as IEndpointStatistics; return new RouteMetricsSummary { ContextName = contextName, RouteId = route.RouteId, Status = route.Status.ToString(), InflightCount = ctx.InflightRepository.CountByRoute(route.RouteId), MessagesProcessed = stats?.MessagesIn ?? 0, Errors = stats?.Errors ?? 0, Rejected = stats?.Rejected ?? 0, Refused = stats?.Refused ?? 0, LastRefusalTime = stats?.LastRefusalTime, LastRefusal = stats?.LastRefusalMessage is { Length: > 0 } rmsg ? rmsg : null, Warnings = stats?.Warnings ?? 0, AvgProcessingMs = stats?.AverageProcessingTime.TotalMilliseconds ?? 0, ThroughputPerSecond = stats?.ThroughputPerSecond ?? 0, LastActivity = stats?.LastActivity, LastError = stats?.LastErrorMessage is { Length: > 0 } msg ? msg : null, LastErrorTime = stats?.LastErrorTime, LastWarning = stats?.LastWarningMessage is { Length: > 0 } wmsg ? wmsg : null, LastWarningTime = stats?.LastWarningTime, Uptime = stats?.Uptime is { } u && u > TimeSpan.Zero ? FormatUptime(u) : null }; } private static string FormatUptime(TimeSpan uptime) { if (uptime.TotalDays >= 1) return $"{(int)uptime.TotalDays}d {uptime.Hours}h {uptime.Minutes}m"; if (uptime.TotalHours >= 1) return $"{(int)uptime.TotalHours}h {uptime.Minutes}m"; return $"{uptime.Minutes}m {uptime.Seconds}s"; } } Path: redb-tsak/src/redb.Tsak.Core/Services/ContextSaveInterceptors.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/Services/ContextSaveInterceptors.cs ---- using redb.Core.Interception; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services; /// /// The of one route context: subscriptions to the host's /// that the context manager removes, all of them, with the context. /// internal sealed class ContextSaveInterceptors : ITsakSaveInterceptors, IDisposable { private readonly IRedbSaveInterceptorRegistry _registry; private readonly string _contextName; private readonly object _gate = new(); private readonly List _subscriptions = new(); private bool _disposed; internal ContextSaveInterceptors(IRedbSaveInterceptorRegistry registry, string contextName) { _registry = registry; _contextName = contextName; } /// Subscriptions still in place (for tests and diagnostics). internal int Count { get { lock (_gate) return _subscriptions.Count; } } /// public IDisposable Add(IRedbSaveInterceptor interceptor) { ArgumentNullException.ThrowIfNull(interceptor); lock (_gate) { ObjectDisposedException.ThrowIf(_disposed, $"save interceptors of context '{_contextName}'"); var subscription = new Subscription(this, _registry.Add(interceptor)); _subscriptions.Add(subscription); return subscription; } } /// Removes every interceptor of the context; called when the context is removed. public void Dispose() { Subscription[] subscriptions; lock (_gate) { if (_disposed) return; _disposed = true; subscriptions = _subscriptions.ToArray(); _subscriptions.Clear(); } foreach (var subscription in subscriptions) subscription.Release(); } private void Forget(Subscription subscription) { lock (_gate) _subscriptions.Remove(subscription); } private sealed class Subscription(ContextSaveInterceptors owner, IDisposable registration) : IDisposable { private IDisposable? _registration = registration; // The registry handle drops its reference to the interceptor, and this one drops the handle. internal void Release() => Interlocked.Exchange(ref _registration, null)?.Dispose(); public void Dispose() { Release(); owner.Forget(this); } } } Path: redb-tsak/src/redb.Tsak.Core/Services/DiagnosticService.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/Services/DiagnosticService.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; namespace redb.Tsak.Core.Services; /// /// Collects a comprehensive diagnostic snapshot of the system state. /// Aggregates inflight exchanges, thread pool stats, GC stats, /// per-context summaries, watchdog alerts, and recent lifecycle events. /// public class DiagnosticService { private readonly ITsakContextManager _contextManager; public DiagnosticService(ITsakContextManager contextManager) { _contextManager = contextManager; } /// /// Builds a full system diagnostic dump. /// public DiagnosticDump CollectSystemDump( MetricsService? metricsService = null, RouteWatchdogService? watchdog = null, LifecycleAuditService? auditService = null, Modules.ModuleContextMonitor? moduleContexts = null) { var contexts = _contextManager.GetAllContexts(); var collector = new ContextInfoCollector(_contextManager); // Collect all inflight exchanges across all contexts var allInflight = new List(); var contextSummaries = new List(); foreach (var (name, ctx) in contexts) { var inflight = collector.BrowseInflight(name); if (inflight is not null) allInflight.AddRange(inflight); var routeCtx = ctx as RouteContext; contextSummaries.Add(new DiagnosticContextSummary { ContextName = name, IsStarted = ctx.IsStarted, RouteCount = routeCtx?.Routes.Count ?? 0, EndpointCount = ctx.GetEndpoints().Count, InflightCount = routeCtx?.InflightRepository.Count ?? 0 }); } // Thread pool stats ThreadPool.GetAvailableThreads(out var workerAvail, out var ioAvail); ThreadPool.GetMinThreads(out var workerMin, out var ioMin); ThreadPool.GetMaxThreads(out var workerMax, out var ioMax); var threadPoolInfo = new ThreadPoolDiagnostics { PendingWorkItems = ThreadPool.PendingWorkItemCount, WorkerThreadsAvailable = workerAvail, WorkerThreadsMin = workerMin, WorkerThreadsMax = workerMax, IoThreadsAvailable = ioAvail, IoThreadsMin = ioMin, IoThreadsMax = ioMax }; // GC stats var gcInfo = new GcDiagnostics { Gen0Collections = GC.CollectionCount(0), Gen1Collections = GC.CollectionCount(1), Gen2Collections = GC.CollectionCount(2), TotalMemoryMB = Math.Round(GC.GetTotalMemory(false) / (1024.0 * 1024.0), 2) }; // System metrics from MetricsService if available SystemMetricsSnapshot? sysMetrics = null; var latest = metricsService?.GetLatest(); if (latest is not null) sysMetrics = SystemMetrics(latest, moduleContexts); return new DiagnosticDump { InflightExchanges = allInflight, ThreadPool = threadPoolInfo, GarbageCollector = gcInfo, Contexts = contextSummaries, ActiveAlerts = watchdog?.GetState()?.ActiveAlerts ?? [], RecentEvents = auditService?.GetEvents(limit: 20) ?? [], SystemMetrics = sysMetrics }; } /// The system metrics of the dump and the dashboard: the latest point and the module contexts in memory. internal static SystemMetricsSnapshot SystemMetrics(MetricsPoint latest, Modules.ModuleContextMonitor? moduleContexts) => new() { CpuPercent = latest.Cpu.ProcessUsage, MemoryMB = latest.Memory.WorkingSetMB, ThreadCount = latest.Threading.ActiveThreads, Gen2Collections = latest.GarbageCollector.Gen2Collections, ModuleContextsAlive = moduleContexts?.ModuleContextsAlive ?? 0, OrphanedModuleContexts = moduleContexts?.OrphanedModuleContexts ?? 0, ModuleContextsNotice = moduleContexts?.Notice }; /// /// Builds a diagnostic dump for a single route. /// public RouteDiagnosticDump? CollectRouteDump( string contextName, string routeId, LifecycleAuditService? auditService = null) { var ctx = _contextManager.GetContext(contextName) as RouteContext; if (ctx is null) return null; var route = ctx.GetRoute(routeId); if (route is null) return null; var collector = new ContextInfoCollector(_contextManager); var inflight = collector.BrowseInflight(contextName, routeId) ?? []; var metrics = collector.CollectRouteMetrics(contextName, routeId); var stats = route.Endpoint as IEndpointStatistics; var recentErrors = new List(); if (stats?.LastErrorMessage is { Length: > 0 } msg) recentErrors.Add($"[{stats.LastErrorTime:u}] {msg}"); return new RouteDiagnosticDump { RouteId = route.RouteId, FromUri = route.Endpoint.Uri.ToMaskedUriString(), Status = route.Status.ToString(), AutoStart = route.AutoStart, InflightExchanges = inflight, Metrics = metrics, RecentErrors = recentErrors, LifecycleHistory = auditService?.GetEvents(routeId: routeId, limit: 20) ?? [] }; } } Path: redb-tsak/src/redb.Tsak.Core/Services/HotReloadOptions.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/Services/HotReloadOptions.cs ---- namespace redb.Tsak.Core.Services; /// /// Configuration for hot reload. Bound to Tsak:HotReload. /// public class HotReloadOptions { /// Enable hot reload. Default: true. public bool Enabled { get; set; } = true; /// Filesystem scan interval in seconds. Default: 30. public int ScanIntervalSeconds { get; set; } = 30; /// Number of previous versions to keep for rollback. Default: 2. public int KeepVersions { get; set; } = 2; /// /// RESERVED — not enforced: no code reads this value. A module start is not time-boxed, because the /// coordinator contract takes no CancellationToken. A new /// version that fails to initialize or start IS rolled back — just not on a timeout. Default: 60. /// public int StartupTimeoutSeconds { get; set; } = 60; /// /// RESERVED — sequential cluster rolling updates are NOT implemented yet: no code reads this /// flag and RollingUpdateCoordinator has no callers, so nodes reload modules independently on /// their own scan schedule (review 2026-09-02, С16). Default: false; enabling it only logs a /// warning. Stagger updates yourself by deploying the package to nodes sequentially. /// public bool RollingUpdate { get; set; } = false; /// /// Number of scan cycles to wait before confirming a module removal (DLL deleted from disk). /// Protects against false removals during file replacement (delete + copy). Default: 1. /// With ScanIntervalSeconds=10 and RemovalDebounceScans=1, the effective delay is ~10s. /// public int RemovalDebounceScans { get; set; } = 1; /// /// Number of consecutive scans a newly-seen (or changed) .tpkg must keep the same size and /// last-write time before it is opened/verified. Prevents reading a half-written package while an /// operator is still copying it in (review item 4.11). Default: 2 (one settle cycle). Set to 1 to /// disable the wait. With ScanIntervalSeconds=30 and AdditionStabilityScans=2 the effective wait is /// up to ~30s after the copy stops changing the file. /// public int AdditionStabilityScans { get; set; } = 2; /// /// Use collectible AssemblyLoadContext for module isolation. Default: false. /// When true, old module versions are unloaded from memory on hot-swap, once nothing of the host refers to them: /// the caches of redb.Route keyed by type hold their key weakly, a module's type resolver and prefix resolvers /// live in its context, its save interceptors go with its context, and on unload redb and redb.Route empty the /// caches the .NET libraries keep over the types they handled (System.Text.Json among them, /// https://github.com/dotnet/runtime/issues/65323). A library of the module's own with a static cache of its /// types, or Emit-generated code kept outside the module's context, can still hold it. /// When false (default), old versions stay in memory until the process restarts. /// public bool Collectible { get; set; } = false; /// /// How many module contexts may stay in memory after Tsak let them go before the hotreload health check turns /// Degraded and asks for a restart of the node. Such a context is a replaced or removed version with /// false, or one that did not unload with it true. Default (null): /// + 3. /// public int? MaxOrphanedContexts { get; set; } /// /// A working set (MB) above which GET /api/health/deploy advises a cold deploy instead of a hot swap. Default /// (null): no limit, the advice looks at the module contexts only. /// public double? MaxWorkingSetMb { get; set; } /// The limit in effect: , or + 3 when it is not set. internal int EffectiveMaxOrphanedContexts => MaxOrphanedContexts ?? KeepVersions + 3; /// /// Path to the shared assembly directory. Default: "Libs/shared". /// Assemblies here are loaded into the Default ALC and auto-registered /// as components in all module contexts. /// public string SharedPath { get; set; } = "Libs/shared"; /// /// When true, all contexts are restarted (in dependency order) when a shared /// assembly changes on disk. Default: true. /// public bool RestartContextsOnSharedChange { get; set; } = true; } Path: redb-tsak/src/redb.Tsak.Core/Services/HotReloadService.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/Services/HotReloadService.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Modules; namespace redb.Tsak.Core.Services; /// /// Manages hot reload of module assemblies. /// Monitors configured directories for new DLLs, loads them in collectible ALCs, /// performs graceful swap (stop old → start new), and supports auto-rollback. /// public sealed class HotReloadService : IDisposable { private readonly ITsakModuleRegistry _registry; private readonly ITsakCoordinator _coordinator; private readonly ITsakContextManager _contextManager; private readonly SharedAssemblyLoader _sharedLoader; private readonly HotReloadOptions _options; private readonly ILogger _logger; private readonly string[] _assemblyProbePaths; private readonly bool _collectible; private readonly ModuleContextMonitor _contextMonitor; // Idempotent disposal + coordination with an in-progress scan (review item 4.12): Dispose unloads // ALCs, so a scan running concurrently must finish first (the gate) and a scan starting after // disposal must bail (_disposed). private int _disposed; private readonly SemaphoreSlim _scanGate = new(1, 1); /// /// Module load contexts still in memory after Tsak let them go, in both modes of /// : the same number as . /// public int LeakedAlcCount => _contextMonitor.OrphanedModuleContexts; // DLLs that were scanned and found to contain no ITsakModule — remember last-write time so // we re-scan if the file is replaced with a newer version that might contain a module. private readonly ConcurrentDictionary _ignoredDlls = new(StringComparer.OrdinalIgnoreCase); // module name → (ALC, assembly path, version) private readonly ConcurrentDictionary _loadedModules = new(StringComparer.OrdinalIgnoreCase); // module name → list of previous versions (for rollback), most recent first private readonly ConcurrentDictionary> _previousVersions = new(StringComparer.OrdinalIgnoreCase); // module name → number of consecutive scans where DLL was missing (debounce for file replacement) private readonly ConcurrentDictionary _pendingRemovals = new(StringComparer.OrdinalIgnoreCase); // .tpkg path → (size, mtime, consecutive-stable-scan count) — copy-stability debounce for additions // so a half-written package is not opened mid-copy (review item 4.11). private readonly ConcurrentDictionary _additionStability = new(StringComparer.OrdinalIgnoreCase); // config file path → last known write time (tracks context.json and {Module}.config.json changes) private readonly ConcurrentDictionary _configFileTimestamps = new(StringComparer.OrdinalIgnoreCase); // .tpkg path → list of module names loaded from that package (for atomic package reload/removal) private readonly ConcurrentDictionary> _packageModules = new(StringComparer.OrdinalIgnoreCase); // .tpkg path → package's isolated ALC (entry points live here; companions in Default via Tracker) private readonly ConcurrentDictionary _packageInstances = new(StringComparer.OrdinalIgnoreCase); // bare-DLL full path → REAL module name (InitRoute namespace) — a file whose basename differs // from its module name must still be tracked/removed under the real name (review С24). private readonly ConcurrentDictionary _bareDllNames = new(StringComparer.OrdinalIgnoreCase); public HotReloadService( ITsakModuleRegistry registry, ITsakCoordinator coordinator, ITsakContextManager contextManager, SharedAssemblyLoader sharedLoader, IOptions options, IConfiguration configuration, ILogger logger, Modules.ModuleLoadGate? loadGate = null, ModuleContextMonitor? contextMonitor = null) { _registry = registry; _coordinator = coordinator; _contextManager = contextManager; _sharedLoader = sharedLoader; _options = options.Value; _logger = logger; _assemblyProbePaths = configuration.GetSection("Tsak:Modules:AssemblyPaths").Get() ?? []; _collectible = _options.Collectible; // Load-boundary signature enforcement — one shared gate for every path that loads module // code (startup discovery included), so the public key, not filesystem access, is the // trust anchor (review 2026-09-02, К3). The optional parameter keeps plain unit-test // construction working; DI always provides the gate. _loadGate = loadGate ?? new Modules.ModuleLoadGate(configuration, Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance.CreateLogger()); // The optional parameter keeps plain unit-test construction working; DI provides the node's monitor. _contextMonitor = contextMonitor ?? new ModuleContextMonitor(_options, logger, TimeSpan.FromMilliseconds(100)); if (!_collectible) { _logger.LogInformation( "HotReload: Collectible=false (default). A replaced or removed module version stays in memory until the " + "process restarts; the hotreload health check turns Degraded above {Limit} of them. " + "Tsak:HotReload:Collectible=true unloads old versions once nothing outside the module refers to them", _contextMonitor.MaxOrphanedContexts); } else { _logger.LogInformation( "HotReload: Collectible=true. Replaced module versions are unloaded; one still in memory after {Collections} " + "collections is logged and counted, and the hotreload health check turns Degraded above {Limit} of them", ModuleContextMonitor.Collections, _contextMonitor.MaxOrphanedContexts); } } private readonly Modules.ModuleLoadGate _loadGate; /// /// Staged validation: opens the package (from the caller's VERIFIED bytes) in a throwaway /// collectible ALC and checks it loads and discovers at least one module — companion DLLs stay /// inside that throwaway ALC (isolatedCompanions), so a rejected package leaks nothing /// into the process-wide tracker (review 2026-09-02, С23). The throwaway ALC is unloaded /// afterwards. Returns false (with a reason) when the package is unopenable or module-less. /// internal bool ValidatePackageLoads(byte[] packageBytes, string tpkgPath, out string error) { error = ""; Modules.ModulePackage? probe = null; try { probe = Modules.ModulePackage.Open(packageBytes, tpkgPath, File.GetLastWriteTimeUtc(tpkgPath), probePaths: _assemblyProbePaths, logger: _logger, forceReload: false, collectible: true, isolatedCompanions: true); if (probe is null) { error = "package could not be opened (invalid ZIP, missing/invalid manifest, or unnamed)"; return false; } // Third convention (Route-XML Ф5.2): XML artifacts count as a module, so an XML-only // package (no entry points) passes. Well-formedness is the cheap staged check that // needs no RouteContext — a truncated or hand-broken artifact is refused here, before // the live version is torn down; schema/compile errors stay load-time module-isolated // faults per the owner's fail-fast decision. var xmlModules = 0; if (probe.Manifest.Artifacts.Count > 0) { foreach (var (name, content) in probe.XmlArtifacts) { try { System.Xml.Linq.XDocument.Parse(content); } catch (System.Xml.XmlException ex) { error = $"XML artifact {name} is not well-formed: {ex.Message}"; return false; } } xmlModules = 1; } if (probe.LoadedAssemblies.Count == 0 && xmlModules == 0) { error = "no entry-point assemblies loaded"; return false; } var found = xmlModules; foreach (var assembly in probe.LoadedAssemblies) { try { found += TsakModuleRegistry.DiscoverModulesInAssembly(assembly).Count; } catch (Exception ex) { error = $"module discovery threw: {ex.Message}"; return false; } } if (found == 0) { error = "no modules discovered in the package"; return false; } return true; } catch (Exception ex) { error = ex.Message; return false; } finally { // Unload the throwaway ALC — it was created collectible for exactly this. probe?.Dispose(); } } /// /// Scans the given directories for updated module DLLs and hot-swaps any that have newer versions. /// public async Task ScanAndReloadAsync(IEnumerable paths, CancellationToken ct = default) { if (Volatile.Read(ref _disposed) == 1) return 0; // Serialize scans and coordinate with Dispose: a scan holds the gate for its whole run, so // Dispose (which also takes the gate) can never unload an ALC out from under a live scan (4.12). await _scanGate.WaitAsync(ct).ConfigureAwait(false); try { if (Volatile.Read(ref _disposed) == 1) return 0; return await ScanAndReloadCoreAsync(paths, ct).ConfigureAwait(false); } finally { _scanGate.Release(); // Every swap, reload and removal of the scan let its old contexts go by now: check they leave memory. _contextMonitor.ScheduleCheck(); } } private async Task ScanAndReloadCoreAsync(IEnumerable paths, CancellationToken ct = default) { var reloaded = 0; // Shared-layer change: shared assemblies live in the non-collectible Default ALC and // CANNOT be swapped in-process — the old "reload + restart all contexts" re-served the // already-tracked instances, draining and rebuilding every context on the SAME old bytes // while the log claimed a completed reload (review 2026-09-02, С22). Report once per // change and require a process restart; no pointless context churn. if (_options.RestartContextsOnSharedChange && _sharedLoader.DetectChanges()) { _logger.LogCritical( "Shared assembly change detected on disk. Shared DLLs load into the non-unloadable Default ALC " + "and cannot be swapped in-process — restart the worker process to pick up the new bytes. " + "Contexts are NOT being restarted: that would drain them onto the same old code."); _sharedLoader.AcknowledgeChanges(); } var packageScanPaths = new List(); foreach (var path in paths) { if (!Directory.Exists(path)) continue; _logger.LogDebug("Hot-reload scan: {Path}", path); packageScanPaths.Add(path); foreach (var dll in Directory.GetFiles(path, "*.dll")) { // Trust gate (review 2026-09-02, К3): with signature enforcement on, a bare DLL // cannot carry a signature — hot-reload must not load what discovery refuses. if (!_loadGate.AllowBareDll(dll)) continue; try { var newVersion = GetAssemblyVersion(dll); // The REAL module name (InitRoute namespace) can differ from the file basename; // keying trackers by basename made removal unregister the wrong key while // unloading the live ALC — a ghost module (review 2026-09-02, С24). Once a DLL // has been discovered, address it by its real name. var moduleName = _bareDllNames.TryGetValue(Path.GetFullPath(dll), out var knownName) ? knownName : Path.GetFileNameWithoutExtension(dll); // Skip DLLs previously identified as non-module dependencies (unless file changed) if (_ignoredDlls.TryGetValue(dll, out var ignoredAt) && File.GetLastWriteTimeUtc(dll) <= ignoredAt) continue; // Check if we have this module loaded with an older version if (_loadedModules.TryGetValue(moduleName, out var current)) { if (!ModuleVersion.IsNewer(newVersion, current.Version)) continue; _logger.LogInformation("New version detected for {Module}: {Old} → {New}", moduleName, current.Version, newVersion); var success = await HotSwapAsync(moduleName, dll, newVersion, ct).ConfigureAwait(false); if (success) reloaded++; } else { // Module not tracked by hot reload yet var existingModule = _registry.GetModule(moduleName); if (existingModule is not null) { // Already in registry (loaded at startup) — track with current file timestamp // so the next scan compares apples-to-apples _loadedModules[moduleName] = new LoadedModuleInfo(null, dll, newVersion); } else { // Potential new module — load into its OWN isolated ALC only. Do NOT also // byte-load it into the Default ALC (review item 3.7b): that produced a // second, distinct copy of the module's types in Default while the module // actually runs as the ALC copy — a type-identity split-brain and a leak. // A module's own assembly is not a shared dependency; cross-module shared // types belong in the shared layer (which IS tracked). var fullDll = Path.GetFullPath(dll); var newAlc = new ModuleAssemblyLoadContext(moduleName, _assemblyProbePaths, _collectible); ITsakModule? newModule; try { var assembly = newAlc.LoadFromBytes(fullDll); var sourceDir = Path.GetDirectoryName(fullDll); newModule = TsakModuleRegistry.DiscoverModulesInAssembly(assembly, sourceDir).FirstOrDefault(); } catch (Exception ex) { // A file Tsak cannot use: an InitRoute.main of an unsupported shape, a type that // fails to load, a half-copied image. Said once, then ignored until the file // changes. The throw used to skip both the ignore mark and the unload, so every // scan loaded the file into one more permanent ALC and logged the same error. _logger.LogError(ex, "Module file {Path} cannot be used and is ignored until it changes", dll); IgnoreUntilChanged(dll); newAlc.TryUnload(); continue; } if (newModule is not null) { _bareDllNames[fullDll] = newModule.ModuleName; var alreadyRegistered = _registry.GetModule(newModule.ModuleName); if (alreadyRegistered is not null) { // Registered at startup under its REAL name (≠ basename) — // adopt tracking under that name instead of registering a // duplicate second copy (review 2026-09-02, С24). newAlc.TryUnload(); _loadedModules.TryAdd(newModule.ModuleName, new LoadedModuleInfo(null, dll, newVersion)); } else { _logger.LogInformation("New module discovered: {Module} v{Version}", newModule.ModuleName, newVersion); await _registry.RegisterModuleAsync(newModule); _loadedModules[newModule.ModuleName] = new LoadedModuleInfo(newAlc, dll, newVersion); reloaded++; } } else { _logger.LogDebug("No ITsakModule found in {Path}, skipping", dll); _ignoredDlls[dll] = File.GetLastWriteTimeUtc(dll); newAlc.TryUnload(); } } } } catch (Exception ex) { _logger.LogError(ex, "Error scanning {Path}", dll); } } } // .tpkg packages (CAR-style hot deploy) — atomic package-level reload. Every changed package // across all scan paths is gathered first and reloaded in Manifest.Dependencies order, carrier // before dependents, and a reloaded carrier drags its dependents along — see // ReloadPackagesInDependencyOrderAsync. Scanning the directory in filesystem order // (Directory.GetFiles does not sort) made the outcome depend on the order the file system // happened to return, so a dependent could come up on the carrier's old shared types. reloaded += await ReloadPackagesInDependencyOrderAsync(packageScanPaths, ct).ConfigureAwait(false); // Detect modules whose DLLs have been removed from disk var removed = await DetectRemovedModulesAsync(paths, ct).ConfigureAwait(false); reloaded += removed; // Detect config file changes (context.json, {Module}.config.json) — trigger context recreation var configReloads = await DetectConfigFileChangesAsync(ct).ConfigureAwait(false); reloaded += configReloads; return reloaded; } /// /// A .tpkg this scan pass must (re)load, with the manifest data needed to order it against the /// others. is empty for a first-time load and non-empty for a reload; /// marks a package pulled in because another reload replaced the shared /// companion DLLs it binds to. /// private sealed record PackageCandidate( string Path, byte[] Bytes, DateTime LastWriteUtc, List OldModuleNames, ModuleManifest Manifest, bool IsCascade); /// /// Collects every changed .tpkg across the scan paths, expands the set with the packages that depend /// on the reloaded ones, orders the whole set by and only /// then reloads, carrier before dependent. The package scan reads the directory in filesystem order /// (Directory.GetFiles does not sort), so a carrier and its dependent replaced together were /// reloaded in whatever order the file system returned — the dependent could come up on the old /// types. At start TsakCoordinator orders the contexts by the same manifest Dependencies (a /// package name stands for the contexts of its modules), together with the Dependencies configured /// for the contexts. /// private async Task ReloadPackagesInDependencyOrderAsync(IReadOnlyList paths, CancellationToken ct) { var candidates = new List(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); // Phase 1 — direct changes on disk, through the same gates the per-file scan applied. foreach (var path in paths) { foreach (var tpkg in Directory.GetFiles(path, "*.tpkg")) { try { var tpkgInfo = new FileInfo(tpkg); var lastWrite = tpkgInfo.LastWriteTimeUtc; // Skip if unchanged since the last SUCCESSFUL process (4.11). if (_ignoredDlls.TryGetValue(tpkg, out var trackedWrite) && lastWrite <= trackedWrite) { _additionStability.TryRemove(tpkg, out _); continue; } // Copy-stability debounce (4.11): never read a half-written ZIP. if (!IsPackageStableForLoad(tpkg, tpkgInfo.Length, lastWrite)) continue; // Load-boundary trust gate (review 2026-09-02, К3): the verified bytes are the loaded bytes. var verifiedBytes = _loadGate.ReadVerifiedTpkg(tpkg); if (verifiedBytes is null) continue; var manifest = ModulePackage.TryReadManifest(verifiedBytes) ?? new ModuleManifest(); var oldModuleNames = _packageModules.TryGetValue(tpkg, out var names) ? names : []; candidates.Add(new PackageCandidate(tpkg, verifiedBytes, lastWrite, oldModuleNames, manifest, IsCascade: false)); seen.Add(FullPathKey(tpkg)); } catch (Exception ex) { _logger.LogError(ex, "Error scanning package {Path}", tpkg); } } } // Phase 2 — pull in the packages that depend on a reloaded carrier. CollectDependentPackages(candidates, seen); // Phase 3 — carrier before dependent. var ordered = OrderPackagesByDependencies(candidates); // Phase 4 — (re)load in that order. var reloaded = 0; foreach (var candidate in ordered) { try { reloaded += candidate.OldModuleNames.Count > 0 ? await ReloadPackageAsync(candidate.Path, candidate.Bytes, candidate.OldModuleNames, ct).ConfigureAwait(false) : await LoadNewPackageAsync(candidate.Path, candidate.Bytes, candidate.LastWriteUtc).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error reloading package {Path}", candidate.Path); } } return reloaded; } /// /// Adds, transitively, every loaded package whose names a /// package being reloaded that ships companion DLLs. A reload force-replaces those companions in /// , and a dependent keeps the old assembly identity in its /// already-loaded code, so its context must be recreated as well. This is the rule /// redb.Identity.Contracts.Module records in prose ("reloading this package must be followed /// by reloading every module that uses them") — enforced by TSAK instead of left to the deploy. /// private void CollectDependentPackages(List candidates, HashSet seen) { var carriers = new Queue(); foreach (var candidate in candidates) { if (ShipsCompanions(candidate.Path)) carriers.Enqueue(candidate.Manifest.Name); } var handled = new HashSet(StringComparer.OrdinalIgnoreCase); while (carriers.Count > 0) { var carrierName = carriers.Dequeue(); if (string.IsNullOrWhiteSpace(carrierName) || !handled.Add(carrierName)) continue; foreach (var (path, package) in _packageInstances) { if (!package.Manifest.Dependencies.Any(d => string.Equals(d, carrierName, StringComparison.OrdinalIgnoreCase))) continue; if (!seen.Add(FullPathKey(path))) continue; // already a candidate this pass var bytes = _loadGate.ReadVerifiedTpkg(path); if (bytes is null) { _logger.LogWarning( "Package {Pkg} depends on reloaded {Carrier}, whose shared companions were replaced, " + "but it could not be re-verified — it keeps running against the old types until its own reload", Path.GetFileName(path), carrierName); continue; } var oldModuleNames = _packageModules.TryGetValue(path, out var names) ? names : []; candidates.Add(new PackageCandidate(path, bytes, package.LastWriteUtc, oldModuleNames, package.Manifest, IsCascade: true)); _logger.LogInformation( "Package {Pkg} depends on reloaded {Carrier} — reloading it too so its types rebind to the replaced companions", Path.GetFileName(path), carrierName); if (ShipsCompanions(path)) carriers.Enqueue(package.Manifest.Name); } } } /// /// Orders packages so that every dependency is reloaded before the packages that declare it. Only /// edges between two packages in the same pass are honoured — a dependency outside the set is /// already running and is left alone (the same rule the coordinator's context sort uses). A cycle /// is logged and the remaining packages keep their scan order rather than being dropped. /// private List OrderPackagesByDependencies(List candidates) { var ordered = Modules.PackageDependencyOrder.Sort(candidates, c => c.Path, c => c.Manifest, out var cyclic); if (cyclic.Count > 0) { _logger.LogError( "Cyclic Manifest.Dependencies among hot-reloaded packages: {Packages}. Reloading them in scan order.", string.Join(", ", cyclic.Select(c => c.Manifest.Name))); } return ordered; } /// Whether the package's loaded instance ships shared (companion) DLLs a reload would force-replace. private bool ShipsCompanions(string tpkgPath) => _packageInstances.TryGetValue(tpkgPath, out var package) && package.CompanionAssemblies.Count > 0; private static string FullPathKey(string path) { try { return Path.GetFullPath(path); } catch { return path; } } /// /// First-time load of a package found in a running worker. Opens the package in its own ALC, /// registers every discovered module (skipping ones already in the registry, loaded at startup) and /// records the tracked write time only after a successful open. Returns the number of newly /// registered modules. The startup discovery has its own path in TsakModuleRegistry. /// private async Task LoadNewPackageAsync(string tpkg, byte[] verifiedBytes, DateTime lastWrite) { var package = ModulePackage.Open(verifiedBytes, tpkg, lastWrite, probePaths: _assemblyProbePaths, logger: _logger, collectible: _collectible); if (package is null) return 0; // corrupt/partial — do NOT record; retry next scan var reloaded = 0; var newModuleNames = new List(); // Discover every entry point before registering any: a package whose entry point Tsak cannot use // (an InitRoute.main of an unsupported shape) is refused whole, said once, and ignored until the // file changes. The throw used to leave the package's ALC and its extracted files behind and // re-open it on every scan. var discovered = new List(); try { var packageSourceDir = Path.GetDirectoryName(Path.GetFullPath(tpkg)); foreach (var assembly in package.LoadedAssemblies) discovered.AddRange(TsakModuleRegistry.DiscoverModulesInAssembly(assembly, packageSourceDir)); } catch (Exception ex) { _logger.LogError(ex, "Package {Path} cannot be used and is ignored until it changes", tpkg); package.Dispose(); _ignoredDlls[tpkg] = lastWrite; _additionStability.TryRemove(tpkg, out _); return 0; } foreach (var module in discovered) { if (module is Modules.StaticMethodModule smm) smm.AttachPackage(package); var existingModule = _registry.GetModule(module.ModuleName); if (existingModule is not null) { // Already in registry (loaded at startup discovery) — just track it _loadedModules[module.ModuleName] = new LoadedModuleInfo(package.Alc, tpkg, module.Version); newModuleNames.Add(module.ModuleName); continue; } _logger.LogInformation("New module {Module} from package {Pkg}", module.ModuleName, package.Manifest.Name); await _registry.RegisterModuleAsync(module); _loadedModules[module.ModuleName] = new LoadedModuleInfo(package.Alc, tpkg, module.Version); newModuleNames.Add(module.ModuleName); reloaded++; } // Third convention (Route-XML Ф5.2): XML artifacts from the manifest — the same block the startup // discovery runs. Without it an XML-only package dropped into a RUNNING worker was opened, found // module-less, disposed and ignored (такт 5 E2E find). if (package.Manifest.Artifacts.Count > 0) { var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tpkg)); var xmlModule = new Modules.XmlRouteModule(package, sourceDir, package.ReadModuleConfigJson(package.Manifest.Name), _logger); if (_registry.GetModule(xmlModule.ModuleName) is not null) { // Already in registry (loaded at startup discovery) — just track it _loadedModules[xmlModule.ModuleName] = new LoadedModuleInfo(package.Alc, tpkg, xmlModule.Version); newModuleNames.Add(xmlModule.ModuleName); } else { _logger.LogInformation("New XML route module {Module} from package {Pkg}", xmlModule.ModuleName, package.Manifest.Name); await _registry.RegisterModuleAsync(xmlModule); _loadedModules[xmlModule.ModuleName] = new LoadedModuleInfo(package.Alc, tpkg, xmlModule.Version); newModuleNames.Add(xmlModule.ModuleName); reloaded++; } } if (newModuleNames.Count > 0) { _packageModules[tpkg] = newModuleNames; _packageInstances[tpkg] = package; } else { // No modules found — dispose the ALC package.Dispose(); } // Opened & verified successfully — NOW record the tracked time (4.11), so an earlier mid-copy // failure did not permanently skip this package. (A package with no modules still opened cleanly // and should not be re-opened every scan.) _ignoredDlls[tpkg] = lastWrite; _additionStability.TryRemove(tpkg, out _); return reloaded; } /// /// Copy-stability debounce for a newly-seen / changed .tpkg (review item 4.11): returns true /// only once the file's size and last-write time have held steady for /// consecutive scans, so a half-written package /// is never opened mid-copy. Any change to size or mtime resets the streak. /// internal bool IsPackageStableForLoad(string path, long size, DateTime mtime) { var threshold = Math.Max(1, _options.AdditionStabilityScans); var cur = _additionStability.AddOrUpdate( path, _ => (size, mtime, 1), (_, prev) => prev.Size == size && prev.Mtime == mtime ? (prev.Size, prev.Mtime, prev.Streak + 1) : (size, mtime, 1)); if (cur.Streak < threshold) { _logger.LogDebug( "Package {Pkg} still settling (stable scan {Count}/{Threshold}) — waiting for the copy to finish", Path.GetFileName(path), cur.Streak, threshold); return false; } return true; } /// /// Detects changes to module config files (context.json, {Module}.config.json). /// When a config file changes, triggers context recreation via ProcessModuleUpdatedAsync. /// private async Task DetectConfigFileChangesAsync(CancellationToken ct) { var reloaded = 0; foreach (var (moduleName, info) in _loadedModules.ToArray()) { var module = _registry.GetModule(moduleName); if (module?.SourceDirectory is not { Length: > 0 } sourceDir || !Directory.Exists(sourceDir)) continue; var configFiles = new[] { Path.Combine(sourceDir, "context.json"), Path.Combine(sourceDir, $"{moduleName}.config.json") }; var changed = false; foreach (var configFile in configFiles) { if (!File.Exists(configFile)) continue; var lastWrite = File.GetLastWriteTimeUtc(configFile); var fullPath = Path.GetFullPath(configFile); if (_configFileTimestamps.TryGetValue(fullPath, out var tracked)) { if (lastWrite > tracked) { _logger.LogInformation("Config file changed: {File}", configFile); _configFileTimestamps[fullPath] = lastWrite; changed = true; } } else { // First time seeing this file — just track it _configFileTimestamps[fullPath] = lastWrite; } } if (changed && module != null) { _logger.LogInformation("Recreating context for module {Module} due to config file change", moduleName); try { await _coordinator.ProcessModuleUpdatedAsync(module).ConfigureAwait(false); reloaded++; } catch (Exception ex) { _logger.LogError(ex, "Failed to recreate context for {Module} after config change", moduleName); } } } return reloaded; } // RestartAllContextsForSharedChangeAsync was removed 2026-09-02 (review С22): shared DLLs // load into the non-unloadable Default ALC, so its "reload" re-served the already-tracked // old instances and the context churn rebuilt everything on the same bytes. A shared change // is now reported once as critical and requires a process restart (see the scan loop). /// /// Detects modules whose DLL/.tpkg files no longer exist on disk. /// For packages: removes ALL modules from the package atomically. /// Uses debounce (RemovalDebounceScans) to avoid false positives during file replacement. /// private async Task DetectRemovedModulesAsync(IEnumerable scanPaths, CancellationToken ct) { // Build set of all module file paths currently on disk (.dll + .tpkg) var existingFiles = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var path in scanPaths) { if (!Directory.Exists(path)) continue; foreach (var dll in Directory.GetFiles(path, "*.dll")) existingFiles.Add(Path.GetFullPath(dll)); foreach (var tpkg in Directory.GetFiles(path, "*.tpkg")) existingFiles.Add(Path.GetFullPath(tpkg)); } // Clean stale _ignoredDlls entries (files that no longer exist) foreach (var ignored in _ignoredDlls.Keys.ToArray()) { if (!existingFiles.Contains(Path.GetFullPath(ignored))) _ignoredDlls.TryRemove(ignored, out _); } // Clean stale copy-stability entries for packages that vanished mid-settle (4.11) foreach (var pending in _additionStability.Keys.ToArray()) { if (!existingFiles.Contains(Path.GetFullPath(pending))) _additionStability.TryRemove(pending, out _); } var removed = 0; var debounceThreshold = Math.Max(1, _options.RemovalDebounceScans); // Detect removed .tpkg packages — unload all modules atomically foreach (var (tpkgPath, moduleNames) in _packageModules.ToArray()) { if (existingFiles.Contains(Path.GetFullPath(tpkgPath))) { _pendingRemovals.TryRemove(tpkgPath, out _); continue; } var count = _pendingRemovals.AddOrUpdate(tpkgPath, 1, (_, c) => c + 1); if (count < debounceThreshold) { _logger.LogDebug("Package {Pkg} missing (scan {Count}/{Threshold}), waiting for debounce", Path.GetFileName(tpkgPath), count, debounceThreshold); continue; } _logger.LogInformation("Package {Pkg} removed from disk — unloading {Count} modules", Path.GetFileName(tpkgPath), moduleNames.Count); foreach (var moduleName in moduleNames) { var success = await UnloadModuleAsync(moduleName, ct).ConfigureAwait(false); if (success) removed++; } _packageModules.TryRemove(tpkgPath, out _); _pendingRemovals.TryRemove(tpkgPath, out _); // Dispose the package ALC (unloads entry points if collectible) if (_packageInstances.TryRemove(tpkgPath, out var oldPkg)) oldPkg.Dispose(); } // Detect removed bare .dll modules foreach (var (moduleName, info) in _loadedModules.ToArray()) { // Skip modules tracked via _packageModules (handled above) if (info.DllPath.EndsWith(".tpkg", StringComparison.OrdinalIgnoreCase)) continue; if (existingFiles.Contains(Path.GetFullPath(info.DllPath))) { _pendingRemovals.TryRemove(moduleName, out _); continue; } var count = _pendingRemovals.AddOrUpdate(moduleName, 1, (_, c) => c + 1); if (count < debounceThreshold) { _logger.LogDebug( "Module {Module} DLL missing (scan {Count}/{Threshold}), waiting for debounce", moduleName, count, debounceThreshold); continue; } _logger.LogInformation( "Module {Module} DLL removed from disk, performing graceful shutdown", moduleName); var success = await UnloadModuleAsync(moduleName, ct).ConfigureAwait(false); if (success) removed++; _pendingRemovals.TryRemove(moduleName, out _); } return removed; } /// /// Gracefully stops a module context, unregisters the module, and cleans up ALC state. /// public async Task UnloadModuleAsync(string moduleName, CancellationToken ct = default) { try { // 1. Graceful shutdown — stops context, closes connections try { await _coordinator.ProcessModuleRemovedAsync(moduleName).ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex, "Error during graceful shutdown of module {Module}", moduleName); } // 2. Unregister from module registry await _registry.UnregisterModuleAsync(moduleName); // 3. Clean up current ALC (skip for package-owned modules — their ALC // is disposed atomically when the package itself is removed) if (_loadedModules.TryRemove(moduleName, out var info)) { var isPackageOwned = info.DllPath.EndsWith(".tpkg", StringComparison.OrdinalIgnoreCase); if (!isPackageOwned) info.Alc?.TryUnload(); } // 4. Clean up archived versions if (_previousVersions.TryRemove(moduleName, out var history)) { lock (history) { foreach (var prev in history) prev.Alc?.TryUnload(); history.Clear(); } } _logger.LogInformation( "Module {Module} unloaded: context stopped, ALC released (Collectible={Collectible})", moduleName, _collectible); return true; } catch (Exception ex) { _logger.LogError(ex, "Failed to unload module {Module}", moduleName); return false; } } /// /// Reloads a .tpkg package in place: the old modules leave the registry silently (no events), the /// new package is opened, its modules are registered silently, and the coordinator recreates their /// contexts as one batch — so persisted context state (e.g. autoStart=false of a named context) /// survives the reload. Unlike UnloadModuleAsync (permanent removal), the module stays. /// /// If a module of the new version does not come up, the previous package is restored (old module /// instances and their contexts back, modules only the new version added stopped) and the file is /// skipped until it changes. A module the new version no longer ships has its context stopped. /// public async Task ReloadPackageAsync(string tpkgPath, List oldModuleNames, CancellationToken ct = default) { // Path-based entry (external callers): route through the trust gate so the verified // bytes are also the loaded bytes (review 2026-09-02, К3). var verified = _loadGate.ReadVerifiedTpkg(tpkgPath); if (verified is null) { _logger.LogWarning("Refusing to reload package {Pkg}: trust gate refused it", Path.GetFileName(tpkgPath)); return 0; } return await ReloadPackageAsync(tpkgPath, verified, oldModuleNames, ct).ConfigureAwait(false); } internal async Task ReloadPackageAsync(string tpkgPath, byte[] packageBytes, List oldModuleNames, CancellationToken ct = default) { _logger.LogInformation("Reloading package {Pkg}: {Count} old modules", Path.GetFileName(tpkgPath), oldModuleNames.Count); // 0. Staged validation BEFORE touching the running version. Load the new package into a // throwaway collectible ALC (companions isolated inside it — a rejected package leaks // nothing into the shared tracker) and verify it opens and discovers at least one module. // Only if that succeeds do we tear the old version down. A broken .tpkg therefore leaves // the live context running instead of destroying it and failing to replace it. if (!ValidatePackageLoads(packageBytes, tpkgPath, out var validationError)) { _logger.LogError( "Refusing to reload package {Pkg}: staged validation failed ({Error}). Keeping the current version.", Path.GetFileName(tpkgPath), validationError); return 0; } // 1. Silently unregister old modules (no events → coordinator keeps context alive, // autoStart state preserved in store). Capture what is needed to put them back first: until // the new version has actually come up, the old one is the rollback target — so the // destructive cleanup (unloading a replaced DLL module's ALC, dropping version history) // waits for step 5. var oldModules = new List<(string Name, ITsakModule? Module, LoadedModuleInfo? Info)>(oldModuleNames.Count); foreach (var moduleName in oldModuleNames) { _loadedModules.TryGetValue(moduleName, out var oldInfo); oldModules.Add((moduleName, _registry.GetModule(moduleName), oldInfo)); _registry.UnregisterModuleSilent(moduleName); } // The old package is disposed AFTER the context swap (step 4), not here: Dispose deletes // the package's extracted resources directory, and until ProcessBatchAsync replaces the // context the OLD routes are still live and may read file= resources from it. TryUnload // is cooperative, so delaying it changes nothing for assemblies (forceReload below already // handles shared-dependency replacement). _packageInstances.TryRemove(tpkgPath, out var oldPackage); // 2. Open new package — forceReload: true ensures shared dependencies get replaced // in the tracker so both modules see the updated Assembly instance. // Each package gets its own ALC for entry point isolation. var package = ModulePackage.Open(packageBytes, tpkgPath, File.GetLastWriteTimeUtc(tpkgPath), probePaths: _assemblyProbePaths, logger: _logger, forceReload: true, collectible: _collectible); if (package is null) { _logger.LogWarning("Failed to open updated package {Pkg}", Path.GetFileName(tpkgPath)); // The old context is still the live one — keep its package tracked and alive, and put its // modules back into the registry (step 1 took them out silently). if (oldPackage is not null) _packageInstances[tpkgPath] = oldPackage; foreach (var (_, oldModule, _) in oldModules) { if (oldModule is not null) await _registry.ReplaceModuleSilentAsync(oldModule); } return 0; } var newModuleNames = new List(); var allNewModules = new List(); var reloaded = 0; // 3. Discover and register modules silently (no events — avoids concurrent // ModuleAdded handlers racing to recreate the same context) foreach (var assembly in package.LoadedAssemblies) { var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tpkgPath)); var modules = TsakModuleRegistry.DiscoverModulesInAssembly(assembly, sourceDir); foreach (var module in modules) { if (module is Modules.StaticMethodModule smm) smm.AttachPackage(package); _logger.LogInformation("Loading module {Module} from package {Pkg}", module.ModuleName, package.Manifest.Name); await _registry.ReplaceModuleSilentAsync(module); _loadedModules[module.ModuleName] = new LoadedModuleInfo(package.Alc, tpkgPath, module.Version); newModuleNames.Add(module.ModuleName); allNewModules.Add(module); reloaded++; } } // Third convention (Route-XML Ф5.2): XML artifacts — same silent-replace flow, so a redrop // of an XML-only package swaps its routes through the batch recreation below. if (package.Manifest.Artifacts.Count > 0) { var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tpkgPath)); var xmlModule = new Modules.XmlRouteModule(package, sourceDir, package.ReadModuleConfigJson(package.Manifest.Name), _logger); _logger.LogInformation("Loading XML route module {Module} from package {Pkg}", xmlModule.ModuleName, package.Manifest.Name); await _registry.ReplaceModuleSilentAsync(xmlModule); _loadedModules[xmlModule.ModuleName] = new LoadedModuleInfo(package.Alc, tpkgPath, xmlModule.Version); newModuleNames.Add(xmlModule.ModuleName); allNewModules.Add(xmlModule); reloaded++; } // 4. Process all modules as a batch — creates each context exactly once // with the full set of modules (no intermediate partial recreations). A module that does not // come up — reported by the coordinator, which swallows Initialize/start exceptions so a bad // module cannot crash the node, or an exception out of the batch itself — restores the // previous package instead of leaving the module down. if (allNewModules.Count > 0) { ModuleActivationFailure? failed = null; Exception? batchException = null; try { var report = await _coordinator.ProcessBatchAsync(allNewModules).ConfigureAwait(false); foreach (var module in allNewModules) { failed = report.FailureFor(module.ModuleName); if (failed is not null) break; } } catch (Exception ex) { batchException = ex; // logged right below, together with the reported case } if (failed is not null || batchException is not null) { _logger.LogError(failed?.Exception ?? batchException, "Package {Pkg}: the new version did not come up (module {Module}); restoring the previous version", Path.GetFileName(tpkgPath), failed?.ModuleName ?? "batch"); await RestorePreviousPackageAsync(tpkgPath, package, oldPackage, oldModules, newModuleNames) .ConfigureAwait(false); return 0; } } // 5. The new version is up — the deferred cleanup of the old one is safe now. var newNames = new HashSet(newModuleNames, StringComparer.OrdinalIgnoreCase); foreach (var (name, _, oldInfo) in oldModules) { // Don't TryUnload individual module ALCs for package modules — the package ALC is // unloaded atomically below. Only a module that moved here from a bare DLL has its own. if (oldInfo?.Alc is not null && oldInfo.DllPath != tpkgPath) oldInfo.Alc.TryUnload(); if (!newNames.Contains(name)) { // A module the new version no longer ships: stop its context BEFORE the old package (and // its extracted resources) is disposed below — it would otherwise keep running on it. await RemoveModuleContextAsync(tpkgPath, name).ConfigureAwait(false); _loadedModules.TryRemove(name, out _); } _previousVersions.TryRemove(name, out _); } // Old package goes away only now — the old context (and its file= resource reads) is gone. oldPackage?.Dispose(); // Update package tracking. Record the tracked write-time only now, after a successful reload // (4.11) — the scan loop no longer records it eagerly, so a failed reload (validation/open // returned 0 above) is retried on the next scan instead of being permanently skipped. _packageModules[tpkgPath] = newModuleNames; _packageInstances[tpkgPath] = package; _ignoredDlls[tpkgPath] = package.LastWriteUtc; _additionStability.TryRemove(tpkgPath, out _); _logger.LogInformation("Package {Pkg} reloaded: {Count} modules", Path.GetFileName(tpkgPath), newModuleNames.Count); return reloaded; } /// /// Stops the context of a module that leaves with a package reload or rollback. A failure is logged, /// not thrown: the reload or rollback must still finish its bookkeeping. /// private async Task RemoveModuleContextAsync(string tpkgPath, string moduleName) { try { await _coordinator.ProcessModuleRemovedAsync(moduleName).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Package {Pkg}: stopping the context of module {Module} failed; it may still be running", Path.GetFileName(tpkgPath), moduleName); } } /// /// Puts the previous version of a package back after its new version failed to come up in /// : the old instances /// return to the registry and their contexts are recreated (a module re-initializes on a fresh /// context, as a named-context recreation always does), a module only the new version added has its /// context stopped, and the new package is disposed only after that. The broken file's write time is /// recorded, so the scan does not re-read the same bytes every interval — the next reload happens /// when the file changes. /// private async Task RestorePreviousPackageAsync(string tpkgPath, ModulePackage newPackage, ModulePackage? oldPackage, List<(string Name, ITsakModule? Module, LoadedModuleInfo? Info)> oldModules, List newModuleNames) { // Old instances back into the registry first: stopping a new-only module below recreates a named // context from the registry, which must already hold the old versions by then. var restorable = new List(oldModules.Count); foreach (var (name, module, info) in oldModules) { if (info is not null) _loadedModules[name] = info; else _loadedModules.TryRemove(name, out _); if (module is null) continue; await _registry.ReplaceModuleSilentAsync(module); restorable.Add(module); } // A module only the NEW version added was already activated by the batch: stop its context before // the new package (its code and resources) is disposed below. var oldNames = new HashSet(oldModules.Select(o => o.Name), StringComparer.OrdinalIgnoreCase); foreach (var name in newModuleNames) { if (oldNames.Contains(name)) continue; // replaced by the old instance above await RemoveModuleContextAsync(tpkgPath, name).ConfigureAwait(false); _registry.UnregisterModuleSilent(name); _loadedModules.TryRemove(name, out _); } if (oldPackage is not null) _packageInstances[tpkgPath] = oldPackage; // _packageModules[tpkgPath] still lists the old names — this path never overwrote it. _ignoredDlls[tpkgPath] = newPackage.LastWriteUtc; _additionStability.TryRemove(tpkgPath, out _); var restored = ModuleActivationReport.Success; Exception? restoreException = null; if (restorable.Count > 0) { try { restored = await _coordinator.ProcessBatchAsync(restorable).ConfigureAwait(false); } catch (Exception ex) { restoreException = ex; // reported as critical right below } } // The new package goes away only after the old contexts replaced the new ones. newPackage.Dispose(); if (restoreException is not null || !restored.Succeeded || restorable.Count == 0) { _logger.LogCritical(restoreException ?? restored.Failures.FirstOrDefault()?.Exception, "Package {Pkg}: the new version failed and the previous version could not be fully restored — its modules may be down. " + "Deploy a working package; this file is skipped until it changes.", Path.GetFileName(tpkgPath)); } else { _logger.LogWarning( "Package {Pkg}: rolled back to the previous version. The new file is skipped until it changes.", Path.GetFileName(tpkgPath)); } } /// /// Performs hot swap of a single module: load new → stop old → unload old → start new. /// On failure, stays on old version (auto-rollback). /// public async Task HotSwapAsync(string moduleName, string newDllPath, string newVersion, CancellationToken ct = default) { ITsakModule? newModule = null; ModuleAssemblyLoadContext? newAlc = null; // Once we unregister the old module the registry is on the swap-in-progress state; ANY later // failure must roll back to the old version, not leave the registry pointing at a broken new // module (review item 3.2). var registryMutated = false; try { // 1. Load new assembly in a fresh ALC (from bytes — file never locked). NOTE: we do NOT // publish it to the shared LoadedAssemblyTracker yet — other modules must not resolve // the new, unvalidated-and-unstarted assembly. The tracker is switched only after the // new version has started successfully (step 8). newAlc = new ModuleAssemblyLoadContext(Path.GetFileNameWithoutExtension(newDllPath), _assemblyProbePaths, _collectible); var fullDllPath = Path.GetFullPath(newDllPath); var assembly = newAlc.LoadFromBytes(fullDllPath); // 2. Discover module in the loaded assembly var sourceDir = Path.GetDirectoryName(Path.GetFullPath(newDllPath)); var modules = TsakModuleRegistry.DiscoverModulesInAssembly(assembly, sourceDir); newModule = modules.FirstOrDefault(m => m.ModuleName.Equals(moduleName, StringComparison.OrdinalIgnoreCase)); if (newModule is null) { _logger.LogWarning("Module {Module} not found in new assembly {Path}, skipping swap", moduleName, newDllPath); newAlc.TryUnload(); return false; } // 3. Validate new module can initialize if (!newModule.CanInitialize) { _logger.LogWarning("New version of {Module} cannot initialize, staying on current version", moduleName); newAlc.TryUnload(); return false; } // 4. Silently unregister old module (no events → state preserved in store, // autoStart=false survives). Same pattern as ReloadPackageAsync. The instance is kept: // for a version loaded outside hot reload (startup discovery) it is the only copy of the // old code Tsak has once the file is overwritten in place. var oldModule = _registry.GetModule(moduleName); _registry.UnregisterModuleSilent(moduleName); registryMutated = true; // 5. Archive old version for rollback if (_loadedModules.TryGetValue(moduleName, out var oldInfo)) { var history = _previousVersions.GetOrAdd(moduleName, _ => new List()); lock (history) { history.Insert(0, oldInfo with { LiveModule = oldModule }); // Trim to keep only N versions while (history.Count > _options.KeepVersions) { var evicted = history[^1]; history.RemoveAt(history.Count - 1); evicted.Alc?.TryUnload(); } } } // 6. Replace module in registry (silent — no events, coordinator is called directly) await _registry.ReplaceModuleSilentAsync(newModule); // 7. Start new module context. ANY failure here rolls back to the old version — otherwise the // old module is unregistered and the registry is left on a broken new one. "Failure" is an // exception from the coordinator AND a module the coordinator REPORTS as not come up: it // swallows Initialize/start exceptions so a bad module cannot crash the node, so the report // is the only way a swap learns its new version never started. Exception? startFailure; try { var report = await _coordinator.ProcessModuleAddedAsync(newModule).ConfigureAwait(false); startFailure = report.FailureFor(moduleName)?.Exception; } catch (Exception ex) { startFailure = ex; // logged right below, together with the reported case } if (startFailure is not null) { _logger.LogError(startFailure, "New version of {Module} failed to start, rolling back to previous version", moduleName); var rolledBack = await RollbackAsync(moduleName, ct, overwrittenPath: newDllPath).ConfigureAwait(false); newAlc?.TryUnload(); // tracker was never switched to the new bytes — nothing to revert there if (!rolledBack) _logger.LogError("Rollback of {Module} after failed swap did not restore a previous version — module may be down", moduleName); // The failed file stays newer than the tracked version, so every scan swapped it in again: // the live module was torn down and rolled back once per scan interval, with a fresh ALC // each time. It is retried only once the file changes. IgnoreUntilChanged(newDllPath); return false; } // 8. Started successfully — finalize tracking. The module's OWN entry assembly is NOT // published to the shared LoadedAssemblyTracker: it lives only in newAlc (isolated), // exactly as the .tpkg path treats entry points (ModulePackage — entry points are never // tracked). Publishing it would Assembly.Load a second, non-unloadable copy into the // Default ALC (a leak no module context count would show) and risk a type-identity // split-brain; cross-module shared types must flow through the shared/companion layer, // which IS tracked. (Review item F-7.) _loadedModules[moduleName] = new LoadedModuleInfo(newAlc, newDllPath, newVersion); _logger.LogInformation("Hot-swapped {Module} to version {Version}", moduleName, newVersion); return true; } catch (Exception ex) { if (registryMutated) { // We already unregistered the old module (steps 4–6 mutated the registry). Restore the // old version rather than leaving the registry on a half-swapped/broken module. _logger.LogError(ex, "Hot swap of {Module} failed after unregistering the old version, rolling back", moduleName); var rolledBack = await RollbackAsync(moduleName, ct, overwrittenPath: newDllPath).ConfigureAwait(false); newAlc?.TryUnload(); if (!rolledBack) _logger.LogError("Rollback of {Module} did not restore a previous version — module may be down", moduleName); } else { // Failure before switching (load/discover/validate). The old module is untouched. _logger.LogError(ex, "Hot swap failed for {Module} before switching, staying on current version", moduleName); newAlc?.TryUnload(); } return false; } } /// /// Rolls back a module to the previous version. /// — the path the FAILED new version was loaded from /// (passed by HotSwapAsync): when it equals the previous version's path, the update was /// in-place and the file on disk now holds the broken bytes — reloading it would be a fake /// rollback (review 2026-09-02, С21). /// Returns true if rollback succeeded. /// public async Task RollbackAsync(string moduleName, CancellationToken ct = default, string? overwrittenPath = null) { if (!_previousVersions.TryGetValue(moduleName, out var history)) { _logger.LogWarning("No previous versions available for rollback of {Module}", moduleName); return false; } LoadedModuleInfo? previous; lock (history) { if (history.Count == 0) { _logger.LogWarning("No previous versions available for rollback of {Module}", moduleName); return false; } previous = history[0]; history.RemoveAt(0); } try { ITsakModule? oldModule; if (previous.Alc is null && previous.LiveModule is { } liveModule) { // The previous version was loaded outside hot reload (startup discovery): its code is // still in the process, and the swap kept its module instance. Roll back onto that // instance — the standard deployment overwrites the DLL in place, so the file now holds // the bytes being rolled back FROM and there is no old copy on disk to re-read. await _coordinator.ProcessModuleRemovedAsync(moduleName).ConfigureAwait(false); oldModule = liveModule; } else { System.Reflection.Assembly rollbackAssembly; if (previous.Alc is not null && previous.Alc.Assemblies.Any()) { // The previous version's code is STILL LOADED — roll back onto the live instance. // Re-reading previous.DllPath is wrong for an in-place update: old and new share // the path, the file now holds the bytes being rolled back FROM, and the old code // "rolled back" into the broken version in a retry loop (review 2026-09-02, С21). await _coordinator.ProcessModuleRemovedAsync(moduleName).ConfigureAwait(false); rollbackAssembly = previous.Alc.Assemblies.First(); } else if (overwrittenPath is not null && string.Equals(Path.GetFullPath(previous.DllPath), Path.GetFullPath(overwrittenPath), StringComparison.OrdinalIgnoreCase)) { // No live instance and the failed new version was written to the SAME path — the // disk no longer holds the previous version. A fake rollback would load the broken // bytes in a retry loop; refuse loudly instead and keep the history entry. _logger.LogCritical( "Rollback of {Module} impossible: {Path} was overwritten in place and no live instance of " + "version {Version} remains — deploy a known-good file.", moduleName, previous.DllPath, previous.Version); lock (history) history.Insert(0, previous); return false; } else { // Stop current version await _coordinator.ProcessModuleRemovedAsync(moduleName).ConfigureAwait(false); // Re-discover and register old version (load via ALC from bytes — no lock) var rollbackAlc = new ModuleAssemblyLoadContext(Path.GetFileNameWithoutExtension(previous.DllPath), _assemblyProbePaths, _collectible); // Entry assembly stays ALC-private — NOT republished to the shared tracker (see the F-7 note // in HotSwapAsync step 8). Republishing would leak a duplicate copy into the Default ALC. rollbackAssembly = rollbackAlc.LoadFromBytes(previous.DllPath); } var rollbackSourceDir = Path.GetDirectoryName(Path.GetFullPath(previous.DllPath)); var modules = TsakModuleRegistry.DiscoverModulesInAssembly(rollbackAssembly, rollbackSourceDir); oldModule = modules.FirstOrDefault(m => m.ModuleName.Equals(moduleName, StringComparison.OrdinalIgnoreCase)); if (oldModule is null) { _logger.LogError("Failed rollback: module {Module} not found in previous assembly {Path}", moduleName, previous.DllPath); return false; } } await _registry.ReplaceModuleSilentAsync(oldModule); var report = await _coordinator.ProcessModuleAddedAsync(oldModule).ConfigureAwait(false); _loadedModules[moduleName] = previous; if (report.FailureFor(moduleName) is { } failure) { // The previous version is registered and tracked again, but it did not come up either — // the coordinator swallowed the exception (a bad module must not crash the node). _logger.LogCritical(failure.Exception, "Rollback of {Module} to version {Version} failed: the previous version did not start either — the module is down", moduleName, previous.Version); return false; } _logger.LogInformation("Rolled back {Module} to version {Version}", moduleName, previous.Version); return true; } catch (Exception ex) { _logger.LogError(ex, "Rollback failed for {Module}", moduleName); return false; } } /// Tracks a module loaded via the initial discovery (not via hot reload). public void TrackModule(string moduleName, string dllPath, string version) { _loadedModules[moduleName] = new LoadedModuleInfo(null, dllPath, version); } /// /// Skips on later scans until its write time moves: the same rule that keeps a /// non-module dependency from being re-read every scan, applied to a file that failed. /// private void IgnoreUntilChanged(string path) { _ignoredDlls[path] = File.GetLastWriteTimeUtc(path); } /// /// Adopts packages loaded during startup discovery (by TsakModuleRegistry). /// Takes ownership of the package ALCs so hot-reload can manage their lifecycle. /// Must be called once, after DiscoverModulesAsync and before the first ScanAndReloadAsync. /// public void AdoptStartupPackages(IReadOnlyDictionary packages) { foreach (var (tpkgPath, package) in packages) { _packageInstances[tpkgPath] = package; _ignoredDlls[tpkgPath] = package.LastWriteUtc; // Build module name list for this package var moduleNames = new List(); foreach (var assembly in package.LoadedAssemblies) { var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tpkgPath)); var modules = TsakModuleRegistry.DiscoverModulesInAssembly(assembly, sourceDir); foreach (var module in modules) { moduleNames.Add(module.ModuleName); _loadedModules[module.ModuleName] = new LoadedModuleInfo( package.Alc, tpkgPath, module.Version); } } // Third convention (Route-XML Ф5.2): an XML route module is keyed by the manifest // name — without this an adopted XML-only package had no _packageModules entry, so // its redrop took the new-package path instead of ReloadPackageAsync. if (package.Manifest.Artifacts.Count > 0) { moduleNames.Add(package.Manifest.Name); _loadedModules[package.Manifest.Name] = new LoadedModuleInfo( package.Alc, tpkgPath, package.Manifest.Version); } if (moduleNames.Count > 0) _packageModules[tpkgPath] = moduleNames; _logger.LogDebug("Adopted startup package {Pkg}: {Count} modules", Path.GetFileName(tpkgPath), moduleNames.Count); } } public void Dispose() { // Idempotent (4.12): a second Dispose is a no-op. if (Interlocked.Exchange(ref _disposed, 1) == 1) return; // Wait for any in-progress scan to finish before unloading its ALCs (coordinate, not just via // a cancellation token). A scan blocked on the gate here will see _disposed and bail on release. _scanGate.Wait(); try { // Dispose package ALCs first (covers all package-owned modules atomically) foreach (var pkg in _packageInstances.Values) pkg.Dispose(); _packageInstances.Clear(); // Dispose remaining bare-DLL ALCs (skip package-owned — already handled above) foreach (var info in _loadedModules.Values) { if (info.Alc is not null && !info.DllPath.EndsWith(".tpkg", StringComparison.OrdinalIgnoreCase)) info.Alc.TryUnload(); } foreach (var history in _previousVersions.Values) { foreach (var info in history) info.Alc?.TryUnload(); } } finally { _scanGate.Release(); } } private static string GetAssemblyVersion(string dllPath) { var lastWrite = File.GetLastWriteTimeUtc(dllPath); return lastWrite.ToString("yyyy.MM.dd.HHmm", System.Globalization.CultureInfo.InvariantCulture); } /// The load context of this version; null for a version found at startup. /// The entry assembly of this version. /// The version this module reports. /// /// The instance that ran this version, kept from the moment it was swapped out. For a version loaded /// outside hot reload ( is null: startup discovery) it is the only copy of that code once /// the file is overwritten in place, and a rollback re-activates it. /// internal sealed record LoadedModuleInfo( ModuleAssemblyLoadContext? Alc, string DllPath, string Version, ITsakModule? LiveModule = null); } Path: redb-tsak/src/redb.Tsak.Core/Services/LifecycleHookOrdering.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/Services/LifecycleHookOrdering.cs ---- using redb.Tsak.Core.Contracts; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Services; /// /// Deterministic ordering for instances. Sorts by /// (Order asc, Type.FullName asc) so that two hooks sharing the same Order /// still execute in a stable, reproducible sequence across processes and runs. /// Emits a single WRN per Order-collision so operators can fix ambiguous configurations. /// internal static class LifecycleHookOrdering { /// Stable ascending order with WRN on Order collisions. public static IEnumerable OrderAscending( IEnumerable hooks, ILogger logger) { var materialized = Materialize(hooks); WarnOnTies(materialized, logger); return materialized .OrderBy(h => h.Order) .ThenBy(h => h.GetType().FullName, StringComparer.Ordinal); } /// Stable descending order (mirror of ) for shutdown. public static IEnumerable OrderDescending( IEnumerable hooks, ILogger logger) { var materialized = Materialize(hooks); WarnOnTies(materialized, logger); return materialized .OrderByDescending(h => h.Order) .ThenByDescending(h => h.GetType().FullName, StringComparer.Ordinal); } private static IReadOnlyCollection Materialize(IEnumerable hooks) => hooks as IReadOnlyCollection ?? hooks.ToList(); private static void WarnOnTies(IReadOnlyCollection hooks, ILogger logger) { foreach (var grp in hooks.GroupBy(h => h.Order).Where(g => g.Count() > 1)) { var names = string.Join(", ", grp.Select(h => h.GetType().FullName).OrderBy(n => n, StringComparer.Ordinal)); logger.LogWarning( "Lifecycle hooks share Order={Order} — tie broken by type FullName (deterministic but implicit). " + "Set distinct Order values to make execution order explicit. Hooks: {Hooks}", grp.Key, names); } } } Path: redb-tsak/src/redb.Tsak.Core/Services/NamedRedbStartFailures.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/Services/NamedRedbStartFailures.cs ---- using System.Collections.Concurrent; namespace redb.Tsak.Core.Services; /// /// What went wrong with the named redb instances of the contexts at their start, kept for the health check: an instance /// whose schema bootstrap failed (it is registered and may work once the database answers), and an instance that was /// not registered because its database refused the start. A line of the log at start is easy to miss; this stays until /// the context is removed or built again. /// internal sealed class NamedRedbStartFailures { /// False when the instance was not registered at all. /// /// The type of the failure. Its message stays in the log: a health answer may be read without authorization (the /// readiness probe), and a message of a driver names the database host. /// internal sealed record Failure(string ContextName, string InstanceName, bool Registered, string Kind); private readonly ConcurrentDictionary<(string Context, string Instance), Failure> _failures = new(); internal void Report(string contextName, string instanceName, bool registered, Exception failure) => _failures[(contextName.ToLowerInvariant(), instanceName.ToLowerInvariant())] = new Failure(contextName, instanceName, registered, failure.GetType().Name); /// Forgets a context: it was removed, or is about to be built again. internal void Clear(string contextName) { var key = contextName.ToLowerInvariant(); foreach (var entry in _failures.Keys.Where(k => k.Context == key)) _failures.TryRemove(entry, out _); } internal IReadOnlyList Current => _failures.Values .OrderBy(f => f.ContextName, StringComparer.OrdinalIgnoreCase) .ThenBy(f => f.InstanceName, StringComparer.OrdinalIgnoreCase) .ToArray(); } Path: redb-tsak/src/redb.Tsak.Core/Services/RedbInstanceDescription.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/Services/RedbInstanceDescription.cs ---- using System.Security.Cryptography; using System.Text; using redb.Tsak.Contracts; namespace redb.Tsak.Core.Services; /// /// Describes a redb instance for the storage page, capability flags included. /// /// The flags are decided by the provider, not by whether a value came back null: SQLite has no schemas, no /// usage counters and no record of when statistics were refreshed, so those columns and the per-table /// analyze button are not drawn at all. Reading it the other way round — hiding a column because this run /// returned nulls — would hide a column on PostgreSQL the moment a database happened to have no reads yet. /// /// internal static class RedbInstanceDescription { /// Builds the description of one instance from its configured provider and connection string. internal static RedbInstanceInfo Describe( string name, string? contextName, string? provider, string? connectionString, bool usePro, bool isActive) { var normalized = (provider ?? "").Trim().ToLowerInvariant(); // Anything that is not one of the two schema-bearing engines is treated as the poorest case: an // unknown provider gets no columns rather than empty ones. var rich = normalized is "postgres" or "postgresql" or "mssql" or "sqlserver"; return new RedbInstanceInfo { Name = name, ContextName = contextName, Provider = normalized, UsePro = usePro, IsActive = isActive, Fingerprint = Fingerprint(normalized, connectionString), SupportsSchemas = rich, SupportsUsageCounters = rich, SupportsAnalyzeTimestamps = rich }; } /// /// Identifies the database behind an instance without disclosing it: the first bytes of a hash over the /// provider and the connection string. Contexts that declare the same database get the same fingerprint, /// which is how the dashboard collapses fifteen rows of five contexts into the three databases they are. /// A connection string carries credentials and never leaves the node, so it is not sent instead. /// private static string Fingerprint(string provider, string? connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) return ""; var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(provider + "|" + connectionString)); return Convert.ToHexString(bytes.AsSpan(0, 8)).ToLowerInvariant(); } } Path: redb-tsak/src/redb.Tsak.Core/Services/RedbInstanceFactory.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/Services/RedbInstanceFactory.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using redb.Core; using redb.Core.Configuration; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; namespace redb.Tsak.Core.Services; /// /// Creates isolated instances from config dictionaries. /// Each instance lives in its own mini-DI container (ServiceProvider) that the caller must dispose. /// internal static class RedbInstanceFactory { /// /// Creates a named IRedbService from a config dictionary. /// /// Instance name (for logging). /// Config dictionary (Provider, ConnectionString, UsePro, etc.). /// Optional logger for diagnostics. /// /// The host's registry of save interceptors: given, the instance runs the interceptors modules subscribed through /// their contexts, as the host's redb service does. /// /// /// Told a failure of the schema bootstrap that leaves the instance handed out (it is logged as a warning here). /// /// Tuple of the service and its mini-container (caller must dispose container). public static (IRedbService Service, ServiceProvider Container) Create( string name, IDictionary config, ILogger? logger = null, redb.Core.Interception.IRedbSaveInterceptorRegistry? saveInterceptorRegistry = null, Action? onBootstrapFailure = null) { var provider = GetString(config, "Provider"); var connectionString = GetString(config, "ConnectionString"); if (string.IsNullOrEmpty(provider)) throw new InvalidOperationException($"Named redb '{name}': 'Provider' is required (postgres, mssql or sqlite)."); if (string.IsNullOrEmpty(connectionString)) throw new InvalidOperationException($"Named redb '{name}': 'ConnectionString' is required."); var usePro = GetBool(config, "UsePro"); var services = new ServiceCollection(); // AddRedb keeps a registry already in the container (TryAdd), so the instance shares the host's. if (saveInterceptorRegistry is not null) services.AddSingleton(saveInterceptorRegistry); if (usePro) { services.AddRedbPro(options => { ConfigureProvider(options, provider, connectionString, name, isPro: true); options.Configure(c => ApplyConfig(c, config)); }); } else { services.AddRedb(options => { ConfigureProvider(options, provider, connectionString, name, isPro: false); options.Configure(c => ApplyConfig(c, config)); }); } // Add minimal logging so internal services can resolve ILogger services.AddLogging(lb => lb.SetMinimumLevel(LogLevel.Warning)); var container = services.BuildServiceProvider(); var redbService = container.GetRequiredService(); // RedbInitHostedService won't auto-run (no IHost). If EnsureCreated, init manually. var ensureCreated = GetBool(config, "EnsureCreated"); if (ensureCreated) { try { redbService.InitializeAsync(ensureCreated: true).GetAwaiter().GetResult(); logger?.LogInformation("Named redb '{Name}': schema initialized (EnsureCreated=true)", name); } catch (Exception ex) when (IsStartRefusal(ex)) { // The database refuses this start: the instance is not handed out, the caller reports it. container.Dispose(); throw; } catch (Exception ex) { logger?.LogWarning(ex, "Named redb '{Name}': failed to ensure schema", name); onBootstrapFailure?.Invoke(ex); } } logger?.LogInformation( "Created named IRedbService '{Name}' (provider={Provider}, pro={Pro})", name, provider, usePro); return (redbService, container); } /// /// A failure of the schema bootstrap after which the instance is not handed out: the database holds a schema newer /// than this build serves (redb changed nothing and must not be used on it), or the schema lock was not released /// (another process is still changing the schema, and this one did not get to check or synchronise it). /// internal static bool IsStartRefusal(Exception ex) => ex is redb.Core.Exceptions.RedbSchemaNewerException or redb.Core.Exceptions.RedbSchemaLockTimeoutException; private static void ConfigureProvider(RedbOptionsBuilder options, string provider, string connectionString, string name, bool isPro) { // Use explicit namespace-qualified calls to avoid ambiguity between OS and Pro extension methods var infrastructure = (IRedbOptionsBuilderInfrastructure)options; if (!string.IsNullOrEmpty(connectionString)) infrastructure.Configuration.ConnectionString = connectionString; switch (provider.ToLowerInvariant()) { case "postgres" or "postgresql" or "npgsql": if (isPro) redb.Postgres.Pro.Extensions.PostgresProOptionsExtensions.UsePostgres(options, connectionString); else redb.Postgres.Extensions.PostgresOptionsExtensions.UsePostgres(options, connectionString); break; case "mssql" or "sqlserver": if (isPro) redb.MSSql.Pro.Extensions.MsSqlProOptionsExtensions.UseMsSql(options, connectionString); else redb.MSSql.Extensions.MsSqlOptionsExtensions.UseMsSql(options, connectionString); break; case "sqlite": // redb.SQLite.Pro.Extensions.UseSqlite is tier-agnostic — it dispatches // on AddRedb (Free) vs AddRedbPro (Pro) at registration time, so the same // call works for both branches. redb.SQLite.Pro.Extensions.SqliteProOptionsExtensions.UseSqlite(options, connectionString); break; default: throw new InvalidOperationException( $"Named redb '{name}': unsupported provider '{provider}'. Use 'postgres', 'mssql' or 'sqlite'."); } } private static void ApplyConfig(RedbServiceConfiguration c, IDictionary config) { // Reflection-based pass first, so every RedbServiceConfiguration property is reachable and an // unrecognised key gets reported instead of vanishing. The hand-written block below then runs // unchanged and stays authoritative — it also carries the legacy key names (EnsureCreated // defaulting to false here, the *Minutes spellings), which the binder must not second-guess. Extensions.RedbConfigBinder.Apply( c, new ConfigurationBuilder() .AddInMemoryCollection(config.ToDictionary(kv => kv.Key, kv => kv.Value?.ToString())) .Build(), "Redb", m => Console.Error.WriteLine(m)); // EnsureCreated defaults to false for named instances (schema assumed to exist) c.EnsureCreated = GetBool(config, "EnsureCreated"); if (TryGetString(config, "PropsSaveStrategy", out var strategy)) c.PropsSaveStrategy = Enum.Parse(strategy, ignoreCase: true); if (TryGetBool(config, "EnablePropsCache", out var propsCache)) c.EnablePropsCache = propsCache; if (TryGetInt(config, "PropsCacheMaxSize", out var pcMax)) c.PropsCacheMaxSize = pcMax; if (TryGetInt(config, "PropsCacheTtlMinutes", out var pcTtl)) c.PropsCacheTtl = TimeSpan.FromMinutes(pcTtl); if (TryGetBool(config, "SkipHashValidationOnCacheCheck", out var skipHash)) c.SkipHashValidationOnCacheCheck = skipHash; if (TryGetBool(config, "EnableListCache", out var listCache)) c.EnableListCache = listCache; if (TryGetInt(config, "ListCacheTtlMinutes", out var lcTtl)) c.ListCacheTtl = TimeSpan.FromMinutes(lcTtl); if (TryGetBool(config, "EnableMetadataCache", out var metaCache)) c.EnableMetadataCache = metaCache; if (TryGetInt(config, "MetadataCacheLifetimeMinutes", out var metaTtl)) c.MetadataCacheLifetimeMinutes = metaTtl; if (TryGetBool(config, "WarmupMetadataCacheOnInit", out var warmup)) c.WarmupMetadataCacheOnInit = warmup; if (TryGetInt(config, "DefaultLoadDepth", out var loadDepth)) c.DefaultLoadDepth = loadDepth; if (TryGetInt(config, "DefaultMaxTreeDepth", out var treeDepth)) c.DefaultMaxTreeDepth = treeDepth; if (TryGetBool(config, "ThrowOnObjectNotFound", out var throwNotFound)) c.ThrowOnObjectNotFound = throwNotFound; if (TryGetBool(config, "AutoSyncSchemesOnSave", out var autoSync)) c.AutoSyncSchemesOnSave = autoSync; if (TryGetBool(config, "EnableSchemaValidation", out var schemaVal)) c.EnableSchemaValidation = schemaVal; if (TryGetBool(config, "EnableDataValidation", out var dataVal)) c.EnableDataValidation = dataVal; if (TryGetString(config, "CacheDomain", out var cacheDomain)) c.CacheDomain = cacheDomain; } // ── Config helpers ─────────────────────────────────────────────── private static string? GetString(IDictionary d, string key) => d.TryGetValue(key, out var v) ? v?.ToString() : null; private static bool GetBool(IDictionary d, string key) => d.TryGetValue(key, out var v) && v is true or "true" or "True" or "TRUE"; private static bool TryGetString(IDictionary d, string key, out string value) { if (d.TryGetValue(key, out var v) && v != null) { value = v.ToString()!; return true; } value = default!; return false; } private static bool TryGetBool(IDictionary d, string key, out bool value) { if (d.TryGetValue(key, out var v)) { value = v is true or "true" or "True" or "TRUE"; return true; } value = default; return false; } private static bool TryGetInt(IDictionary d, string key, out int value) { if (d.TryGetValue(key, out var v)) { if (v is int i) { value = i; return true; } if (v is long l) { value = (int)l; return true; } if (v != null && int.TryParse(v.ToString(), out var parsed)) { value = parsed; return true; } } value = default; return false; } } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/InMemoryTsakModuleStore.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/Services/Storage/InMemoryTsakModuleStore.cs ---- using System.Collections.Concurrent; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services.Storage; /// /// In-memory module store for Standalone mode. Not persistent across restarts. /// public class InMemoryTsakModuleStore : ITsakModuleStore { private readonly ConcurrentDictionary _modules = new(StringComparer.OrdinalIgnoreCase); public Task> GetAllAsync() => Task.FromResult>(_modules.Values.ToList()); public Task GetAsync(string moduleName) => Task.FromResult(_modules.GetValueOrDefault(moduleName)); public Task SaveAsync(TsakModuleRecord record) { _modules[record.ModuleName] = record; return Task.CompletedTask; } public Task RemoveAsync(string moduleName) { _modules.TryRemove(moduleName, out _); return Task.CompletedTask; } public Task SaveBatchAsync(IEnumerable records) { foreach (var record in records) _modules[record.ModuleName] = record; return Task.CompletedTask; } } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/InMemoryTsakStateStore.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/Services/Storage/InMemoryTsakStateStore.cs ---- using System.Collections.Concurrent; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services.Storage; /// /// In-memory state store for Standalone mode. Not persistent across restarts. /// Ordinal, case-sensitive keys — the contract; this class used /// to fold case and thereby diverge from the redb-backed store (review 2026-09-02, С7). /// public class InMemoryTsakStateStore : ITsakStateStore { private readonly ConcurrentDictionary _state = new(StringComparer.Ordinal); public Task GetAsync(string key) => Task.FromResult(_state.GetValueOrDefault(key)); public Task SetAsync(string key, string value) { _state[key] = value; return Task.CompletedTask; } public Task RemoveAsync(string key) { _state.TryRemove(key, out _); return Task.CompletedTask; } public Task> GetByPrefixAsync(string prefix) { var result = _state .Where(kv => kv.Key.StartsWith(prefix, StringComparison.Ordinal)) .ToDictionary(kv => kv.Key, kv => kv.Value); return Task.FromResult>(result); } } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/RedbTsakModuleStore.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/Services/Storage/RedbTsakModuleStore.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services.Storage; /// /// Props class for module store entries. /// Fields mirror for typed query access. /// public class TsakModuleProps { public string ModuleName { get; set; } = string.Empty; public string Version { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public List Dependencies { get; set; } = []; public TsakModuleStatus Status { get; set; } = TsakModuleStatus.Discovered; public string? AssemblyPath { get; set; } /// /// Cluster the record belongs to. Null on a record written before cluster isolation (4.0.x and /// older): its key is the bare module name, and a store still lists it until its own cluster /// saves or removes that module. /// public string? ClusterName { get; set; } } /// /// Redb-backed module store. Persists module metadata across restarts and cluster nodes. /// The key lives in ValueUnique: one record per module is enforced by the /// database, and SaveByUniqueAsync makes a true upsert — /// two nodes discovering the same module concurrently converge on one record. /// The key is "{cluster}:{module}" (): several clusters on one /// database keep their own record of an equally named module. A record written before cluster /// isolation (bare module name, no ) is still read until /// this cluster saves the module; removing a module removes that old record too. /// value_string still mirrors the name for dashboard visibility. /// Every operation awaits a one-time ensure step (scheme sync + legacy backfill), so hosts /// without TsakHostedService and reads racing its startup see pre-V4 rows /// (review 2026-09-02, В4). /// public class RedbTsakModuleStore : ITsakModuleStore { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly string _clusterName; private readonly string _keyPrefix; private readonly SemaphoreSlim _ensureLock = new(1, 1); private volatile bool _ensured; public RedbTsakModuleStore( IServiceScopeFactory scopeFactory, ILogger? logger = null, IConfiguration? configuration = null) { _scopeFactory = scopeFactory; _logger = logger ?? NullLogger.Instance; _clusterName = TsakStorageScope.ClusterName(configuration); _keyPrefix = _clusterName + ":"; } private string KeyOf(string moduleName) => _keyPrefix + moduleName; public async Task> GetAllAsync() { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var clusterName = _clusterName; var objects = await redb.Query() .Where(p => p.ClusterName == clusterName || p.ClusterName == null) .ToListAsync(); var records = objects .Where(o => o.Props is not null && o.Props.ClusterName == clusterName) .Select(ToRecord) .ToList(); // Records written before cluster isolation, unless this cluster has its own record of the module. var own = records.Select(r => r.ModuleName).ToHashSet(StringComparer.Ordinal); records.AddRange(objects .Where(o => o.Props is not null && o.Props.ClusterName is null && !own.Contains(o.Props.ModuleName)) .Select(ToRecord)); return records; } public async Task GetAsync(string moduleName) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = await FindAsync(redb, KeyOf(moduleName)) ?? await FindLegacyAsync(redb, moduleName); return obj is not null ? ToRecord(obj) : null; } public async Task SaveAsync(TsakModuleRecord record) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var props = ToProps(record); props.ClusterName = _clusterName; // The Remove+Save+Save interleave (review С2) is covered by the core since BR-8 closed: // SaveByUniqueAsync retries an ObjectKey race onto the current winner itself. await redb.SaveByUniqueAsync(new RedbObject { name = record.ModuleName, ValueUnique = KeyOf(record.ModuleName), value_string = record.ModuleName, value_long = (long)record.Status, note = record.Description, Props = props }); } public async Task RemoveAsync(string moduleName) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var existing = await FindAsync(redb, KeyOf(moduleName)); if (existing is not null) await redb.DeleteAsync(existing); // The record written before cluster isolation goes too — otherwise the read fallback would // bring the removed module back. var legacy = await FindLegacyAsync(redb, moduleName); if (legacy is not null) await redb.DeleteAsync(legacy); } public async Task SaveBatchAsync(IEnumerable records) { foreach (var record in records) await SaveAsync(record); } private static async Task?> FindAsync(IRedbService redb, string stored) => await redb.Query() .WhereRedb(o => o.ValueUnique == stored) .FirstOrDefaultAsync(); /// /// The record written before cluster isolation for . Another /// cluster's key can spell the same string, so only a record without a cluster counts. /// private static async Task?> FindLegacyAsync(IRedbService redb, string moduleName) { var obj = await FindAsync(redb, moduleName); return obj is not null && obj.Props?.ClusterName is null ? obj : null; } /// One-time scheme sync + legacy backfill; safe under concurrency, retried on failure. private async Task EnsureReadyAsync() { if (_ensured) return; await _ensureLock.WaitAsync(); try { if (_ensured) return; using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await BackfillLegacyAsync(redb, _logger); _ensured = true; // only after success — a failure retries on the next call } finally { _ensureLock.Release(); } } /// /// The ONE home of the module-store legacy migration rule. Called from the store's ensure /// step and from TsakHostedService startup. A pre-key row gets the bare-name key of a 4.0.x /// record and is read through the same fallback as one. /// internal static Task BackfillLegacyAsync(IRedbService redb, ILogger logger) => TsakUniqueBackfill.RunAsync( redb, o => o.ValueString ?? o.Props?.ModuleName, TsakUniqueBackfill.DuplicatePolicy.DeleteLosers, logger); // ── Mapping helpers ────────────────────────────────────────────── private static TsakModuleRecord ToRecord(RedbObject obj) { var props = obj.Props!; return new TsakModuleRecord { ModuleName = props.ModuleName, Version = props.Version, Description = props.Description, Dependencies = props.Dependencies, Status = props.Status, AssemblyPath = props.AssemblyPath, RegisteredAt = obj.date_create, LastUpdatedAt = obj.date_modify }; } private static TsakModuleProps ToProps(TsakModuleRecord record) => new() { ModuleName = record.ModuleName, Version = record.Version, Description = record.Description, Dependencies = record.Dependencies.ToList(), Status = record.Status, AssemblyPath = record.AssemblyPath }; } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/RedbTsakStateStore.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/Services/Storage/RedbTsakStateStore.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Route.RedbCore; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services.Storage; /// /// Props class for state store entries. Scheme is auto-created from type name. /// public class TsakStateProps { /// State value (stored in Props for typed access; also mirrored to note). public string Value { get; set; } = string.Empty; /// /// Cluster the entry belongs to. Null on an entry written before cluster isolation (4.0.x and /// older): its key has no cluster prefix, and a store still reads it until its own cluster writes /// or removes that key. /// public string? ClusterName { get; set; } } /// /// Redb-backed state store. Persists key-value state across restarts. /// The key lives in ValueUnique: uniqueness per key is enforced by the database and /// SaveByUniqueAsync makes a true upsert — two nodes setting /// the same key concurrently converge on one record instead of duplicating it. /// The stored key is "{cluster}:{key}" (): several clusters /// on one database keep their own route and context state. An entry written before cluster /// isolation (unprefixed, no ) is still read — by key and /// by prefix — until this cluster writes the key; removing a key removes that old entry too, so /// the old value never comes back. Keys come back from in caller form. /// Keys are normalized with (440-cap of the key column; /// caller keys embed context/route ids and carry no length contract — review 2026-09-02, В8). /// value_string still mirrors the raw key (truncated to its own cap) for visibility. /// Prefix search is server-side and case-sensitive ordinal (owner decision 2026-09-02); the /// contract note lives on . /// Every operation awaits a one-time ensure step (scheme sync + legacy-key backfill), so a /// host without TsakHostedService — or a read racing its startup — still sees pre-V4 rows /// (review 2026-09-02, В4). /// public class RedbTsakStateStore : ITsakStateStore { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly string _clusterName; private readonly string _keyPrefix; private readonly SemaphoreSlim _ensureLock = new(1, 1); private volatile bool _ensured; public RedbTsakStateStore( IServiceScopeFactory scopeFactory, ILogger? logger = null, IConfiguration? configuration = null) { _scopeFactory = scopeFactory; _logger = logger ?? NullLogger.Instance; _clusterName = TsakStorageScope.ClusterName(configuration); _keyPrefix = _clusterName + ":"; } private string KeyOf(string key) => RedbUniqueKey.Normalize(_keyPrefix + key); private static string LegacyKeyOf(string key) => RedbUniqueKey.Normalize(key); public async Task GetAsync(string key) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = await FindAsync(redb, KeyOf(key)) ?? await FindLegacyAsync(redb, LegacyKeyOf(key)); return obj?.Props?.Value; } public async Task SetAsync(string key, string value) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var stored = KeyOf(key); // The Remove+Set+Set interleave (review С2) is covered by the core since BR-8 closed: // SaveByUniqueAsync retries an ObjectKey race — including "the resolved row was deleted // and the key re-created" — onto the current winner itself. await redb.SaveByUniqueAsync(new RedbObject { name = stored, ValueUnique = stored, value_string = key.Length <= 440 ? key : key[..440], note = value, Props = new TsakStateProps { Value = value, ClusterName = _clusterName } }); } public async Task RemoveAsync(string key) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var existing = await FindAsync(redb, KeyOf(key)); if (existing is not null) await redb.DeleteAsync(existing); // The entry written before cluster isolation goes too — otherwise the read fallback would // bring the removed value back. var legacy = await FindLegacyAsync(redb, LegacyKeyOf(key)); if (legacy is not null) await redb.DeleteAsync(legacy); } public async Task> GetByPrefixAsync(string prefix) { await EnsureReadyAsync(); using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Server-side PREFILTER, not the final answer: LIKE is case-insensitive on SQLite (and a // CI-collation MSSQL), so it may return a superset there — the ordinal re-checks below // make the case-sensitive contract hold on every provider (BR-6 contract). The prefix is an // index condition on SQL Server only; on PostgreSQL with a non-C database collation and on // SQLite the index (_id_scheme, _value_unique) narrows to the scheme and the prefix is a // filter over its rows — cheap while the scheme holds hundreds of keys. Metacharacters // in the prefix are safe since BR-7 closed: the core treats StartsWith operands as // literals on all providers, so the old full-load fallback is gone. var scopedPrefix = _keyPrefix + prefix; var scoped = await redb.Query() .WhereRedb(o => o.ValueUnique!.StartsWith(scopedPrefix)) .ToListAsync(); var result = new Dictionary(StringComparer.Ordinal); foreach (var o in scoped) { if (o.ValueUnique is { } stored && stored.StartsWith(scopedPrefix, StringComparison.Ordinal)) result[stored[_keyPrefix.Length..]] = o.Props?.Value ?? string.Empty; } // Entries written before cluster isolation, unless this cluster has its own entry for the key. var legacy = await redb.Query() .WhereRedb(o => o.ValueUnique!.StartsWith(prefix)) .ToListAsync(); foreach (var o in legacy) { if (o.Props?.ClusterName is null && o.ValueUnique is { } stored && stored.StartsWith(prefix, StringComparison.Ordinal)) result.TryAdd(stored, o.Props?.Value ?? string.Empty); } return result; } private static async Task?> FindAsync(IRedbService redb, string stored) => await redb.Query() .WhereRedb(o => o.ValueUnique == stored) .FirstOrDefaultAsync(); /// /// The entry written before cluster isolation under . Another cluster's /// prefixed key can spell the same string, so only an entry without a cluster counts. /// private static async Task?> FindLegacyAsync(IRedbService redb, string stored) { var obj = await FindAsync(redb, stored); return obj is not null && obj.Props?.ClusterName is null ? obj : null; } /// One-time scheme sync + legacy backfill; safe under concurrency, retried on failure. private async Task EnsureReadyAsync() { if (_ensured) return; await _ensureLock.WaitAsync(); try { if (_ensured) return; using var scope = _scopeFactory.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.SyncSchemeAsync(); await BackfillLegacyAsync(redb, _logger); _ensured = true; // only after success — a failure retries on the next call } finally { _ensureLock.Release(); } } /// /// The ONE home of the state-store legacy migration rule (pre-key rows keyed on /// value_string). Called from the store's ensure step and from TsakHostedService startup. /// A pre-key row gets the unprefixed key of a 4.0.x entry and is read through the same /// fallback as one. /// internal static Task BackfillLegacyAsync(IRedbService redb, ILogger logger) => TsakUniqueBackfill.RunAsync( redb, o => o.ValueString is { Length: > 0 } raw ? RedbUniqueKey.Normalize(raw) : null, TsakUniqueBackfill.DuplicatePolicy.DeleteLosers, logger); } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/TsakStorageScope.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/Services/Storage/TsakStorageScope.cs ---- using Microsoft.Extensions.Configuration; namespace redb.Tsak.Core.Services.Storage; /// /// Cluster scope of the redb-backed Tsak stores. Several Tsak clusters may share one database, so a /// stored key carries the cluster name from Tsak:Cluster:ClusterName. The default matches the /// cluster options of redb.Tsak.Core.Pro, and a host without cluster mode uses it as well. /// internal static class TsakStorageScope { public const string DefaultClusterName = "default"; public static string ClusterName(IConfiguration? configuration) => configuration?["Tsak:Cluster:ClusterName"] is { } name && !string.IsNullOrWhiteSpace(name) ? name : DefaultClusterName; } Path: redb-tsak/src/redb.Tsak.Core/Services/Storage/TsakUniqueBackfill.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/Services/Storage/TsakUniqueBackfill.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Entities; namespace redb.Tsak.Core.Services.Storage; /// /// One-time V4 migration pass: stamps ValueUnique onto rows written by pre-key /// versions of Tsak. A NULL key sits /// outside the partial unique index, so without this pass legacy rows would coexist with /// keyed ones and escape the "one record per key" guarantee. Idempotent: rows that /// already carry a key are never touched, a second run is a single server-side probe. /// Duplicates (the trace of the old check-then-insert races) resolve deterministically: /// the lowest id wins — the same winner the old self-healing picked. /// public static class TsakUniqueBackfill { public enum DuplicatePolicy { /// Losers are deleted — operational records (locks, nodes, assignments, KV entries). DeleteLosers, /// /// Losers stay, unkeyed, and are logged as critical — for rows that may anchor a /// subtree (cluster roots, groups), where silent deletion could orphan children. /// KeepLosersUnkeyed, } /// /// returns the ValueUnique for a legacy row, or null /// when it cannot be computed (the row is skipped with a warning; an /// from it counts as null). runs /// on the winner right before it is saved — e.g. to fill a new Props field on the way. /// public static async Task RunAsync( IRedbService redb, Func, string?> computeKey, DuplicatePolicy duplicates, ILogger logger, Action>? amend = null) where TProps : class, new() { // Post-migration fast path (review 2026-09-02, Q4): one probe of the partial index // instead of hydrating the whole scheme on every process start — this pass sits on // startup-critical paths (leader election's first lock acquire included). var hasLegacy = await redb.Query() .WhereRedb(o => o.ValueUnique == null) .AnyAsync() .ConfigureAwait(false); if (!hasLegacy) return; // Transient deadlocks in the stamp/delete sweep must not abort node startup // (review 2026-09-02, С4; plan Ф7.1 required the retry from the start). await DeadlockRetryHelper.ExecuteWithRetryAsync( () => RunCoreAsync(redb, computeKey, duplicates, logger, amend)).ConfigureAwait(false); } private static async Task RunCoreAsync( IRedbService redb, Func, string?> computeKey, DuplicatePolicy duplicates, ILogger logger, Action>? amend) where TProps : class, new() { // The full load runs only while legacy rows exist; every scheme this pass runs on is // small by construction (locks, nodes, assignments, state entries, module records, keys). var all = await redb.Query().ToListAsync().ConfigureAwait(false); var legacy = all.Where(o => o.ValueUnique is null).ToList(); if (legacy.Count == 0) return; var claimedKeys = new HashSet( all.Where(o => o.ValueUnique is not null).Select(o => o.ValueUnique!), StringComparer.Ordinal); var withKeys = new List<(RedbObject Row, string? Key)>(legacy.Count); foreach (var row in legacy) { string? key; try { key = computeKey(row); } catch (ArgumentException ex) { logger.LogWarning(ex, "{Scheme}: cannot compute a unique key for legacy row {Id}", typeof(TProps).Name, row.id); key = null; } withKeys.Add((row, key)); } foreach (var group in withKeys.GroupBy(t => t.Key, StringComparer.Ordinal)) { if (group.Key is null) { foreach (var (row, _) in group) logger.LogWarning("{Scheme}: legacy row {Id} has no computable unique key — left unkeyed", typeof(TProps).Name, row.id); continue; } var ordered = group.Select(t => t.Row).OrderBy(o => o.id).ToList(); var losers = ordered.AsEnumerable(); // A keyed row for this value may already exist (another node re-created the record // after its own backfill) — then every legacy row is a loser. if (!claimedKeys.Contains(group.Key)) { var winner = ordered[0]; winner.ValueUnique = group.Key; amend?.Invoke(winner); try { await redb.SaveAsync(winner).ConfigureAwait(false); losers = ordered.Skip(1); if (ordered.Count > 1) logger.LogWarning("{Scheme}: key '{Key}' had {Count} legacy duplicates — kept id {Id}", typeof(TProps).Name, group.Key, ordered.Count, winner.id); } catch (RedbUniqueViolationException ex) when (!IsObjectKeyViolation(ex)) { // The violation came from a DIFFERENT unique index (e.g. an amend-stamped // [RedbUnique] Props field). These rows are NOT duplicates of each other's // object key — deleting them would destroy live data (review 2026-09-02, К4: // pre-V4 api-key rotation left two hashes sharing one note; the second row is // the CURRENT credential). Keep everything, report loudly, move on. logger.LogCritical(ex, "{Scheme}: stamping key '{Key}' violated a different unique index ({Where}) — " + "rows of this group are left unkeyed and NOT deleted; resolve the conflicting " + "values (e.g. duplicate ids) and restart to finish the migration", typeof(TProps).Name, group.Key, ex.PropertyName ?? ex.ConstraintName ?? "unresolved index"); continue; } catch (RedbUniqueViolationException) { // The object key itself was claimed concurrently by another node's backfill — // our winner is a loser like the rest. logger.LogInformation("{Scheme}: key '{Key}' was claimed concurrently — all legacy rows are losers", typeof(TProps).Name, group.Key); } catch (RedbUniqueKeyValueException ex) { // The computed key breaks a core constraint (e.g. longer than 440 chars). // A data problem in one row must not crash node startup (review 2026-09-02, // В8) — leave the group unkeyed and report it. logger.LogCritical(ex, "{Scheme}: key for legacy row {Id} is not storable ({Message}) — row left unkeyed", typeof(TProps).Name, winner.id, ex.Message); winner.ValueUnique = null; continue; } } foreach (var loser in losers) { if (duplicates == DuplicatePolicy.KeepLosersUnkeyed) { logger.LogCritical( "{Scheme}: legacy row {Id} duplicates key '{Key}' and may anchor a subtree — left unkeyed. " + "Verify which subtree actually holds the live children before touching either row", typeof(TProps).Name, loser.id, group.Key); continue; } try { await redb.DeleteAsync(loser).ConfigureAwait(false); } catch (Exception ex) { logger.LogWarning(ex, "{Scheme}: failed to delete legacy duplicate {Id} (key '{Key}')", typeof(TProps).Name, loser.id, group.Key); } } } } /// /// True only when the violation is confidently attributable to the OBJECT key index /// (_objects._value_unique) — first-class via /// since BR-8 closed (the old heuristic parsed constraint names and driver text). An UNKNOWN /// source answers false: the destructive claimed-concurrently path must never run on a guess /// (review 2026-09-02, К4). /// internal static bool IsObjectKeyViolation(RedbUniqueViolationException ex) => ex.Kind == RedbUniqueViolationKind.ObjectKey; } Path: redb-tsak/src/redb.Tsak.Core/Services/SystemContextBuilder.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/Services/SystemContextBuilder.cs ---- using System.Data.Common; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Controllers; using redb.Route.Http; using redb.Route.Processors; using redb.Route.Quartz; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Tsak.Core.Audit; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Dlq; using redb.Tsak.Core.Controllers; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Security; using redb.Core.Providers; namespace redb.Tsak.Core.Services; /// /// Builds and starts the _system route context that hosts the REST management API. /// Pipeline: HTTP listener → header bridge → auth (optional) → controller dispatch. /// Respects Tsak:Api:Enabled config (default: true). /// public class SystemContextBuilder { public const string SystemContextName = "_system"; /// Route id of the auth-exempt echo probe on the API port; it ships stopped. public const string EchoRouteId = "system-echo"; /// /// Route id of the management API itself. Without it the engine derives an id from the listen URI — /// http://0.0.0.0:9090/{**path}?host=… — which reads as noise in the dashboard and cannot travel /// as a path segment of the routes API. /// public const string ApiRouteId = "system-api"; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false, Converters = { new JsonStringEnumConverter() } }; /// Loopback client used by the facade /metrics route to proxy the OTel listener. private static readonly HttpClient MetricsClient = new() { Timeout = TimeSpan.FromSeconds(10) }; private readonly ITsakContextManager _contextManager; private readonly IConfiguration _configuration; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public SystemContextBuilder( ITsakContextManager contextManager, IConfiguration configuration, IServiceProvider serviceProvider, ILogger logger) { _contextManager = contextManager; _configuration = configuration; _serviceProvider = serviceProvider; _logger = logger; } /// /// Creates and starts the _system context with the REST API if enabled in config. /// Returns the context or null if the API is disabled. /// public async Task BuildAndStartAsync( ITsakModuleRegistry registry, CancellationToken ct = default) { var enabled = _configuration.GetValue("Tsak:Api:Enabled", true); if (!enabled) { _logger.LogInformation("REST API disabled (Tsak:Api:Enabled=false)"); return null; } // Secure by default: bind loopback. Local runs work out of the box; exposing the management // plane on 0.0.0.0/an external address is now an explicit choice, not the default. var host = _configuration.GetValue("Tsak:Api:Host", "127.0.0.1"); var port = _configuration.GetValue("Tsak:Api:Port", 9090); var authEnabled = _configuration.GetValue("Tsak:Auth:Enabled", false); // Auth-exempt patterns (config: Tsak:Api:AuthExempt). Default: K8s health probes. // Patterns ending in '*' use prefix match; otherwise exact (case-insensitive) match. var exemptPatterns = _configuration .GetSection("Tsak:Api:AuthExempt") .Get() ?? new[] { "/api/health/*", "/api/health" }; // Consolidated port summary so an operator sees EVERY configured port in one startup line, instead // of hunting through the API, echo and Prometheus setup separately. var echoPathSummary = _configuration.GetValue("Tsak:Api:Echo:Path", "/api/echo"); var promEnabled = _configuration.GetValue("Tsak:Metrics:Prometheus:Enabled", false); var promPort = _configuration.GetValue("Tsak:Metrics:Prometheus:Port", 9464); var promSummary = promEnabled ? $"/metrics on http://{host}:{port}/metrics (scrapes OTel listener http://localhost:{promPort}/metrics)" : "disabled"; _logger.LogInformation( "Tsak ports — management API: http://{Host}:{Port} (auth={Auth}); echo: http://{Host}:{Port}{Echo} " + "(AutoStart=false); Prometheus: {Prom}", host, port, authEnabled, host, port, echoPathSummary, promSummary); // Loud warning: management plane exposed off-loopback with no auth = full unauthenticated admin. var isLoopback = string.Equals(host, "127.0.0.1", StringComparison.Ordinal) || string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) || string.Equals(host, "::1", StringComparison.Ordinal); if (!isLoopback && !authEnabled) { _logger.LogWarning( "SECURITY: the Tsak management API is bound to a non-loopback address ({Host}:{Port}) with " + "authentication DISABLED. Anyone who can reach this port gets full unauthenticated admin " + "(stop/remove contexts, upload modules, issue keys, dump config). Set Tsak:Auth:Enabled=true " + "or bind Tsak:Api:Host to 127.0.0.1 before exposing this port.", host, port); } // 1. Create the context via context manager var context = _contextManager.CreateContext(SystemContextName, _serviceProvider, new Dictionary()); var routeContext = (RouteContext)context; // 2. Add HTTP component so http: URIs resolve var httpComponent = _serviceProvider.GetService(typeof(HttpComponent)) as HttpComponent; if (httpComponent is null) { _logger.LogError("HttpComponent not available in DI — cannot start REST API. Register AddRedbRouteHttp() in DI."); await _contextManager.RemoveContextAsync(SystemContextName); return null; } routeContext.AddComponent(httpComponent); // 3. Register services that controllers need RegisterServices(routeContext, registry, authEnabled); // 4. Build controller registry var controllerRegistry = new ControllerRegistry(); controllerRegistry.RegisterAssembly(typeof(ContextsController).Assembly); // 4a. Let plugins contribute additional controllers and services var plugins = _serviceProvider.GetService>() ?? Enumerable.Empty(); foreach (var plugin in plugins) { plugin.ConfigureServices(routeContext, _serviceProvider); foreach (var asm in plugin.GetControllerAssemblies()) controllerRegistry.RegisterAssembly(asm); } // 5. Build auth processor if enabled ApiKeyService? apiKeyService = null; if (authEnabled) { apiKeyService = CreateApiKeyService(); routeContext.AddService(typeof(ApiKeyService), apiKeyService); } // 5a. Per-IP brute-force throttle on the ACTUAL authentication surface (review item 4.5). // Every non-exempt API request carries a key, so key-guessing can be attempted against ANY // endpoint — not just /api/auth/*. The previous gate was path-limited AND counted every request // (so it could not be applied surface-wide without throttling legitimate authenticated traffic). // This throttle instead counts key-auth FAILURES per client IP across the whole surface and locks // the IP out after Limit failures within WindowSeconds; a valid key clears the counter, so real // clients are never affected. Disabled when Limit <= 0. var authThrottleLimit = _configuration.GetValue("Tsak:Api:AuthThrottle:Limit", 10); var authThrottleWindowSec = _configuration.GetValue("Tsak:Api:AuthThrottle:WindowSeconds", 60); var authThrottleLockoutSec = _configuration.GetValue("Tsak:Api:AuthThrottle:LockoutSeconds", 120); // Client address for the throttle. The shared Kestrel host resolves X-Forwarded-For against // Tsak:Http:TrustedProxies before any consumer runs, so redbHttp.RemoteAddress already IS the // client whenever that list is set, whatever the length of the proxy chain. The older // Tsak:Api:AuthThrottle:TrustProxyHeaders flag took the right-most XFF hop itself, which is the // client only behind exactly one proxy; it stays honoured as a shim when the host list is empty, // with a warning, and is ignored when the host resolves. var hostTrustedProxies = _serviceProvider.GetService>()?.Value.TrustedProxies; var hostResolvesProxies = hostTrustedProxies?.IsEnabled == true; var legacyTrustProxyFlag = _configuration.GetValue("Tsak:Api:AuthThrottle:TrustProxyHeaders", false); var authThrottleTrustProxy = legacyTrustProxyFlag && !hostResolvesProxies; if (legacyTrustProxyFlag && hostResolvesProxies) { _logger.LogInformation( "Tsak:Api:AuthThrottle:TrustProxyHeaders is ignored: Tsak:Http:TrustedProxies is set and the host resolves the client address"); } else if (legacyTrustProxyFlag) { _logger.LogWarning( "Tsak:Api:AuthThrottle:TrustProxyHeaders is deprecated and assumes exactly ONE reverse proxy " + "(right-most X-Forwarded-For hop). Behind a chain of proxies that hop is the next proxy, not the " + "client, and every caller shares one throttle bucket. Set Tsak:Http:TrustedProxies instead"); } FailedAttemptThrottle? authThrottle = null; if (authEnabled && authThrottleLimit > 0 && apiKeyService is not null) { authThrottle = new FailedAttemptThrottle( maxAttempts: authThrottleLimit, window: TimeSpan.FromSeconds(authThrottleWindowSec), lockoutDuration: TimeSpan.FromSeconds(authThrottleLockoutSec)); } // 5b. Role enforcement (Tsak:Auth:EnforceRoles, default true when auth is on). // Runs immediately after a successful auth check and only there, so it can never // touch technical endpoints: auth-exempt paths (k8s probes under /api/health/*) // skip the whole block, and the echo / Prometheus routes have their own pipelines. var enforceRoles = _configuration.GetValue("Tsak:Auth:EnforceRoles", true); // Fail-closed by default: a key with no roles gets NO access to role-gated endpoints. (Set // Tsak:Auth:RolelessKeysAreAdmin=true only to keep pre-RBAC keys working as admin during migration.) var rolelessKeysAreAdmin = _configuration.GetValue("Tsak:Auth:RolelessKeysAreAdmin", false); RoleAuthorizationProcessor? roleAuthorizer = null; if (authEnabled && enforceRoles) { roleAuthorizer = new RoleAuthorizationProcessor(controllerRegistry, rolelessKeysAreAdmin); _logger.LogInformation( "Role enforcement enabled (roleless keys treated as admin: {Legacy})", rolelessKeysAreAdmin); } else if (authEnabled) { _logger.LogWarning( "Role enforcement disabled (Tsak:Auth:EnforceRoles=false) — any valid API key may call any endpoint"); } // 6. Add API route var echoPath = _configuration.GetValue("Tsak:Api:Echo:Path", "/api/echo"); var listenUri = $"http:{host}:{port}/{{**path}}?host={host}&port={port}&inOut=true"; var actionFilters = _serviceProvider.GetService>() ?? Enumerable.Empty(); var dispatcher = new ControllerDispatcherProcessor(controllerRegistry, routeContext, actionFilters); routeContext.AddRoutes(r => { r.From(listenUri).RouteId(ApiRouteId).Process(async (exchange, ct) => { BridgeHttpHeaders(exchange); // Only a STOPPED echo reaches this catch-all: a running one out-ranks it by path specificity. // The request used to run into the API key check and answer 401, which read as "the echo // needs a key". It needs no key, it needs starting, so say that. The exchange is stopped and // falls through: the key check below skips it, and PrepareHttpResponse still writes the body. if (RequestPathIs(exchange, echoPath)) { ApiResponse.ServiceUnavailable(exchange, $"The echo route '{EchoRouteId}' is stopped. It needs no API key, but it ships stopped: start it " + $"from the dashboard (Routes) or with POST /api/contexts/{SystemContextName}/routes/{EchoRouteId}/start."); exchange.Stop(); } if (!exchange.IsStopped && apiKeyService is not null && !IsAuthExempt(exchange, exemptPatterns)) { // Per-IP brute-force lockout on the whole auth surface (4.5). The key here is the // AuthorizeProcessor carries NO required roles, so a stopped exchange means the KEY // was missing/invalid (401) — the brute-force signal — never a role denial (403, // enforced separately below). So only genuine key-auth failures feed the throttle, // and a valid key clears the counter. var clientIp = ExtractClientIp(exchange, authThrottleTrustProxy); if (authThrottle is not null && authThrottle.IsLockedOut(clientIp)) { ApiResponse.TooManyRequests(exchange, "Too many failed authentication attempts. Try again later."); exchange.Stop(); } else { var authorizer = new AuthorizeProcessor(apiKeyService); await authorizer.Process(exchange, ct); if (authThrottle is not null) { if (exchange.IsStopped) authThrottle.RecordFailure(clientIp); // invalid/missing key else authThrottle.RecordSuccess(clientIp); // valid key clears state } } // Role check for the authenticated caller. Unreachable for auth-exempt // technical endpoints — they never enter this block. if (!exchange.IsStopped && roleAuthorizer is not null) await roleAuthorizer.Process(exchange, ct); } if (!exchange.IsStopped) await dispatcher.Process(exchange, ct); PrepareHttpResponse(exchange); }); }); // 6a. Echo route — auth-exempt liveness/debug probe. Reflects the request back as // JSON ("am I reaching the host, and what did it receive?"). It shares the main // API port: its concrete path (default /api/echo) now out-ranks the catch-all // `{**path}` dispatcher thanks to SharedHttpServerManager's specificity ordering, // so no separate port is needed. Ships with AutoStart(false): it stays stopped // until started by hand from the Routes API / dashboard, and while running its own // Process pipeline (no AuthorizeProcessor) answers it without an API key. var echoUri = $"http:{host}:{port}{echoPath}?host={host}&port={port}&inOut=true"; routeContext.AddRoutes(r => { r.From(echoUri) .RouteId(EchoRouteId) .AutoStart(false) .Process((exchange, _) => { var echo = BuildEcho(exchange); exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(echo, JsonOptions); exchange.Out.Headers["Content-Type"] = "application/json"; exchange.Out.Headers["status.code"] = 200; exchange.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; }); }); _logger.LogInformation( "Echo route 'system-echo' registered on http://{Host}:{Port}{Path} (AutoStart=false, no auth)", host, port, echoPath); // 6b. Prometheus /metrics — exposes the loopback OTel scrape listener through the // facade's Kestrel server (the Api port). No separate public port and no Windows // URL ACL: the OTel listener is loopback-only, and this route rides Kestrel which // binds sockets directly. Auth-exempt (own pipeline) and out-ranks the catch-all by // path specificity. Mounted only when the Prometheus exporter is enabled. if (_configuration.GetValue("Tsak:Metrics:Prometheus:Enabled", false)) { var metricsPort = _configuration.GetValue("Tsak:Metrics:Prometheus:Port", 9464); var scrapeUrl = $"http://localhost:{metricsPort}/metrics"; var metricsUri = $"http:{host}:{port}/metrics?host={host}&port={port}&inOut=true"; // Optional auth for /metrics (review item 4.6). Off by default: /metrics rides the Api port, // which now binds loopback by default (2.1), and Prometheus scrapers usually don't send a // key. Operators who expose the Api port externally can require a valid API key by setting // Tsak:Metrics:Prometheus:RequireAuth=true. var metricsAuth = _configuration.GetValue("Tsak:Metrics:Prometheus:RequireAuth", false) && apiKeyService is not null ? new Security.AuthorizeProcessor(apiKeyService) : null; routeContext.AddRoutes(r => { r.From(metricsUri) .RouteId("system-metrics") .Process(async (exchange, ct) => { if (metricsAuth is not null) { await metricsAuth.Process(exchange, ct); if (exchange.IsStopped) return; // 401 already written by the authorizer } exchange.Out ??= exchange.In.Clone(); try { using var resp = await MetricsClient.GetAsync(scrapeUrl, ct); exchange.Out.Body = await resp.Content.ReadAsByteArrayAsync(ct); // The HTTP consumer reads the response content type from // redbHttp.ResponseContentType (a plain "Content-Type" header is // ignored and it would otherwise default to application/json, which // Prometheus rejects). Pass the OTel exposition content type through // verbatim — it carries the `version=0.0.4` Prometheus needs. exchange.Out.Headers[HttpHeaders.ResponseContentType] = resp.Content.Headers.ContentType?.ToString() ?? "text/plain; version=0.0.4; charset=utf-8"; exchange.Out.Headers["status.code"] = (int)resp.StatusCode; exchange.Out.Headers[HttpHeaders.ResponseCode] = (int)resp.StatusCode; } catch (Exception ex) { // OTel listener not up (e.g. loopback bind was skipped) — report 503, // never throw out of the scrape route. exchange.Out.Body = System.Text.Encoding.UTF8.GetBytes($"# metrics unavailable: {ex.Message}\n"); exchange.Out.Headers[HttpHeaders.ResponseContentType] = "text/plain; charset=utf-8"; exchange.Out.Headers["status.code"] = 503; exchange.Out.Headers[HttpHeaders.ResponseCode] = 503; } }); }); _logger.LogInformation( "Prometheus metrics exposed via facade http://{Host}:{Port}/metrics (proxying loopback :{MetricsPort}, no auth)", host, port, metricsPort); } // 6c. Admin audit writer route — direct://tsak-audit → INSERT into tsak_audit_log. // Mounted only when a redb provider is configured and audit persistence is enabled; // without a database the RouteAdminAuditService is never attached and the log sink // keeps handling audit events. var auditProvider = ConfigureAuditRoute(routeContext); // 6d. Retention sweeps as first-class cron routes (Routes API/dashboard + scheduler page), // replacing the bare Quartz jobs. Must be added before Start so the cron consumers wire up. ConfigureRetentionRoutes(routeContext, auditProvider); // 7. Start await context.Start(ct); _logger.LogInformation("REST API started on http://{Host}:{Port}", host, port); // 7a. Attach the persistent audit sink now that the writer route is live. Attach is a // no-op when no provider is configured. if (auditProvider != AuditProvider.None && _serviceProvider.GetService() is RouteAdminAuditService routeAudit) { routeAudit.Attach(routeContext); } // 7b. Attach the generic broker alert channel (kafka:/amqp:/… from Tsak:Watchdog:Alerts:Endpoint). // No-op unless enabled; the target component must be registered on this context by the host. _serviceProvider.GetService()?.AttachEndpointChannel(routeContext); return context; } /// /// Adds the SQL component, registers the audit data source in the context registry, and /// mounts the direct://tsak-audit writer route. Returns the resolved provider, or /// when audit persistence is off or no database is /// configured — in which case nothing is mounted. /// private AuditProvider ConfigureAuditRoute(RouteContext routeContext) { if (!_configuration.GetValue("Tsak:Audit:Enabled", true)) return AuditProvider.None; var provider = AuditStorage.ResolveProvider(_configuration); if (provider == AuditProvider.None) return AuditProvider.None; var connStr = AuditStorage.ResolveConnectionString(_configuration, provider); if (string.IsNullOrEmpty(connStr)) { _logger.LogWarning( "Audit provider '{Provider}' configured but connection string missing — audit stays on the log sink", provider); return AuditProvider.None; } try { routeContext.AddComponent(new SqlComponent()); // Register the ADO provider factory (idempotent) and publish the data source. var invariant = AuditStorage.ProviderInvariantName(provider); if (!DbProviderFactories.GetProviderInvariantNames().Contains(invariant)) DbProviderFactories.RegisterFactory(invariant, AuditStorage.ProviderFactory(provider)); routeContext.AddToRegistry(AuditStorage.DataSourceName, (ISqlConnectionFactory)new SqlConnectionFactory( new SqlConnectionOptions { ConnectionString = connStr, ProviderName = invariant, ProviderFactory = AuditStorage.ProviderFactory(provider) })); routeContext.AddRoutes(new TsakAuditRouteBuilder(provider, Storage.TsakStorageScope.ClusterName(_configuration))); _logger.LogInformation("Admin audit writer route mounted on {Endpoint} ({Provider})", AuditStorage.AuditEndpoint, provider); return provider; } catch (Exception ex) { _logger.LogError(ex, "Failed to mount admin audit route — falling back to the log sink"); return AuditProvider.None; } } /// /// Mounts the retention sweeps as cron:// routes on the _system context (replacing the /// former bare Quartz jobs) — gated exactly as before: audit needs an active provider + a positive /// Tsak:Audit:RetentionDays; DLQ needs to be available + a positive Tsak:Dlq:RetentionDays. /// The Cron component is added only when at least one sweep is registered; the shared scheduler /// (injected into every Tsak context) is ensured so the cron jobs show on the scheduler page too. /// private void ConfigureRetentionRoutes(RouteContext routeContext, AuditProvider auditProvider) { var config = _serviceProvider.GetService(); var loggerFactory = _serviceProvider.GetService(); var audit = _serviceProvider.GetService(); var auditDays = config?.GetValue("Tsak:Audit:RetentionDays", AuditRetentionRouteBuilder.DefaultRetentionDays) ?? AuditRetentionRouteBuilder.DefaultRetentionDays; var auditOn = auditProvider != AuditProvider.None && audit is { IsAvailable: true } && auditDays > 0; var dlq = _serviceProvider.GetService(); var dlqDays = config?.GetValue("Tsak:Dlq:RetentionDays", DlqRetentionRouteBuilder.DefaultRetentionDays) ?? DlqRetentionRouteBuilder.DefaultRetentionDays; var dlqOn = dlq is { IsAvailable: true } && dlqDays > 0; if (!auditOn && !dlqOn) return; // The retention sweeps are cron routes of this context: it builds its own scheduler from the Tsak options, as // every context does; the dashboard reads the scheduler of each context, this one included. routeContext.AddComponent(new CronComponent()); if (_serviceProvider.GetService() is { } quartzOptions) routeContext.AddService(typeof(redb.Route.Quartz.QuartzSchedulerOptions), quartzOptions); if (auditOn) { routeContext.AddRoutes(new AuditRetentionRouteBuilder( audit!, auditDays, loggerFactory?.CreateLogger())); _logger.LogInformation("Audit retention route mounted (cron://{Id}, {Days}d)", AuditRetentionRouteBuilder.RouteIdName, auditDays); } if (dlqOn) { routeContext.AddRoutes(new DlqRetentionRouteBuilder( dlq!, dlqDays, loggerFactory?.CreateLogger())); _logger.LogInformation("DLQ retention route mounted (cron://{Id}, {Days}d)", DlqRetentionRouteBuilder.RouteIdName, dlqDays); } } /// /// Bridges redbHttp.* headers to route.* headers expected by ControllerDispatcherProcessor. /// internal static void BridgeHttpHeaders(IExchange exchange) { var headers = exchange.In.Headers; if (headers.TryGetValue(HttpHeaders.Path, out var path)) headers[ControllerDispatcherProcessor.PathHeader] = path; if (headers.TryGetValue(HttpHeaders.Method, out var method)) headers[ControllerDispatcherProcessor.MethodHeader] = method; // Bridge query parameters: redbHttp.QueryParam.* → query.* const string httpPrefix = "redbHttp.QueryParam."; foreach (var key in headers.Keys.Where(k => k.StartsWith(httpPrefix)).ToList()) headers[$"query.{key[httpPrefix.Length..]}"] = headers[key]; } /// /// Resolves the client IP used to key the per-IP auth throttle (review item 4.5). The address is /// redbHttp.RemoteAddress: the socket peer, or, when Tsak:Http:TrustedProxies is set, the /// client the shared Kestrel host already resolved from X-Forwarded-For against that list /// (any chain length, unparseable hop stops the walk, untrusted peer ignored). That resolution is the /// supported path; this method then has nothing to parse. /// /// is the deprecated Tsak:Api:AuthThrottle:TrustProxyHeaders /// shim, honoured only while the host list is empty: the right-most hop of X-Forwarded-For /// is taken as the client. That hop is the address the nearest proxy appended, so a client cannot /// forge it, but it is the client only behind exactly ONE proxy. Behind a chain it is the next proxy /// in line, every caller lands in that one bucket, and a valid key from anyone clears the counter for /// everyone. Falls back to the peer address, then "unknown" (so a header-less request still /// shares one bucket rather than bypassing the throttle). /// /// internal static string ExtractClientIp(IExchange exchange, bool legacyRightmostHop) { if (legacyRightmostHop) { var xff = exchange.In.getHeader("X-Forwarded-For")?.ToString(); if (!string.IsNullOrWhiteSpace(xff)) { // Deprecated single-proxy model: the right-most entry is what the one trusted proxy appended. var parts = xff.Split(','); var last = parts[^1].Trim(); if (last.Length > 0) return last; } } return exchange.In.Headers.TryGetValue(HttpHeaders.RemoteAddress, out var ip) ? ip?.ToString() ?? "unknown" : "unknown"; } /// /// Checks if the request path is exempt from authentication. /// Patterns are read from Tsak:Api:AuthExempt (default: K8s health probes /// /api/health/* and /api/health). A trailing * means prefix /// match; otherwise exact case-insensitive match. /// /// True when the request path equals , case-insensitive, a trailing slash ignored. internal static bool RequestPathIs(IExchange exchange, string path) { var requested = exchange.In.Headers.TryGetValue(HttpHeaders.Path, out var p) ? p?.ToString() : null; return requested is not null && requested.TrimEnd('/').Equals(path.TrimEnd('/'), StringComparison.OrdinalIgnoreCase); } internal static bool IsAuthExempt(IExchange exchange, IReadOnlyList patterns) { var path = exchange.In.Headers.TryGetValue(HttpHeaders.Path, out var p) ? p?.ToString() : null; if (path is null || patterns.Count == 0) return false; foreach (var raw in patterns) { if (string.IsNullOrEmpty(raw)) continue; if (raw.EndsWith('*')) { var prefix = raw.AsSpan(0, raw.Length - 1); if (path.AsSpan().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return true; } else if (path.Equals(raw, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// /// Serializes response body to JSON and maps status.code → redbHttp.ResponseCode /// so that the HTTP transport returns proper status codes and JSON content. /// internal static void PrepareHttpResponse(IExchange exchange) { if (exchange.Out is null) return; // ControllerDispatcherProcessor.WriteResult overwrites status.code to 204 for null // results, even when the controller already set a different code via ApiResponse. // Restore the intended status from ControllerErrorResponse if present. var body = exchange.Out.Body; if (body is ControllerErrorResponse errorResp) exchange.Out.Headers["status.code"] = errorResp.StatusCode; // Map status.code → redbHttp.ResponseCode for HTTP transport if (exchange.Out.Headers.TryGetValue("status.code", out var sc)) exchange.Out.Headers[HttpHeaders.ResponseCode] = sc; // Serialize non-primitive bodies to JSON bytes if (body is not null && body is not byte[] && body is not string && body is not Stream) exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(body, JsonOptions); } /// /// Builds the echo payload for the system-echo route: reflects the incoming HTTP /// request (method, path, query, content-type, remote address, body) back to the caller /// so an operator can confirm the host is reachable and see exactly what it received. /// internal static object BuildEcho(IExchange exchange) { var headers = exchange.In.Headers; string? H(string key) => headers.TryGetValue(key, out var v) ? v?.ToString() : null; // Parsed query params surface as redbHttp.QueryParam.{name}. var query = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var kv in headers) { if (kv.Key.StartsWith(HttpHeaders.QueryParamPrefix, StringComparison.Ordinal)) query[kv.Key[HttpHeaders.QueryParamPrefix.Length..]] = kv.Value?.ToString(); } // POST bodies arrive as byte[]; surface them as a string so the echo is readable. var body = exchange.In.Body switch { null => null, byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes), string s => s, var x => x.ToString() }; return new { status = "alive", method = H(HttpHeaders.Method), path = H(HttpHeaders.Path), url = H(HttpHeaders.Url), queryString = H(HttpHeaders.Query), query, contentType = H(HttpHeaders.ContentType), remoteAddress = H(HttpHeaders.RemoteAddress), body, receivedAt = DateTimeOffset.UtcNow }; } private void RegisterServices(RouteContext context, ITsakModuleRegistry registry, bool authEnabled) { context.AddService(typeof(ITsakContextManager), _contextManager); context.AddService(typeof(ITsakModuleRegistry), registry); context.AddService(typeof(IConfiguration), _configuration); // for /api/system/config // Optional services — register if available in DI TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); TryRegisterService(context); } private void TryRegisterService(RouteContext context) where T : class { var service = _serviceProvider.GetService(typeof(T)) as T; if (service is not null) context.AddService(typeof(T), service); } private ApiKeyService CreateApiKeyService() { var secret = _configuration["Tsak:Auth:Secret"]; if (string.IsNullOrWhiteSpace(secret)) throw new InvalidOperationException( "Tsak:Auth:Secret must be configured when auth is enabled. Minimum 16 characters."); var store = _serviceProvider.GetService() ?? new ConfigApiKeyStore(_configuration); var userProvider = _serviceProvider.GetService(); var svc = new ApiKeyService(store, System.Text.Encoding.UTF8.GetBytes(secret), userProvider); // Revocation-sensitivity knobs (review item 2.7). CacheTtl is the full lifetime; the shorter // RevocationCheckInterval bounds how long a key revoked on another node stays accepted here. var cacheTtl = _configuration.GetValue("Tsak:Auth:CacheTtlSeconds", 300); var revoCheck = _configuration.GetValue("Tsak:Auth:RevocationCheckSeconds", 30); svc.CacheTtl = TimeSpan.FromSeconds(cacheTtl <= 0 ? 300 : cacheTtl); svc.RevocationCheckInterval = TimeSpan.FromSeconds(revoCheck < 0 ? 30 : revoCheck); return svc; } } Path: redb-tsak/src/redb.Tsak.Core/Services/TsakContextManager.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/Services/TsakContextManager.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Quartz; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Tsak.Contracts; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Monitoring; using redb.Tsak.Core.Modules; using redb.Route.Extensions; using redb.Tsak.Core.Controllers; using redb.Route.RedbCore.Extensions; namespace redb.Tsak.Core.Services; /// /// Manages lifecycle of route contexts. Supports named (config-driven) and anonymous (dynamic) contexts. /// Based on lt.tsak RouteContextManager, adapted for redb.Route. /// public class TsakContextManager : ITsakContextManager { private readonly ConcurrentDictionary _contexts = new(StringComparer.OrdinalIgnoreCase); private readonly ITsakStateStore _stateStore; private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly LifecycleAuditService? _auditService; private readonly SharedAssemblyLoader? _sharedLoader; private readonly IEnumerable _contextCustomizers; // Serializes lifecycle operations (start/stop/restart/remove) to prevent // races between API calls and hot-reload context recreation. private readonly SemaphoreSlim _lifecycleLock = new(1, 1); // Mini-DI containers for named redb instances, keyed by context name. // Must be disposed when context is removed. private readonly ConcurrentDictionary> _namedRedbContainers = new(StringComparer.OrdinalIgnoreCase); // What was actually registered, for the storage page. The context registry cannot be enumerated, and // an instance whose creation failed must not appear in a list that offers to query it. private readonly ConcurrentDictionary> _namedRedbInstances = new(StringComparer.OrdinalIgnoreCase); /// Named redb instances whose start went wrong, for the health check. internal NamedRedbStartFailures NamedRedbStartFailures { get; } = new(); // The save interceptors modules subscribed through their context, removed with the context. private readonly ConcurrentDictionary _saveInterceptors = new(StringComparer.OrdinalIgnoreCase); private const string AutoStartKeyPrefix = "context:autostart:"; public TsakContextManager( ITsakStateStore stateStore, IConfiguration configuration, ILogger logger, IEnumerable contextCustomizers, LifecycleAuditService? auditService = null, SharedAssemblyLoader? sharedLoader = null) { _stateStore = stateStore; _configuration = configuration; _logger = logger; _contextCustomizers = contextCustomizers; _auditService = auditService; _sharedLoader = sharedLoader; // Before any module context exists: a module in markup names its ADO provider and cannot register one. Audit.TsakSqlDialect.RegisterProviderFactories(); } public IRouteContext CreateContext(string contextName, IServiceProvider serviceProvider, IDictionary configuration) { // Serialize with start/stop/restart/remove (review item 3.1). CreateContext mutates both // _contexts and _namedRedbContainers; running it outside _lifecycleLock let a concurrent // RemoveContextAsync TryRemove *before* the TryAdd here, leaving an orphaned context and a // leaked named-redb container the remover believed was gone. Lock order is always // coordinator-per-context → _lifecycleLock (no lifecycle path re-enters the coordinator), so it // cannot invert; no lifecycle method calls CreateContext, so there is no re-entrancy either. _lifecycleLock.Wait(); try { // Fail fast under the lock, before building anything or touching _namedRedbContainers. if (_contexts.ContainsKey(contextName)) throw new InvalidOperationException($"Context '{contextName}' already exists."); return CreateContextCore(contextName, serviceProvider, configuration); } finally { _lifecycleLock.Release(); } } /// /// The route engine options of a module context: the host's RedbRoute section (consumer start retry, thread /// pool profiles, attachments, processing timeout, ...), bound afresh for each context so a context never shares /// a mutable options object with another. The REST API's _system context keeps the defaults: a processing /// timeout or stream caching set for the modules is not the API's. An invalid value fails the context's creation. /// private RouteEngineOptions? EngineOptions(string contextName) => contextName == SystemContextBuilder.SystemContextName ? null : _configuration.GetSection(RouteEngineOptions.SectionName).Get(); /// Builds and publishes a context. Caller MUST hold . private IRouteContext CreateContextCore(string contextName, IServiceProvider serviceProvider, IDictionary configuration) { var loggerFactory = serviceProvider.GetService(); var context = new RouteContext(serviceProvider, contextName, loggerFactory, EngineOptions(contextName)); // A module cannot reach the host's DI, so its save interceptors go through the context and live as long as it. var saveInterceptorRegistry = serviceProvider.GetService(); var saveInterceptors = saveInterceptorRegistry is null ? null : new ContextSaveInterceptors(saveInterceptorRegistry, contextName); if (saveInterceptors is not null) context.AddService(typeof(ITsakSaveInterceptors), saveInterceptors); // The checkpoint DLQ goes on when the context starts (InstallCheckpointDlq), after the module configured // its context: an error handler of the module's own then runs after the capture instead of colliding with it. // tsak-dlq: is there from the start, for the OnException bodies that dead-letter a failure they took. if (serviceProvider.GetService() is { } dlq) context.AddComponent(new Dlq.TsakDlqComponent(contextName, dlq)); // Register shared components (connectors, shared models) from Libs/shared/ if (_sharedLoader is { LoadedAssemblies.Count: > 0 }) context.AddComponents(_sharedLoader.LoadedAssemblies.ToArray()); // The Quartz scheduler options, not a scheduler: the context builds its own with its first cron/qtimer route // (redb.Route.Quartz, a scheduler per context as Apache Camel's per CamelContext) — its own job namespace and, // clustered, a cluster of the nodes that run this context. if (serviceProvider.GetService() is { } quartzOptions) context.AddService(typeof(redb.Route.Quartz.QuartzSchedulerOptions), quartzOptions); // Run context customizers (e.g. cluster policy factory registration) foreach (var customizer in _contextCustomizers) { try { customizer.CustomizeAsync(context, serviceProvider, contextName) .ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { _logger.LogWarning(ex, "Context customizer {Customizer} failed for {Context}", customizer.GetType().Name, contextName); } } foreach (var (key, value) in configuration) { if (value != null) context.SetProperty(key, value); } // sql: steps take dataSource=redb (the host's redb service) and dataSource=redb: (a named instance of the // "Redb" section below). After the customizers: a data source one of them put under "redb" is left as it is. redb.Route.RedbCore.Sql.RedbSqlDataSourceExtensions.AddRedbSqlDataSource(context); // Register named IRedbService instances from "Redb" config section RegisterNamedRedbServices(context, contextName, configuration, saveInterceptorRegistry); // Wire route-level state persistence callback context.OnBeforeRoutesStart = async routes => { // Load suspended keys: routes manually stopped should remain stopped var suspendedPrefix = RoutesController.RouteSuspendedKeyPrefix + contextName + ":"; var suspended = await _stateStore.GetByPrefixAsync(suspendedPrefix); // Load started keys: routes manually started (with definition AutoStart=false) should start var startedPrefix = RoutesController.RouteStartedKeyPrefix + contextName + ":"; var started = await _stateStore.GetByPrefixAsync(startedPrefix); if (suspended.Count == 0 && started.Count == 0) return; foreach (var route in routes) { var suspendedKey = RoutesController.RouteSuspendedKey(contextName, route.RouteId); var startedKey = RoutesController.RouteStartedKey(contextName, route.RouteId); if (suspended.ContainsKey(suspendedKey)) { route.AutoStart = false; _logger.LogInformation("Route {RouteId} in context {Context} suspended by persisted state", route.RouteId, contextName); } else if (started.ContainsKey(startedKey)) { route.AutoStart = true; _logger.LogInformation("Route {RouteId} in context {Context} started by persisted state", route.RouteId, contextName); } } // Clean orphan keys for routes that no longer exist var routeIds = new HashSet(routes.Select(r => r.RouteId)); foreach (var key in suspended.Keys) { var routeId = key[(suspendedPrefix.Length)..]; if (!routeIds.Contains(routeId)) { await _stateStore.RemoveAsync(key); _logger.LogDebug("Cleaned orphan route suspended key: {Key}", key); } } foreach (var key in started.Keys) { var routeId = key[(startedPrefix.Length)..]; if (!routeIds.Contains(routeId)) { await _stateStore.RemoveAsync(key); _logger.LogDebug("Cleaned orphan route started key: {Key}", key); } } }; if (!_contexts.TryAdd(contextName, context)) { saveInterceptors?.Dispose(); context.Dispose(); throw new InvalidOperationException($"Context '{contextName}' already exists."); } if (saveInterceptors is not null) _saveInterceptors[contextName] = saveInterceptors; _auditService?.RegisterContext(contextName, context); _logger.LogInformation("Created context {Context}", contextName); return context; } public IRouteContext? GetContext(string contextName) => _contexts.GetValueOrDefault(contextName); public IReadOnlyList<(string Name, IRouteContext Context)> GetAllContexts() => _contexts.Select(kv => (kv.Key, kv.Value)).ToList(); public async Task StartContextAsync(string contextName, bool ignoreAutoStart = false) { await _lifecycleLock.WaitAsync().ConfigureAwait(false); try { await StartContextCoreAsync(contextName, ignoreAutoStart); } finally { _lifecycleLock.Release(); } } public async Task StopContextAsync(string contextName, bool setAutoStartFalse = true, CancellationToken ct = default) { await _lifecycleLock.WaitAsync(ct).ConfigureAwait(false); try { return await StopContextCoreAsync(contextName, setAutoStartFalse, ct); } finally { _lifecycleLock.Release(); } } public async Task RestartContextAsync(string contextName, CancellationToken ct = default) { await _lifecycleLock.WaitAsync(ct).ConfigureAwait(false); try { var stopResult = await StopContextCoreAsync(contextName, setAutoStartFalse: false, ct: ct); await _stateStore.SetAsync(AutoStartKeyPrefix + contextName, "true"); await StartContextCoreAsync(contextName); return new ContextActionResponse { Name = contextName, Status = "Running", InflightBefore = stopResult.InflightBefore, InflightAfter = stopResult.InflightAfter, DrainTimeMs = stopResult.DrainTimeMs }; } finally { _lifecycleLock.Release(); } } public async Task RemoveContextAsync(string contextName, bool preserveState = false) { await _lifecycleLock.WaitAsync().ConfigureAwait(false); try { await RemoveContextCoreAsync(contextName, preserveState); } finally { _lifecycleLock.Release(); } } // ── Core implementations (caller must hold _lifecycleLock) ── private async Task StartContextCoreAsync(string contextName, bool ignoreAutoStart = false) { if (!_contexts.TryGetValue(contextName, out var context)) throw new InvalidOperationException($"Context '{contextName}' not found."); if (context.IsStarted) { _logger.LogDebug("Context {Context} already started", contextName); return; } if (!ignoreAutoStart && !await ShouldAutoStartAsync(contextName).ConfigureAwait(false)) { _logger.LogInformation("Context {Context} skipped (autoStart=false)", contextName); return; } if (ignoreAutoStart && !IsAnonymousContext(contextName)) await _stateStore.SetAsync(AutoStartKeyPrefix + contextName, "true"); InstallCheckpointDlq(contextName, context); await context.Start(CancellationToken.None); _auditService?.RecordContextEvent(contextName, LifecycleEventType.ContextStarted); _logger.LogInformation("Started context {Context}", contextName); WarnAboutRouteIdsTheApiCannotAddress(contextName, context); } /// /// Makes the checkpoint DLQ the context's error handler: a failure no OnException took, of a route that /// left a replay checkpoint, is dead-lettered. The module's own error handler (its <deadLetterChannel>, /// or one set in code) runs after the capture. Once per context — a restart finds it in place. Resolved from the /// context's provider (not ctor-injected) to avoid a TsakContextManager ↔ DlqService circular dependency. /// private static void InstallCheckpointDlq(string contextName, IRouteContext context) { if (context.ErrorHandler is Dlq.CheckpointDlqHandler) return; if (context.GetServiceProvider()?.GetService() is not { } dlq) return; context.ErrorHandler = new Dlq.CheckpointDlqHandler(contextName, dlq, next: context.ErrorHandler); } /// /// Names the routes the management API cannot address. A route that is never given an id through /// .RouteId(...) gets one derived from its from-URI, slashes included, and the API addresses a route /// by a path segment: /api/contexts/{ctx}/routes/{routeId}/start. Kestrel passes such a segment on /// with %2F still encoded, the lookup misses, and start, stop and detail all answer 404; in the /// dashboard the route is a row of URI noise whose every button fails. The route itself runs exactly as /// declared — only managing it from outside is impossible, hence a warning and not a refusal to start. /// private void WarnAboutRouteIdsTheApiCannotAddress(string contextName, IRouteContext context) { if (context is not RouteContext routeContext) return; foreach (var route in routeContext.Routes) { if (!route.RouteId.Contains('/')) continue; _logger.LogWarning( "Route '{RouteId}' of context {Context} cannot be managed through the API or the dashboard: " + "its id carries a '/', and a route is addressed by a path segment. Give the route an " + "explicit id with .RouteId(...)", route.RouteId, contextName); } } private async Task StopContextCoreAsync(string contextName, bool setAutoStartFalse = true, CancellationToken ct = default) { if (!_contexts.TryGetValue(contextName, out var context)) throw new InvalidOperationException($"Context '{contextName}' not found."); if (!context.IsStarted) return new ContextActionResponse { Name = contextName, Status = "Stopped" }; var routeCtx = context as RouteContext; var inflightBefore = routeCtx?.InflightRepository.Count ?? 0; var sw = Stopwatch.StartNew(); await context.Stop(ct); sw.Stop(); var inflightAfter = routeCtx?.InflightRepository.Count ?? 0; if (inflightBefore > 0) { _logger.LogInformation( "Context {Context} stopped: drained {Drained}/{Total} exchanges in {Elapsed}ms", contextName, inflightBefore - inflightAfter, inflightBefore, sw.ElapsedMilliseconds); } if (setAutoStartFalse && !IsAnonymousContext(contextName)) await _stateStore.SetAsync(AutoStartKeyPrefix + contextName, "false"); _logger.LogInformation("Stopped context {Context} (autoStart persisted: {Persist})", contextName, setAutoStartFalse); _auditService?.RecordContextEvent(contextName, LifecycleEventType.ContextStopped); return new ContextActionResponse { Name = contextName, Status = "Stopped", InflightBefore = inflightBefore, InflightAfter = inflightAfter, DrainTimeMs = sw.ElapsedMilliseconds }; } private async Task RemoveContextCoreAsync(string contextName, bool preserveState = false) { if (!_contexts.TryRemove(contextName, out var context)) return; if (context.IsStarted) await context.Stop(CancellationToken.None); // The module's save interceptors go before anything else of the context: the registry must hold no reference // to a type of the module by the time its AssemblyLoadContext unloads. if (_saveInterceptors.TryRemove(contextName, out var saveInterceptors)) saveInterceptors.Dispose(); _namedRedbInstances.TryRemove(contextName, out _); NamedRedbStartFailures.Clear(contextName); // Dispose named redb mini-containers before context disposal if (_namedRedbContainers.TryRemove(contextName, out var containers)) { foreach (var container in containers) { try { container.Dispose(); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to dispose named redb container for context {Context}", contextName); } } _logger.LogDebug("Disposed {Count} named redb container(s) for context {Context}", containers.Count, contextName); } context.Dispose(); if (!preserveState && !IsAnonymousContext(contextName)) { await _stateStore.RemoveAsync(AutoStartKeyPrefix + contextName); await CleanupRouteSuspendedKeysAsync(contextName); } _auditService?.RecordContextEvent(contextName, LifecycleEventType.ContextRemoved); _logger.LogInformation("Removed context {Context}", contextName); } public bool ShouldAutoStart(string contextName) => ShouldAutoStartAsync(contextName).GetAwaiter().GetResult(); public async Task ShouldAutoStartAsync(string contextName) { // First check state store (persisted override) var persisted = await _stateStore.GetAsync(AutoStartKeyPrefix + contextName).ConfigureAwait(false); if (persisted != null) return string.Equals(persisted, "true", StringComparison.OrdinalIgnoreCase); // Then the host's own word for this context: appsettings Tsak:Contexts:{name}:AutoStart overrides the module's files var configValue = _configuration[$"Tsak:Contexts:{contextName}:AutoStart"]; if (configValue != null) return string.Equals(configValue, "true", StringComparison.OrdinalIgnoreCase); // Then the context's merged configuration: the package's {Module}.config.json, the file beside it, context.json, // the default section and the Override, in the layer order. A package that says AutoStart=false is not started. if (GetContext(contextName)?.GetProperty("AutoStart") is { } merged && bool.TryParse(merged.ToString(), out var mergedAutoStart)) return mergedAutoStart; // Default context config var defaultAutoStart = _configuration["Tsak:Contexts:default:AutoStart"]; if (defaultAutoStart != null) return string.Equals(defaultAutoStart, "true", StringComparison.OrdinalIgnoreCase); return true; // default: autoStart } /// Remove orphaned autoStart keys for anonymous contexts from StateStore. public async Task CleanupAnonymousStatesAsync() { var entries = await _stateStore.GetByPrefixAsync(AutoStartKeyPrefix); foreach (var key in entries.Keys) { if (key.Contains("_dyn_", StringComparison.Ordinal)) { await _stateStore.RemoveAsync(key); _logger.LogDebug("Cleaned up orphaned anonymous state key: {Key}", key); } } } /// Remove all route:suspended keys for a given context. private async Task CleanupRouteSuspendedKeysAsync(string contextName) { var prefix = RoutesController.RouteSuspendedKeyPrefix + contextName + ":"; var entries = await _stateStore.GetByPrefixAsync(prefix); foreach (var key in entries.Keys) { await _stateStore.RemoveAsync(key); _logger.LogDebug("Cleaned route suspended key on context removal: {Key}", key); } } private static bool IsAnonymousContext(string contextName) => contextName.Contains("_dyn_", StringComparison.Ordinal); /// /// Reads the "Redb" section from context configuration and registers named IRedbService instances. /// Each named instance gets its own mini-DI container tracked for disposal. /// /// EnsureCreated gating: only the instance whose name matches /// RedbInstanceName (top-level, or Identity:RedbInstanceName as a /// module fallback) is allowed to honor EnsureCreated=true and run /// IRedbService.InitializeAsync at registration. All other /// registered instances are still created (so callers can resolve them via /// "redb-factory:{name}") but their EnsureCreated is forced to /// false — they do NOT open a connection at startup. This prevents /// dev-time toggles like identity-pg/identity-sqlite from /// failing the host with a connect-refused warning when the non-active /// backend is offline. /// /// private void RegisterNamedRedbServices(IRouteContext context, string contextName, IDictionary configuration, redb.Core.Interception.IRedbSaveInterceptorRegistry? saveInterceptorRegistry) { if (!configuration.TryGetValue("Redb", out var redbSection) || redbSection is not IDictionary redbDict) return; var activeRedbName = ResolveActiveRedbName(configuration); NamedRedbStartFailures.Clear(contextName); var containers = new List(); var described = new List(); foreach (var (name, entryRaw) in redbDict) { if (entryRaw is not IDictionary entryConfig) { _logger.LogWarning("Named redb '{Name}' in context {Context}: config is not a dictionary, skipping", name, contextName); continue; } var isActive = activeRedbName is not null && string.Equals(name, activeRedbName, StringComparison.OrdinalIgnoreCase); IDictionary effectiveConfig = entryConfig; if (!isActive) { // Non-active instance — force EnsureCreated=false so InitializeAsync // (and the connect attempt it implies) is skipped. The container is // still built and 'redb-factory:{name}' is still resolvable; the // underlying provider opens its connection lazily at first actual use. var overrideConfig = new Dictionary(entryConfig, StringComparer.OrdinalIgnoreCase); overrideConfig["EnsureCreated"] = false; effectiveConfig = overrideConfig; _logger.LogInformation( "Named redb '{Name}' in context {Context}: NOT active (active='{Active}') — registered without schema bootstrap", name, contextName, activeRedbName ?? ""); } try { var (service, container) = RedbInstanceFactory.Create( name, effectiveConfig, _logger, saveInterceptorRegistry, onBootstrapFailure: ex => NamedRedbStartFailures.Report(contextName, name.TrimStart('#'), registered: true, ex)); // Register the scope factory so that named services can be resolved // per-exchange (thread-safe). The singleton is kept as a fallback for // non-exchange callers (seed, diagnostics). var scopeFactory = container.GetRequiredService(); var cleanName = name.TrimStart('#'); context.AddToRegistry("redb-factory:" + cleanName, scopeFactory); context.RegisterRedbService(name, service); containers.Add(container); described.Add(RedbInstanceDescription.Describe( cleanName, contextName, entryConfig.TryGetValue("Provider", out var providerValue) ? providerValue?.ToString() : null, entryConfig.TryGetValue("ConnectionString", out var connValue) ? connValue?.ToString() : null, entryConfig.TryGetValue("UsePro", out var proValue) && proValue is true or "true" or "True" or "TRUE", isActive)); _logger.LogInformation("Registered named IRedbService '{Name}' for context {Context}", name, contextName); } catch (Exception ex) when (RedbInstanceFactory.IsStartRefusal(ex)) { _logger.LogError(ex, "Named redb '{Name}' in context {Context} is not registered: its database refused the start", name, contextName); NamedRedbStartFailures.Report(contextName, name.TrimStart('#'), registered: false, ex); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to create named IRedbService '{Name}' for context {Context}, skipping", name, contextName); } } if (containers.Count > 0) _namedRedbContainers[contextName] = containers; if (described.Count > 0) _namedRedbInstances[contextName] = described; } /// public IReadOnlyList GetNamedRedbInstances() => _namedRedbInstances .SelectMany(entry => entry.Value) .OrderBy(i => i.ContextName, StringComparer.OrdinalIgnoreCase) .ThenBy(i => i.Name, StringComparer.OrdinalIgnoreCase) .ToArray(); /// /// Picks the active redb instance name for a context. Checks top-level /// RedbInstanceName first (the canonical location used by the HTTP facade /// and merged from Contexts.default.RedbInstanceName), then falls back to /// Identity:RedbInstanceName for the redb.Identity module convention. /// Returns null when neither is set: then no entry is active, and every instance is /// registered without the schema bootstrap, whatever its EnsureCreated says. /// private static string? ResolveActiveRedbName(IDictionary configuration) { if (configuration.TryGetValue("RedbInstanceName", out var top) && top?.ToString() is { } topStr && !string.IsNullOrWhiteSpace(topStr)) return topStr; if (configuration.TryGetValue("Identity", out var identitySection) && identitySection is IDictionary identityDict && identityDict.TryGetValue("RedbInstanceName", out var nested) && nested?.ToString() is { } nestedStr && !string.IsNullOrWhiteSpace(nestedStr)) return nestedStr; return null; } } Path: redb-tsak/src/redb.Tsak.Core/Services/TsakCoordinator.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/Services/TsakCoordinator.cs ---- using System.Collections.Concurrent; using System.Threading.Channels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Contracts; namespace redb.Tsak.Core.Services; /// /// Orchestrates module-to-context mapping. Subscribes to registry events and /// creates/updates/removes contexts accordingly. /// Two context types: Named (from config, multi-module) and Anonymous (one module each). /// Based on lt.tsak ModuleContextCoordinator. /// public class TsakCoordinator : ITsakCoordinator, IDisposable { private readonly ITsakContextManager _contextManager; private readonly IConfiguration _configuration; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; // Registry events are EventHandler (synchronous, void). Instead of handling them as // fire-and-forget `async void` (unordered, unobservable, and impossible to wait on), each event is // ENQUEUED here and a single background consumer AWAITS the handler in FIFO order (review items // 1.7/3.8). This gives true async processing with no `async void`, deterministic ordering, and a // WaitForIdleAsync drain so startup/tests can wait for topology changes to finish. private readonly Channel _eventQueue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); private Task? _consumerTask; private int _initialized; // _pending and _idleSignal are guarded by _idleLock together: the busy↔idle transition and the // signal reset/complete MUST be atomic, or a lost-wakeup hangs WaitForIdleAsync (the consumer could // complete a signal a concurrent Enqueue just swapped out, stranding the real waiter's signal). private readonly object _idleLock = new(); private int _pending; private TaskCompletionSource _idleSignal = CreateIdleSignal(completed: true); private sealed record QueuedEvent(Func Work, string EventName, string Subject); // module → context name mapping private readonly ConcurrentDictionary _moduleContextMap = new(StringComparer.OrdinalIgnoreCase); // contextName → first moduleName that claimed it (for collision detection) private readonly ConcurrentDictionary _claimedContextNames = new(StringComparer.OrdinalIgnoreCase); // Per-context lock: serializes RecreateContextWithModulesAsync and ProcessModuleRemovedAsync // to prevent races when multiple ModuleAdded events fire concurrently for the same context. private readonly ConcurrentDictionary _contextLocks = new(StringComparer.OrdinalIgnoreCase); private ITsakModuleRegistry? _registry; public TsakCoordinator( ITsakContextManager contextManager, IConfiguration configuration, IServiceProvider serviceProvider, ILogger logger) { _contextManager = contextManager; _configuration = configuration; _serviceProvider = serviceProvider; _logger = logger; } public void Initialize(ITsakModuleRegistry registry) { // Idempotent: subscribe exactly once, even if Initialize is called again with the same registry // — otherwise events would be handled (and processed) multiple times. if (Interlocked.Exchange(ref _initialized, 1) == 1) return; _registry = registry; // Registry events (synchronous EventHandler) are ENQUEUED, not handled inline as async void. // A single background consumer awaits each handler in order — see the field comment above. registry.ModuleAdded += (_, module) => Enqueue(() => ProcessModuleAddedAsync(module), "ModuleAdded", module.ModuleName); registry.ModuleRemoved += (_, name) => Enqueue(() => ProcessModuleRemovedAsync(name), "ModuleRemoved", name); registry.ModuleUpdated += (_, module) => Enqueue(() => ProcessModuleUpdatedAsync(module), "ModuleUpdated", module.ModuleName); registry.ModulesBatchAdded += (_, modules) => Enqueue(() => ProcessBatchAsync(modules), "ModulesBatchAdded", $"{modules.Count} modules"); _consumerTask ??= Task.Run(ConsumeEventsAsync); _logger.LogInformation("Coordinator initialized, subscribed to registry events"); } /// /// Waits until every enqueued registry-event has been processed. Lets startup and tests wait for /// topology changes to settle instead of racing the (formerly fire-and-forget) handlers. /// public async Task WaitForIdleAsync(CancellationToken ct = default) { while (true) { Task idleTask; lock (_idleLock) { if (_pending == 0) return; // While _pending > 0 the signal is always the uncompleted one installed on the last // idle→busy transition, so this captures a genuinely-pending task (no busy-spin). idleTask = _idleSignal.Task; } await idleTask.WaitAsync(ct).ConfigureAwait(false); } } /// Enqueues a registry-event handler for the single background consumer to await in order. private void Enqueue(Func work, string eventName, string subject) { // Mark busy BEFORE writing, so a WaitForIdleAsync called right after enqueuing cannot observe // a stale "idle" signal. The transition and the signal swap are one atomic step under the lock. lock (_idleLock) { if (_pending++ == 0) _idleSignal = CreateIdleSignal(completed: false); } if (!_eventQueue.Writer.TryWrite(new QueuedEvent(work, eventName, subject))) { // Queue already completed (coordinator disposed) — undo the pending bump. lock (_idleLock) { if (--_pending == 0) _idleSignal.TrySetResult(); } } } /// Single background consumer: awaits each queued handler in FIFO order, catching+logging /// per item so one bad module can never crash the node or stall the queue. private async Task ConsumeEventsAsync() { await foreach (var item in _eventQueue.Reader.ReadAllAsync().ConfigureAwait(false)) { try { await item.Work().ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Coordinator '{Event}' handler failed for '{Subject}' — node stays up, this topology change was skipped", item.EventName, item.Subject); } finally { lock (_idleLock) { if (--_pending == 0) _idleSignal.TrySetResult(); // safe under lock: RunContinuationsAsynchronously } } } } private static TaskCompletionSource CreateIdleSignal(bool completed) { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); if (completed) tcs.TrySetResult(); return tcs; } /// public void Dispose() { _eventQueue.Writer.TryComplete(); // Best-effort drain so in-flight topology changes finish; never block shutdown indefinitely. try { _consumerTask?.Wait(TimeSpan.FromSeconds(5)); } catch { /* shutdown — ignore */ } GC.SuppressFinalize(this); } public async Task ProcessBatchAsync(IReadOnlyList modules) { _logger.LogInformation("Processing batch of {Count} modules", modules.Count); // Group by target context (named or anonymous) var namedContextModules = new Dictionary>(StringComparer.OrdinalIgnoreCase); var anonymousModules = new List(); foreach (var module in modules) { var (contextName, isNamed) = DetermineContextForModule(module); if (isNamed) { if (!TryClaimContextName(contextName, module.ModuleName)) continue; // collision logged — skip this module, keep processing the batch if (!namedContextModules.TryGetValue(contextName, out var list)) { list = []; namedContextModules[contextName] = list; } list.Add(module); } else { anonymousModules.Add(module); } } // Collect all context names and their dependencies for topological ordering var allContextEntries = new List<(string Name, IReadOnlyList Modules, bool IsAnonymous)>(); // A named context is recreated with its FULL membership: the batch modules replace their // same-named predecessors and the modules already running there stay — the same rule as // GetAllModulesForNamedContext on the single-module path. A package reload hands the coordinator // only that package's modules; recreating the context from the batch alone dropped the modules // another package keeps in the same named context. At startup nothing runs yet, so the // membership is exactly the batch. foreach (var (contextName, contextModules) in namedContextModules) { var members = GetModulesInContext(contextName).ToList(); foreach (var module in contextModules) { var index = members.FindIndex(m => string.Equals(m.ModuleName, module.ModuleName, StringComparison.OrdinalIgnoreCase)); if (index >= 0) members[index] = module; else members.Add(module); } allContextEntries.Add((contextName, members, false)); } foreach (var module in anonymousModules) { var contextName = GenerateAnonymousContextName(module.ModuleName); allContextEntries.Add((contextName, [module], true)); } // Topological sort by Dependencies from config var ordered = TopologicalSort(allContextEntries); // The set is replaced as a whole: every context in it stops first, in reverse dependency order, and only // then do they come up again, in dependency order. Recreated one at a time — stop, create, start, next — // a facade stayed up while the context it forwards to was being replaced (dependency declared), or a new // facade came up before its backend (not declared); both windows took requests that could only fail. // Now no context runs while one it depends on does not, and for the length of a reload the set is plainly // unavailable. Camel stops routes in the reverse of their startup order for the same reason. The locks of // the whole set are held throughout, taken in name order so that two reloads cannot lock each other out. var locks = ordered .Select(e => e.Name) .Distinct(StringComparer.OrdinalIgnoreCase) .OrderBy(n => n, StringComparer.OrdinalIgnoreCase) .Select(n => _contextLocks.GetOrAdd(n, _ => new SemaphoreSlim(1, 1))) .ToList(); var taken = 0; try { foreach (var contextLock in locks) { await contextLock.WaitAsync().ConfigureAwait(false); taken++; } for (var i = ordered.Count - 1; i >= 0; i--) await RemoveContextIfPresentAsync(ordered[i].Name).ConfigureAwait(false); var failures = new List(); foreach (var (contextName, contextModules, _) in ordered) failures.AddRange(await BringUpContextCoreAsync(contextName, contextModules).ConfigureAwait(false)); return new ModuleActivationReport(failures); } finally { for (var i = 0; i < taken; i++) locks[i].Release(); } } public async Task ProcessModuleAddedAsync(ITsakModule module) { _logger.LogInformation("Processing added module {Module}", module.ModuleName); var (contextName, isNamed) = DetermineContextForModule(module); if (isNamed) { // Collision logged — skip this module (node stays up). Not reported as an activation failure. if (!TryClaimContextName(contextName, module.ModuleName)) return ModuleActivationReport.Success; // Named context: recreate with ALL configured modules (existing + new) var allModulesForContext = GetAllModulesForNamedContext(contextName, module); return new ModuleActivationReport(await RecreateContextWithModulesAsync(contextName, allModulesForContext)); } // Anonymous: create dedicated context contextName = GenerateAnonymousContextName(module.ModuleName); return new ModuleActivationReport(await RecreateContextWithModulesAsync(contextName, [module])); } public async Task ProcessModuleRemovedAsync(string moduleName) { _logger.LogInformation("Processing removed module {Module}", moduleName); if (!_moduleContextMap.TryRemove(moduleName, out var contextName)) return; var existingContext = _contextManager.GetContext(contextName); if (existingContext == null) return; // If anonymous context: just remove it if (IsAnonymousContext(contextName)) { await _contextManager.RemoveContextAsync(contextName); return; } // Named context: recreate without the removed module var remainingModules = GetModulesInContext(contextName) .Where(m => !string.Equals(m.ModuleName, moduleName, StringComparison.OrdinalIgnoreCase)) .ToList(); if (remainingModules.Count == 0) { await _contextManager.RemoveContextAsync(contextName); // Release the context name claim if no modules left _claimedContextNames.TryRemove(contextName, out _); } else { await RecreateContextWithModulesAsync(contextName, remainingModules); } } public async Task ProcessModuleUpdatedAsync(ITsakModule module) { _logger.LogInformation("Processing updated module {Module} v{Version}", module.ModuleName, module.Version); if (!_moduleContextMap.TryGetValue(module.ModuleName, out var contextName)) { // Treat as new await ProcessModuleAddedAsync(module); return; } // Recreate context with updated module if (IsAnonymousContext(contextName)) { await RecreateContextWithModulesAsync(contextName, [module]); } else { var allModules = GetAllModulesForNamedContext(contextName, module); await RecreateContextWithModulesAsync(contextName, allModules); } } /// /// Stops, removes, recreates, initializes all modules, and starts a context. /// Serialized per context name to prevent races from concurrent ModuleAdded events. /// private async Task> RecreateContextWithModulesAsync( string contextName, IReadOnlyList modules) { var contextLock = _contextLocks.GetOrAdd(contextName, _ => new SemaphoreSlim(1, 1)); await contextLock.WaitAsync().ConfigureAwait(false); try { return await RecreateContextWithModulesCoreAsync(contextName, modules).ConfigureAwait(false); } finally { contextLock.Release(); } } private async Task> RecreateContextWithModulesCoreAsync( string contextName, IReadOnlyList modules) { await RemoveContextIfPresentAsync(contextName).ConfigureAwait(false); return await BringUpContextCoreAsync(contextName, modules).ConfigureAwait(false); } private async Task RemoveContextIfPresentAsync(string contextName) { if (_contextManager.GetContext(contextName) is not null) await _contextManager.RemoveContextAsync(contextName, preserveState: true).ConfigureAwait(false); } /// /// Creates, initializes and starts a context that is not running. The caller holds the context's lock and has /// already taken down whatever ran under the name — alone for a single module, or as part of a whole set. /// private async Task> BringUpContextCoreAsync( string contextName, IReadOnlyList modules) { var contextConfig = GetContextConfig(contextName, modules); var context = _contextManager.CreateContext(contextName, _serviceProvider, contextConfig); // Type names in the modules' routes (bean:, , outputClass) resolve to the modules' own classes // first. Registered before the modules initialize, so one of them may still put a resolver of its own. context.AddService(typeof(redb.Route.Abstractions.IBeanTypeResolver), Modules.ModuleTypeResolver.For(modules)); // The redb schemes the modules read go into the cache before they start (only read, nothing synced). The // service is the one a module gets from context.GetRedbService(). if ((context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(redb.Core.IRedbService))) is redb.Core.IRedbService redb) await Modules.ModuleSchemeWarmup.WarmAsync(redb, modules, _logger).ConfigureAwait(false); // Initialize all modules in this context. A module's exception is logged and swallowed — one bad // module must not crash the node or keep the rest of its context down — but it is REPORTED, so a // hot swap, a package reload or a cluster assignment can react (roll back, mark Failed). List? failures = null; foreach (var module in modules) { try { // Awaited: the context starts only after an async module has finished its setup. await module.InitializeAsync(context).ConfigureAwait(false); _moduleContextMap[module.ModuleName] = contextName; _logger.LogInformation("Initialized module {Module} in context {Context}", module.ModuleName, contextName); } catch (Exception ex) { _logger.LogError(ex, "Failed to initialize module {Module} in context {Context}", module.ModuleName, contextName); (failures ??= []).Add(new ModuleActivationFailure(module.ModuleName, contextName, ex)); } } // A context in which no module came up has nothing to run. Starting it anyway logged "started // successfully: all 0 endpoints operational" right after the module's error and showed the context // Running on the dashboard. It stays created and stopped: visible, and startable by hand once fixed. if (failures is not null && failures.Count == modules.Count) { _logger.LogError( "Context {Context} not started: none of its {Count} module(s) initialized ({Modules}), see the errors above", contextName, modules.Count, string.Join(", ", modules.Select(m => m.ModuleName))); return failures; } // Auto-start if configured if (await _contextManager.ShouldAutoStartAsync(contextName).ConfigureAwait(false)) { try { await _contextManager.StartContextAsync(contextName); } catch (Exception ex) { _logger.LogError(ex, "Failed to auto-start context {Context}", contextName); // The context never started, so none of its modules came up: report each one not already reported. failures ??= []; foreach (var module in modules) { if (!failures.Exists(f => string.Equals(f.ModuleName, module.ModuleName, StringComparison.OrdinalIgnoreCase))) failures.Add(new ModuleActivationFailure(module.ModuleName, contextName, ex)); } } } return failures ?? (IReadOnlyList)Array.Empty(); } /// /// Determines the target context for a module based on config. /// Priority: appsettings Contexts section → {Module}.config.json beside the module on disk → the one embedded in the .tpkg → anonymous. /// private (string ContextName, bool IsNamed) DetermineContextForModule(ITsakModule module) { var moduleName = module.ModuleName; // Step 1: Check appsettings Tsak:Contexts:{key}:Modules[] var contextsSection = _configuration.GetSection("Tsak:Contexts"); foreach (var contextSection in contextsSection.GetChildren()) { if (string.Equals(contextSection.Key, "default", StringComparison.OrdinalIgnoreCase)) continue; var modulesConfig = contextSection.GetSection("Modules").Get(); if (modulesConfig?.Contains(moduleName, StringComparer.OrdinalIgnoreCase) == true) { // Use explicit ContextName from section if present, otherwise section key var explicitName = contextSection["ContextName"]; return (explicitName ?? contextSection.Key, true); } } // Step 2: {Module}.config.json beside the module on disk, which overrides the package's own (as in the merge) if (module.SourceDirectory is { Length: > 0 } sourceDir && Directory.Exists(sourceDir)) { var moduleConfigPath = Path.Combine(sourceDir, $"{moduleName}.config.json"); if (File.Exists(moduleConfigPath)) { try { var jsonConfig = new ConfigurationBuilder() .AddJsonFile(moduleConfigPath, optional: true, reloadOnChange: false) .Build(); var contextName = jsonConfig["ContextName"]; if (!string.IsNullOrWhiteSpace(contextName)) { _logger.LogInformation( "Module {Module} has ContextName '{ContextName}' from {File}.config.json", moduleName, contextName, moduleName); return (contextName, true); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to read ContextName from {Module}.config.json", moduleName); } } } // Step 3: the config embedded in the .tpkg if (module is Contracts.IEmbeddedConfigModule { EmbeddedConfigJson: { Length: > 0 } configJson }) { try { using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(configJson)); var jsonConfig = new ConfigurationBuilder() .AddJsonStream(stream) .Build(); var contextName = jsonConfig["ContextName"]; if (!string.IsNullOrWhiteSpace(contextName)) { _logger.LogInformation( "Module {Module} has ContextName '{ContextName}' from embedded package config", moduleName, contextName); return (contextName, true); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to read ContextName from embedded config for {Module}", moduleName); } } // Step 4: Anonymous context return (moduleName, false); } /// /// Validates that a named ContextName is not already claimed by an unrelated module. /// Modules in the same appsettings Modules[] section are allowed to share a context name. /// /// /// Claims a context name for a module. Returns true if the name is free (or already this /// module's / same appsettings group), false on a genuine collision. Must NOT throw: it runs /// under the registry event handlers, and a throw there (previously an /// InvalidOperationException) escaped as an unobserved async void exception and /// killed the whole node. A collision is now a logged rejection — the offending module is skipped, /// the node stays up and other modules keep loading. /// private bool TryClaimContextName(string contextName, string moduleName) { if (!_claimedContextNames.TryGetValue(contextName, out var claimedBy)) { _claimedContextNames[contextName] = moduleName; return true; } if (string.Equals(claimedBy, moduleName, StringComparison.OrdinalIgnoreCase)) return true; // Allow if both modules are in the same appsettings Modules[] section if (AreModulesInSameAppSettingsGroup(claimedBy, moduleName)) return true; _logger.LogError( "Context name '{ContextName}' already claimed by module '{ClaimedBy}' — module '{ModuleName}' " + "will be SKIPPED (context-name collision). Give it a distinct context or group them in the same " + "appsettings Modules[] section.", contextName, claimedBy, moduleName); return false; } /// /// Checks if two modules are listed in the same Tsak:Contexts:{*}:Modules[] section. /// private bool AreModulesInSameAppSettingsGroup(string module1, string module2) { var contextsSection = _configuration.GetSection("Tsak:Contexts"); foreach (var contextSection in contextsSection.GetChildren()) { var modulesConfig = contextSection.GetSection("Modules").Get(); if (modulesConfig == null) continue; var hasModule1 = modulesConfig.Contains(module1, StringComparer.OrdinalIgnoreCase); var hasModule2 = modulesConfig.Contains(module2, StringComparer.OrdinalIgnoreCase); if (hasModule1 && hasModule2) return true; } return false; } private List GetAllModulesForNamedContext(string contextName, ITsakModule newModule) { var existing = GetModulesInContext(contextName).ToList(); // Replace if same name, otherwise add var replaced = false; for (int i = 0; i < existing.Count; i++) { if (string.Equals(existing[i].ModuleName, newModule.ModuleName, StringComparison.OrdinalIgnoreCase)) { existing[i] = newModule; replaced = true; break; } } if (!replaced) existing.Add(newModule); return existing; } private IEnumerable GetModulesInContext(string contextName) { if (_registry == null) return []; return _moduleContextMap .Where(kv => string.Equals(kv.Value, contextName, StringComparison.OrdinalIgnoreCase)) .Select(kv => _registry.GetModule(kv.Key)) .Where(m => m != null) .Cast() .ToList(); } /// /// Builds context configuration by merging layers: /// Layer 1: Tsak:Contexts:default (base) /// Layer 2: Tsak:Contexts:{contextName} (named overrides) /// Layer 3: context.json files from module source directories /// Layer 4: {Module}.config.json, the one embedded in the .tpkg first, then the one beside it on disk /// Layer 5: Tsak:Contexts:{contextName}:Override (DevOps last word) /// Each layer deep-merges over the previous; later layers win on conflicts. /// internal IDictionary GetContextConfig(string contextName, IReadOnlyList? modules = null) { var config = new Dictionary(StringComparer.OrdinalIgnoreCase); // Layer 1: default section var defaultSection = _configuration.GetSection("Tsak:Contexts:default"); if (defaultSection.Exists()) LoadConfigurationSection(defaultSection, config); // Layer 2: named context section if (!string.Equals(contextName, "default", StringComparison.OrdinalIgnoreCase)) { var contextSection = _configuration.GetSection($"Tsak:Contexts:{contextName}"); if (contextSection.Exists()) { var layer2 = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadConfigurationSection(contextSection, layer2); ConfigMergeHelper.DeepMerge(config, layer2); } } // Layers 3+4 per module: context.json beside the module, then {Module}.config.json, first the one embedded in the // .tpkg (the package's own defaults), then the one beside the package on disk, which overrides the package without // repacking it. if (modules != null) { foreach (var module in modules) { var sourceDir = module.SourceDirectory is { Length: > 0 } dir && Directory.Exists(dir) ? dir : null; if (sourceDir is not null) LoadContextJson(sourceDir, contextName, config); // Read like the disk files: a Contexts section scopes it per context. if (module is Contracts.IEmbeddedConfigModule { EmbeddedConfigJson: { Length: > 0 } configJson }) { try { using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(configJson)); var jsonConfig = new ConfigurationBuilder() .AddJsonStream(stream) .Build(); var layer = ExtractLayerForContext(jsonConfig, contextName); ConfigMergeHelper.DeepMerge(config, layer); _logger.LogDebug("Loaded embedded config for module {Module} ({Count} keys)", module.ModuleName, layer.Count); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load embedded config for module {Module}", module.ModuleName); } } if (sourceDir is not null) LoadModuleConfigJson(sourceDir, module.ModuleName, contextName, config); } } // Layer 5: Override section (DevOps last word) var overrideSection = _configuration.GetSection($"Tsak:Contexts:{contextName}:Override"); if (overrideSection.Exists() && overrideSection.GetChildren().Any()) { var overrideConfig = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadConfigurationSection(overrideSection, overrideConfig); ConfigMergeHelper.DeepMerge(config, overrideConfig); _logger.LogInformation("Applied Override layer for context {Context} ({Count} keys)", contextName, overrideConfig.Count); } return config; } /// /// Loads a configuration section into a dictionary, handling nested objects recursively. /// Skips reserved keys (Modules, Override). /// private static void LoadConfigurationSection(IConfigurationSection section, IDictionary config) { foreach (var item in section.GetChildren()) { if (string.Equals(item.Key, "Modules", StringComparison.OrdinalIgnoreCase) || string.Equals(item.Key, "Override", StringComparison.OrdinalIgnoreCase)) continue; if (item.GetChildren().Any()) { var nested = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadNestedConfiguration(item, nested); config[item.Key] = nested; } else { config[item.Key] = item.Value; } } } /// /// Recursively loads nested configuration sections into a dictionary. /// private static void LoadNestedConfiguration(IConfigurationSection section, IDictionary config) { foreach (var child in section.GetChildren()) { if (child.GetChildren().Any()) { var nested = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadNestedConfiguration(child, nested); config[child.Key] = nested; } else { config[child.Key] = child.Value; } } } /// /// Loads module config files from the module's source directory (layers 3+4): /// - context.json: module infrastructure defaults /// - {ModuleName}.config.json: module builder settings /// /// Both files support an OPTIONAL Contexts: root key for per-context /// scoping (mirrors host appsettings Tsak:Contexts:{name}): /// /// { /// "Contexts": { /// "default": { /* shared by all contexts in this folder */ }, /// "identity.core": { "Identity": { ... } }, /// "identity.http": { "IdentityTransport": { ... } } /// } /// } /// /// When Contexts: is absent, the file is merged flat (legacy behaviour). /// When present, only Contexts:default and Contexts:{contextName} /// are merged for the target context; sections for OTHER contexts are ignored. /// private void LoadContextJson(string sourceDir, string contextName, IDictionary config) { // Layer 3: context.json (module infra defaults) var contextJsonPath = Path.Combine(sourceDir, "context.json"); if (File.Exists(contextJsonPath)) { try { var jsonConfig = new ConfigurationBuilder() .AddJsonFile(contextJsonPath, optional: true, reloadOnChange: false) .Build(); var layer = ExtractLayerForContext(jsonConfig, contextName); ConfigMergeHelper.DeepMerge(config, layer); _logger.LogDebug("Loaded context.json from {Path} ({Count} keys for context {Context})", sourceDir, layer.Count, contextName); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load context.json from {Path}", sourceDir); } } } /// Layer 4 on disk: {ModuleName}.config.json beside the module, over the one embedded in its package. private void LoadModuleConfigJson(string sourceDir, string moduleName, string contextName, IDictionary config) { // Layer 4: {ModuleName}.config.json (builder settings) var moduleConfigPath = Path.Combine(sourceDir, $"{moduleName}.config.json"); if (File.Exists(moduleConfigPath)) { try { var jsonConfig = new ConfigurationBuilder() .AddJsonFile(moduleConfigPath, optional: true, reloadOnChange: false) .Build(); var layer = ExtractLayerForContext(jsonConfig, contextName); ConfigMergeHelper.DeepMerge(config, layer); _logger.LogDebug("Loaded {File}.config.json from {Path} ({Count} keys for context {Context})", moduleName, sourceDir, layer.Count, contextName); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load {Module}.config.json from {Path}", moduleName, sourceDir); } } } /// /// Extracts the effective config layer for a given context from a JSON file. /// If the file has a top-level Contexts: section, merges /// Contexts:default then Contexts:{contextName} (later wins). /// Otherwise returns all root keys flat (legacy behaviour). /// private static Dictionary ExtractLayerForContext(IConfiguration jsonConfig, string contextName) { var layer = new Dictionary(StringComparer.OrdinalIgnoreCase); var contextsSection = jsonConfig.GetSection("Contexts"); if (contextsSection.Exists()) { // New format: per-context scoping var defaultSection = contextsSection.GetSection("default"); if (defaultSection.Exists()) { foreach (var section in defaultSection.GetChildren()) LoadNestedOrLeaf(section, layer); } var ownSection = contextsSection.GetSection(contextName); if (ownSection.Exists()) { var own = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var section in ownSection.GetChildren()) LoadNestedOrLeaf(section, own); ConfigMergeHelper.DeepMerge(layer, own); } } else { // Legacy format: flat keys at root, shared by all contexts foreach (var section in jsonConfig.GetChildren()) LoadNestedOrLeaf(section, layer); } return layer; } /// /// Loads an IConfigurationSection as either a nested dictionary or a leaf value. /// private static void LoadNestedOrLeaf(IConfigurationSection section, IDictionary config) { if (section.GetChildren().Any()) { var nested = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadNestedConfiguration(section, nested); config[section.Key] = nested; } else { config[section.Key] = section.Value; } } /// /// The anonymous context a module lives in. A module ALREADY running in an anonymous context (a hot /// swap or a package reload re-adds it) gets that same context back, so the recreation replaces it — /// as the named-context path and always did. The name carries a /// timestamp and a GUID, so generating a fresh one on every re-add created a second context and left /// the old version running next to the new one. /// private string GenerateAnonymousContextName(string moduleName) => _moduleContextMap.TryGetValue(moduleName, out var existing) && IsAnonymousContext(existing) ? existing : $"{moduleName}_dyn_{DateTimeOffset.UtcNow:yyyyMMdd_HHmmss}_{Guid.NewGuid():N}"; private static bool IsAnonymousContext(string contextName) => contextName.Contains("_dyn_", StringComparison.Ordinal); /// /// Reads Dependencies for a context from config layers (appsettings, context.json, module.config.json). /// Returns context names this context depends on. /// internal string[] GetContextDependencies(string contextName, IReadOnlyList? modules = null) { // Check appsettings: Tsak:Contexts:{name}:Dependencies[] var deps = _configuration.GetSection($"Tsak:Contexts:{contextName}:Dependencies").Get(); if (deps is { Length: > 0 }) return deps; // Check default: Tsak:Contexts:default:Dependencies[] deps = _configuration.GetSection("Tsak:Contexts:default:Dependencies").Get(); if (deps is { Length: > 0 }) return deps; // Check module config files if (modules == null) return []; foreach (var module in modules) { if (module.SourceDirectory is not { Length: > 0 } sourceDir || !Directory.Exists(sourceDir)) continue; // context.json var contextJsonPath = Path.Combine(sourceDir, "context.json"); if (File.Exists(contextJsonPath)) { try { var json = new ConfigurationBuilder() .AddJsonFile(contextJsonPath, optional: true, reloadOnChange: false) .Build(); deps = json.GetSection("Dependencies").Get(); if (deps is { Length: > 0 }) return deps; } catch { /* logged elsewhere */ } } // {Module}.config.json var moduleConfigPath = Path.Combine(sourceDir, $"{module.ModuleName}.config.json"); if (File.Exists(moduleConfigPath)) { try { var json = new ConfigurationBuilder() .AddJsonFile(moduleConfigPath, optional: true, reloadOnChange: false) .Build(); deps = json.GetSection("Dependencies").Get(); if (deps is { Length: > 0 }) return deps; } catch { /* logged elsewhere */ } } } return []; } /// The package manifest of a module, null for a module of no package (a bare DLL, a static module). internal static Modules.ModuleManifest? PackageOf(ITsakModule module) => module switch { Modules.XmlRouteModule xml => xml.Manifest, _ => System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(module.GetType().Assembly) is Modules.ModuleAssemblyLoadContext { Manifest: { } manifest } ? manifest : null, }; /// /// Topologically sorts context entries by their declared Dependencies. /// Contexts with no dependencies come first. Cyclic dependencies are detected and logged. /// private List<(string Name, IReadOnlyList Modules, bool IsAnonymous)> TopologicalSort( List<(string Name, IReadOnlyList Modules, bool IsAnonymous)> entries) { if (entries.Count <= 1) return entries; // Build adjacency: context → depends-on context names var depMap = new Dictionary(StringComparer.OrdinalIgnoreCase); var entryMap = new Dictionary Modules, bool IsAnonymous)>(StringComparer.OrdinalIgnoreCase); foreach (var entry in entries) { entryMap[entry.Name] = entry; depMap[entry.Name] = GetContextDependencies(entry.Name, entry.Modules); } // Dependencies the modules declare themselves name modules or packages, not contexts: ITsakModule.Dependencies // and the package manifest's Dependencies (the rule the hot reload orders packages by). Each name stands // for the contexts of this batch that run a module of that name or of that package. var contextsByName = new Dictionary>(StringComparer.OrdinalIgnoreCase); void Provide(string? name, string context) { if (string.IsNullOrWhiteSpace(name)) return; if (!contextsByName.TryGetValue(name, out var contexts)) contextsByName[name] = contexts = new HashSet(StringComparer.OrdinalIgnoreCase); contexts.Add(context); } foreach (var entry in entries) foreach (var module in entry.Modules) { Provide(module.ModuleName, entry.Name); Provide(PackageOf(module)?.Name, entry.Name); } foreach (var entry in entries) { var deps = new HashSet(depMap[entry.Name], StringComparer.OrdinalIgnoreCase); foreach (var module in entry.Modules) foreach (var name in module.Dependencies.Concat(PackageOf(module)?.Dependencies ?? [])) if (contextsByName.TryGetValue(name, out var contexts)) deps.UnionWith(contexts.Where(c => !string.Equals(c, entry.Name, StringComparison.OrdinalIgnoreCase))); depMap[entry.Name] = [.. deps]; } // Kahn's algorithm var inDegree = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var name in entryMap.Keys) inDegree[name] = 0; foreach (var (name, deps) in depMap) { foreach (var dep in deps) { if (entryMap.ContainsKey(dep)) inDegree[name]++; // Dependencies on contexts not in this batch are ignored (already running or external) } } var queue = new Queue(); foreach (var (name, degree) in inDegree) { if (degree == 0) queue.Enqueue(name); } var result = new List<(string Name, IReadOnlyList Modules, bool IsAnonymous)>(); var visited = new HashSet(StringComparer.OrdinalIgnoreCase); while (queue.Count > 0) { var current = queue.Dequeue(); visited.Add(current); result.Add(entryMap[current]); // Find contexts that depend on current — reduce their in-degree foreach (var (name, deps) in depMap) { if (visited.Contains(name)) continue; if (deps.Any(d => string.Equals(d, current, StringComparison.OrdinalIgnoreCase))) { inDegree[name]--; if (inDegree[name] == 0) queue.Enqueue(name); } } } // Detect cycle: any unvisited entries have circular dependencies foreach (var entry in entries) { if (!visited.Contains(entry.Name)) { var deps = string.Join(", ", depMap[entry.Name]); _logger.LogError( "Cyclic dependency detected: context {Context} depends on [{Dependencies}]. Skipping — will not start", entry.Name, deps); } } return result; } } Path: redb-tsak/src/redb.Tsak.Core/Services/TsakHostedService.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/Services/TsakHostedService.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Tsak.Core.Audit; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Security; using redb.Tsak.Core.Modules; using redb.Tsak.Core.Services; using redb.Tsak.Core.Services.Storage; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace redb.Tsak.Core.Services; /// /// Main hosted service managing the Tsak runtime lifecycle. /// Startup: init coordinator → start _system context (REST API) → register static providers (batch) → scan dynamic modules → maintenance loop. /// Lifecycle hooks () run before module discovery and after shutdown. /// Hot reload: periodically scans for updated module DLLs via . /// Shutdown: stop all running contexts (+ cluster deregistration). /// public class TsakHostedService : BackgroundService { private readonly ILogger _logger; private readonly ITsakModuleRegistry _registry; private readonly ITsakContextManager _contextManager; private readonly ITsakCoordinator _coordinator; private readonly IEnumerable _staticProviders; private readonly IConfiguration _configuration; private readonly IEnumerable _lifecycleHooks; private readonly HotReloadService _hotReloadService; private readonly SharedAssemblyLoader _sharedLoader; private readonly SystemContextBuilder? _systemContextBuilder; private readonly IServiceProvider _serviceProvider; public TsakHostedService( ILogger logger, ITsakModuleRegistry registry, ITsakContextManager contextManager, ITsakCoordinator coordinator, IEnumerable staticProviders, IConfiguration configuration, HotReloadService hotReloadService, SharedAssemblyLoader sharedLoader, IServiceProvider serviceProvider, IEnumerable lifecycleHooks, SystemContextBuilder? systemContextBuilder = null) { _logger = logger; _registry = registry; _contextManager = contextManager; _coordinator = coordinator; _staticProviders = staticProviders; _configuration = configuration; _lifecycleHooks = lifecycleHooks; _hotReloadService = hotReloadService; _sharedLoader = sharedLoader; _systemContextBuilder = systemContextBuilder; _serviceProvider = serviceProvider; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Tsak starting..."); try { // 0. Sync Tsak-specific storage schemes // (RedbInitHostedService already called InitializeAsync before us) { using var scope = _serviceProvider.CreateScope(); var redb = scope.ServiceProvider.GetService(); if (redb is not null) { await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); // V4 key migration, proactively at startup. Each rule has ONE home — the // store that owns the scheme (review 2026-09-02, Q1) — and the stores also // run it lazily for hosts without this service; post-migration each call is // a single index probe. await RedbTsakStateStore.BackfillLegacyAsync(redb, _logger); await RedbTsakModuleStore.BackfillLegacyAsync(redb, _logger); await RedbApiKeyStore.BackfillLegacyKeysAsync(redb, _logger); var provider = _configuration["Tsak:Redb:Provider"] ?? "auto"; _logger.LogInformation("Tsak schemes synced (provider: {Provider})", provider); } } // Startup diagnostic summary LogStartupDiagnostics(); // 1. Initialize coordinator (subscribes to registry events) _coordinator.Initialize(_registry); // 1a. Cleanup orphaned anonymous context states if (_contextManager is TsakContextManager tcm) { try { await tcm.CleanupAnonymousStatesAsync(); } catch (Exception ex) { _logger.LogDebug(ex, "Anonymous state cleanup failed"); } } // 1b. Run lifecycle hooks BEFORE module discovery // (e.g. cluster coordinator starts, acquires leadership, etc.) foreach (var hook in LifecycleHookOrdering.OrderAscending(_lifecycleHooks, _logger)) { await hook.OnStartingAsync(stoppingToken).ConfigureAwait(false); } // 1c. Load shared assemblies (connectors, shared models) before any contexts { var sharedCount = _sharedLoader.LoadSharedAssemblies(); if (sharedCount > 0) _logger.LogInformation("Loaded {Count} shared assemblies from {Path}", sharedCount, _sharedLoader.SharedPath); } // 2. Start _system context (REST API) before module contexts if (_systemContextBuilder is not null) { try { await _systemContextBuilder.BuildAndStartAsync(_registry, stoppingToken); } catch (Exception ex) { // The node keeps running its business contexts, but with NO management/control-plane // it is not fully operational — escalate loudly AND flag readiness (review item 4.1) // so it is not silently reported healthy. _logger.LogCritical(ex, "Failed to start REST API (_system context) — node has NO control-plane; readiness will " + "report UNHEALTHY. Business contexts continue."); _serviceProvider.GetService()?.MarkFailed(ex.Message); } } // 2a. Retention sweeps (audit + DLQ) are mounted as cron:// routes on the _system context // by SystemContextBuilder — no bare Quartz jobs here anymore. // 3. Register static providers (fires batch event → coordinator creates contexts) var staticCount = await _registry.RegisterStaticProvidersAsync(_staticProviders); _logger.LogInformation("Registered {Count} static modules", staticCount); // 4. Scan dynamic modules from configured paths var assemblyPaths = _configuration.GetSection("Tsak:Modules:AssemblyPaths").Get(); var collectible = _configuration.GetValue("Tsak:HotReload:Collectible", false); if (assemblyPaths is { Length: > 0 }) { // Register centralized tracker resolver so byte-loaded assemblies // are found by all ALCs (packages, bare DLLs, shared layer). LoadedAssemblyTracker.EnsureResolverRegistered(); int dynamicCount; if (_registry is TsakModuleRegistry concreteRegistry) { dynamicCount = await concreteRegistry.DiscoverModulesAsync(assemblyPaths, probePaths: assemblyPaths, collectible: collectible); // Hand off startup-loaded packages to HotReloadService (takes ALC ownership); the registry lets go. var startupPackages = concreteRegistry.HandOverLoadedPackages(); if (startupPackages.Count > 0) _hotReloadService.AdoptStartupPackages(startupPackages); } else { dynamicCount = await _registry.DiscoverModulesAsync(assemblyPaths); } _logger.LogInformation("Discovered {Count} dynamic module changes", dynamicCount); } _logger.LogInformation("Tsak running with {Modules} modules, {Contexts} contexts", _registry.GetAllModules().Count, _contextManager.GetAllContexts().Count); // 5. Periodic hot-reload loop (only if enabled in config) var hotReloadEnabled = _configuration.GetValue("Tsak:HotReload:Enabled", true); var scanInterval = _configuration.GetValue("Tsak:HotReload:ScanIntervalSeconds", 30); if (hotReloadEnabled && scanInterval > 0 && assemblyPaths is { Length: > 0 }) { _logger.LogInformation("Hot-reload enabled, scanning every {Interval}s", scanInterval); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(scanInterval), stoppingToken); try { var reloaded = await _hotReloadService.ScanAndReloadAsync(assemblyPaths, stoppingToken); if (reloaded > 0) _logger.LogInformation("Hot-reloaded {Count} modules", reloaded); } catch (Exception ex) { _logger.LogError(ex, "Error during periodic module scan"); } } } else { _logger.LogInformation("Hot-reload disabled, running with startup modules only"); await Task.Delay(Timeout.Infinite, stoppingToken); } } catch (OperationCanceledException) { // Expected during graceful shutdown } catch (Exception ex) { _logger.LogCritical(ex, "Tsak fatal error"); throw; } _logger.LogInformation("Tsak stopped"); } /// /// The redb tier the worker registers, as the startup log names it. Reads Tsak:Redb:UsePro with the /// default ConfigureRedb registers by (absent means Pro), so the log line and the registration agree. /// internal static string DatabaseTier(IConfiguration configuration) => configuration.GetValue("Tsak:Redb:UsePro", true) ? "Pro" : "Free"; private void LogStartupDiagnostics() { // The forbidden Quartz combination (review 2026-09-02, В11): a persistent AdoJobStore on // the SHARED redb database with clustering off — several nodes would run non-clustered // schedulers of one name on one qrtz_* set (double-fired triggers, corrupted job state). // Not applicable to SQLite: the database is a local file no second node can share, and // ConfigureQuartz forces clustered=false there (Quartz refuses SQLite + clustered). var clusterEnabled = _configuration.GetValue("Tsak:Cluster:Enabled", false); var jobStore = _configuration["Quartz:quartz.jobStore.type"] ?? ""; var quartzClustered = _configuration.GetValue("Quartz:quartz.jobStore.clustered", false); var redbProvider = _configuration["Tsak:Redb:Provider"]?.ToLowerInvariant() ?? "postgres"; var isSqlite = redbProvider == "sqlite"; if (clusterEnabled && jobStore.Contains("AdoJobStore", StringComparison.OrdinalIgnoreCase) && !quartzClustered && !isSqlite) _logger.LogCritical( "Tsak:Cluster:Enabled=true with Quartz AdoJobStore but quartz.jobStore.clustered=false — every " + "cluster node will run an independent scheduler on the same qrtz_* tables, double-firing triggers " + "and corrupting the job store. Set Quartz:quartz.jobStore.clustered=true."); // RollingUpdate never had an implementation — no code reads the flag (review 2026-09-02, // С16). Warn instead of letting the operator trust a staggered update that will not happen. if (_configuration.GetValue("Tsak:HotReload:RollingUpdate", false)) _logger.LogWarning( "Tsak:HotReload:RollingUpdate=true is NOT implemented: nodes reload modules independently on their " + "own scan schedule. Stagger an update by deploying the package to nodes sequentially yourself."); // Database connection var provider = _configuration["Tsak:Redb:Provider"]?.ToLowerInvariant() ?? "postgres"; var connKey = provider switch { "mssql" or "sqlserver" => "MSSql", "sqlite" => "Sqlite", _ => "Postgres" }; var connStr = _configuration.GetConnectionString(connKey) ?? ""; var safeConnStr = SanitizeConnectionString(connStr); var tier = DatabaseTier(_configuration); _logger.LogInformation("Database: provider={Provider}, tier={Tier}, connection={Connection}", provider, tier, safeConnStr); // Quartz mode var jobStoreType = _configuration["Quartz:quartz.jobStore.type"] ?? "RAMJobStore"; var isAdoJobStore = jobStoreType.Contains("AdoJobStore", StringComparison.OrdinalIgnoreCase); var isRamJobStore = jobStoreType.Contains("RAMJobStore", StringComparison.OrdinalIgnoreCase); if (!isAdoJobStore && !isRamJobStore) { _logger.LogWarning( "Unknown Quartz jobStore.type '{JobStoreType}'. Recognized values are 'RAMJobStore' " + "and any AdoJobStore variant (e.g. 'JobStoreTX'). Treating as non-persistent.", jobStoreType); } var clustered = _configuration.GetValue("Quartz:quartz.jobStore.clustered"); if (clustered && isSqlite && isAdoJobStore) { // Report the EFFECTIVE value, not the raw config — ConfigureQuartz overrode it. _logger.LogWarning( "Quartz: quartz.jobStore.clustered=true is overridden to false on the SQLite provider — Quartz " + "refuses clustered mode on SQLite (no row locks for the QRTZ_LOCKS semaphore), and a SQLite " + "file cannot be shared between nodes anyway."); clustered = false; } var instanceId = _configuration["Quartz:quartz.scheduler.instanceId"] ?? "NON_CLUSTERED"; // NODE stands for the node id (TsakNodeIdentity): report what the schedulers get. if (string.Equals(instanceId.Trim(), TsakNodeIdentity.QuartzInstanceIdOfNode, StringComparison.OrdinalIgnoreCase)) instanceId = $"{TsakNodeIdentity.Resolve(_configuration)} (NODE)"; _logger.LogInformation( "Quartz: store={JobStore}, persistence={Persistence}, clustered={Clustered}, instanceId={InstanceId}", isAdoJobStore ? "AdoJobStore" : "RAMJobStore", isAdoJobStore, clustered, instanceId); // Tsak cluster var tsakCluster = _configuration.GetValue("Tsak:Cluster:Enabled"); var strategy = _configuration["Tsak:Cluster:Strategy"] ?? "round-robin"; var clusterName = _configuration["Tsak:Cluster:ClusterName"] ?? "default"; var groupName = _configuration["Tsak:Cluster:GroupName"] ?? "default"; if (tsakCluster) { _logger.LogInformation( "Tsak cluster: enabled=True, cluster={ClusterName}, group={GroupName}, strategy={Strategy}", clusterName, groupName, strategy); } else { _logger.LogInformation("Tsak cluster: enabled=False (single-node mode)"); } } private static string SanitizeConnectionString(string connStr) { // Show host+database, mask credentials var parts = connStr.Split(';', StringSplitOptions.RemoveEmptyEntries); var safe = new List(); foreach (var part in parts) { var kv = part.Split('=', 2); if (kv.Length != 2) continue; var key = kv[0].Trim().ToLowerInvariant(); if (key is "password" or "pwd") safe.Add($"{kv[0].Trim()}=***"); else safe.Add(part.Trim()); } return string.Join("; ", safe); } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Tsak graceful shutdown, stopping all contexts..."); // Run lifecycle hooks in reverse order (e.g. cluster deregistration) foreach (var hook in LifecycleHookOrdering.OrderDescending(_lifecycleHooks, _logger)) { try { await hook.OnStoppingAsync(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error in lifecycle hook {Hook}", hook.GetType().Name); } } // Don't propagate host's cancellation token to context stops: // draining inflight exchanges in one context may exhaust the host // shutdown timeout, causing remaining contexts to fail with TaskCanceledException // on the lifecycle semaphore. Each context has its own internal drain timeout. foreach (var (name, _) in _contextManager.GetAllContexts()) { try { await _contextManager.StopContextAsync(name, setAutoStartFalse: false, ct: CancellationToken.None); } catch (Exception ex) { _logger.LogError(ex, "Error stopping context {Context}", name); } } await base.StopAsync(cancellationToken); } } Path: redb-tsak/src/redb.Tsak.Core/Services/TsakModuleRegistry.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/Services/TsakModuleRegistry.cs ---- using System.Collections.Concurrent; using System.Reflection; using Microsoft.Extensions.Logging; using redb.Tsak.Core.Contracts; using redb.Tsak.Core.Modules; namespace redb.Tsak.Core.Services; /// /// Thread-safe module registry with assembly scanning, batch events, and version tracking. /// Based on lt.tsak RouteModuleRegistry, redesigned for redb.Route. /// public class TsakModuleRegistry : ITsakModuleRegistry { private readonly ConcurrentDictionary _modules = new(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary _moduleFilePaths = new(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary _loadedPackages = new(StringComparer.OrdinalIgnoreCase); private readonly ITsakModuleStore _store; private readonly ILogger _logger; /// /// Packages loaded during startup discovery and not handed over yet (). /// public IReadOnlyDictionary LoadedPackages => _loadedPackages; /// /// Hands the packages of startup discovery over to their owner (HotReloadService.AdoptStartupPackages) and lets go of /// them: a registry still holding a package keeps its load context, and so every old version of it, in memory after /// the first hot swap. /// internal IReadOnlyDictionary HandOverLoadedPackages() { var packages = new Dictionary(_loadedPackages, StringComparer.OrdinalIgnoreCase); _loadedPackages.Clear(); return packages; } public TsakModuleRegistry( ITsakModuleStore store, ILogger logger, Modules.ModuleLoadGate? loadGate = null) { _store = store; _logger = logger; // Optional so plain unit tests can construct the registry; DI always provides the gate. // Without it discovery is permissive — exactly the pre-fix behavior. _loadGate = loadGate; } private readonly Modules.ModuleLoadGate? _loadGate; public event EventHandler? ModuleAdded; public event EventHandler? ModuleRemoved; public event EventHandler? ModuleUpdated; public event EventHandler>? ModulesBatchAdded; public async Task RegisterStaticProvidersAsync(IEnumerable providers) { var batchModules = new List(); foreach (var provider in providers.OrderByDescending(p => p.Priority)) { if (!provider.CanInitialize()) { _logger.LogWarning("Static provider {Provider} cannot initialize, skipping", provider.ProviderName); continue; } foreach (var module in provider.GetStaticModules()) { if (_modules.TryAdd(module.ModuleName, module)) { batchModules.Add(module); await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded }); _logger.LogInformation("Registered static module {Module} v{Version} from {Provider}", module.ModuleName, module.Version, provider.ProviderName); } else { _logger.LogDebug("Module {Module} already registered, skipping", module.ModuleName); } } } if (batchModules.Count > 0) ModulesBatchAdded?.Invoke(this, batchModules); _logger.LogInformation("Registered {Count} modules from static providers", batchModules.Count); return batchModules.Count; } public async Task DiscoverModulesAsync(IEnumerable assemblyPaths) => await DiscoverModulesAsync(assemblyPaths, probePaths: null, collectible: false); /// /// Discovers modules in assemblies and .tpkg packages at the specified paths. /// Packages are opened with the given and /// settings and stored in for HotReloadService adoption. /// public async Task DiscoverModulesAsync(IEnumerable assemblyPaths, string[]? probePaths, bool collectible) { var added = new List(); var updated = new List(); var removed = new List(); // Detect deleted assemblies foreach (var (moduleName, filePath) in _moduleFilePaths.ToArray()) { if (!File.Exists(filePath)) { if (_modules.TryRemove(moduleName, out _)) { _moduleFilePaths.TryRemove(moduleName, out _); removed.Add(moduleName); await _store.RemoveAsync(moduleName); _logger.LogInformation("Removed module {Module} (assembly deleted: {Path})", moduleName, filePath); } } } foreach (var path in assemblyPaths) { if (!Directory.Exists(path)) { _logger.LogWarning("Assembly path {Path} does not exist, skipping", path); continue; } foreach (var dll in Directory.GetFiles(path, "*.dll")) { // Load-boundary trust gate (review 2026-09-02, К3): with signature enforcement on, // a bare DLL cannot carry a signature and is refused — startup discovery must not // execute what the hot-reload scan would refuse. if (_loadGate is not null && !_loadGate.AllowBareDll(dll)) continue; try { var modules = DiscoverModulesInAssembly(dll); foreach (var module in modules) { _moduleFilePaths[module.ModuleName] = dll; if (_modules.TryGetValue(module.ModuleName, out var existing)) { if (string.Compare(module.Version, existing.Version, StringComparison.Ordinal) > 0) { _modules[module.ModuleName] = module; updated.Add(module); await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded, AssemblyPath = dll, LastUpdatedAt = DateTimeOffset.UtcNow }); _logger.LogInformation("Updated module {Module} v{OldVer} → v{NewVer}", module.ModuleName, existing.Version, module.Version); (existing as IDisposable)?.Dispose(); } } else { _modules[module.ModuleName] = module; added.Add(module); await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded, AssemblyPath = dll }); } } } catch (Exception ex) { _logger.LogError(ex, "Failed to scan assembly {Path}", dll); } } // Scan .tpkg packages (CAR-style deployment), in dependency order: a package that uses the companion DLLs of // a carrier (Manifest.Dependencies) is opened after it, as the hot-reload scan does. In directory order a // dependent opened first failed on its missing types and waited for the next hot-reload scan. foreach (var (tpkg, bytes) in ReadPackagesInDependencyOrder(path)) { try { // Load-boundary trust gate (review 2026-09-02, К3): the verified bytes are the loaded bytes. var package = ModulePackage.Open(bytes, tpkg, File.GetLastWriteTimeUtc(tpkg), probePaths: probePaths, logger: _logger, collectible: collectible); if (package is null) continue; var tpkgFullPath = Path.GetFullPath(tpkg); var packageModuleFound = false; foreach (var assembly in package.LoadedAssemblies) { var sourceDir = Path.GetDirectoryName(tpkgFullPath); var modules = DiscoverModulesInAssembly(assembly, sourceDir); foreach (var module in modules) { if (RefuseNameCollision(module.ModuleName, tpkg, isXml: false)) continue; packageModuleFound = true; // Per-module config from package ({moduleName}.config.json) if (module is Modules.StaticMethodModule smm) smm.AttachPackage(package); _moduleFilePaths[module.ModuleName] = tpkg; _modules[module.ModuleName] = module; added.Add(module); await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded, AssemblyPath = tpkg }); _logger.LogInformation("Discovered module {Module} v{Ver} from package {Pkg}", module.ModuleName, module.Version, package.Manifest.Name); } } // Third convention (Route-XML Ф5.2): XML artifacts from the manifest. // AFTER the assembly scan, so bean:#name objects registered by module code // are visible to the artifacts. An XML-only package (no entry points) is a // full module too — before this, it died on packageModuleFound below. // The XML module is named after the manifest, so the name is checked before the // module is built: a refused one is never constructed. if (package.Manifest.Artifacts.Count > 0 && !RefuseNameCollision(package.Manifest.Name, tpkg, isXml: true)) { var sourceDir = Path.GetDirectoryName(tpkgFullPath); var xmlModule = new Modules.XmlRouteModule(package, sourceDir, package.ReadModuleConfigJson(package.Manifest.Name), _logger); packageModuleFound = true; _moduleFilePaths[xmlModule.ModuleName] = tpkg; _modules[xmlModule.ModuleName] = xmlModule; added.Add(xmlModule); await _store.SaveAsync(new TsakModuleRecord { ModuleName = xmlModule.ModuleName, Version = xmlModule.Version, Description = xmlModule.Description, Dependencies = xmlModule.Dependencies.ToList(), Status = TsakModuleStatus.Loaded, AssemblyPath = tpkg }); _logger.LogInformation("Discovered XML route module {Module} v{Ver} from package {Pkg} ({Artifacts} artifact(s))", xmlModule.ModuleName, xmlModule.Version, package.Manifest.Name, package.Manifest.Artifacts.Count); } // Store package for HotReloadService adoption (owns the ALC) if (packageModuleFound) _loadedPackages[tpkgFullPath] = package; else package.Dispose(); } catch (Exception ex) { _logger.LogError(ex, "Failed to scan package {Path}", tpkg); } } } // Fire events foreach (var name in removed) ModuleRemoved?.Invoke(this, name); foreach (var m in updated) ModuleUpdated?.Invoke(this, m); if (added.Count > 0) ModulesBatchAdded?.Invoke(this, added); var total = added.Count + updated.Count + removed.Count; _logger.LogInformation("Discovery scan: {Added} added, {Updated} updated, {Removed} removed", added.Count, updated.Count, removed.Count); return total; } /// /// The .tpkg files of with the bytes to open, in the order to open them: by /// file name, then every package after the ones its names. The bytes are /// the signature-verified ones when a load gate is set; a package the gate refuses is left out. /// internal IReadOnlyList<(string Path, byte[] Bytes)> ReadPackagesInDependencyOrder(string directory) { var packages = new List<(string Path, byte[] Bytes, ModuleManifest Manifest)>(); foreach (var tpkg in Directory.GetFiles(directory, "*.tpkg").OrderBy(f => f, StringComparer.Ordinal)) { try { var bytes = _loadGate is not null ? _loadGate.ReadVerifiedTpkg(tpkg) : File.ReadAllBytes(tpkg); if (bytes is null) continue; packages.Add((tpkg, bytes, ModulePackage.TryReadManifest(bytes) ?? new ModuleManifest())); } catch (Exception ex) { _logger.LogError(ex, "Failed to scan package {Path}", tpkg); } } var ordered = PackageDependencyOrder.Sort(packages, p => p.Path, p => p.Manifest, out var cyclic); if (cyclic.Count > 0) _logger.LogError( "Cyclic Manifest.Dependencies among packages in {Directory}: {Packages}. Opening them in file-name order.", directory, string.Join(", ", cyclic.Select(p => p.Manifest.Name))); return ordered.Select(p => (p.Path, p.Bytes)).ToList(); } /// /// Refuses a package module whose name another module already holds. The startup scan runs once, so a /// name met twice is two modules claiming it, never an update of one — a hot swap goes through /// . Before this, the second claimant replaced the first, disposed it /// and logged "Updated": a package's XML module destroyed the code module it shared a name with, and the /// same package dropped into two scanned folders replaced itself, with no error anywhere. /// /// The node keeps running: the refusal covers the one registration in dispute, the way a module that fails /// to initialize cannot take the node down either. /// /// /// True when the registration is refused and must not go ahead. private bool RefuseNameCollision(string moduleName, string source, bool isXml) { if (!_modules.TryGetValue(moduleName, out var existing)) return false; var existingSource = _moduleFilePaths.TryGetValue(moduleName, out var path) ? path : "a static provider of the host"; _logger.LogError( "Module '{Module}' from {Source} ({Kind}) is refused: the name is already held by '{Existing}' from " + "{ExistingSource} ({ExistingKind}). Module names are compared without regard to case and must be " + "unique across everything the node loads — a package's code module and its XML module must not share " + "a name either. The module registered first keeps running; rename the manifest or the InitRoute namespace.", moduleName, source, isXml ? "XML module" : "code module", existing.ModuleName, existingSource, existing is Modules.XmlRouteModule ? "XML module" : "code module"); return true; } public async Task RegisterModuleAsync(ITsakModule module) { if (_modules.TryAdd(module.ModuleName, module)) { await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded }).ConfigureAwait(false); _logger.LogInformation("Registered module {Module} v{Version}", module.ModuleName, module.Version); ModuleAdded?.Invoke(this, module); } else { _logger.LogWarning("Module {Module} already registered", module.ModuleName); } } public async Task UnregisterModuleAsync(string moduleName) { if (!_modules.TryRemove(moduleName, out var removed)) return false; _moduleFilePaths.TryRemove(moduleName, out _); await _store.RemoveAsync(moduleName).ConfigureAwait(false); _logger.LogInformation("Unregistered module {Module}", moduleName); ModuleRemoved?.Invoke(this, moduleName); (removed as IDisposable)?.Dispose(); return true; } /// /// Removes a module from the registry without firing events. /// Used during package reload to avoid triggering ProcessModuleRemovedAsync /// (which would delete persisted state like autoStart). /// public bool UnregisterModuleSilent(string moduleName) { if (!_modules.TryRemove(moduleName, out var removed)) return false; _moduleFilePaths.TryRemove(moduleName, out _); _logger.LogDebug("Unregistered module {Module} silently (no events)", moduleName); (removed as IDisposable)?.Dispose(); return true; } /// /// Replaces a module in the registry without firing any events. /// Used by HotReloadService to avoid double context creation. /// public async Task ReplaceModuleSilentAsync(ITsakModule module) { var old = _modules.GetValueOrDefault(module.ModuleName); _modules[module.ModuleName] = module; await _store.SaveAsync(new TsakModuleRecord { ModuleName = module.ModuleName, Version = module.Version, Description = module.Description, Dependencies = module.Dependencies.ToList(), Status = TsakModuleStatus.Loaded }).ConfigureAwait(false); (old as IDisposable)?.Dispose(); _logger.LogDebug("Replaced module {Module} silently (no events)", module.ModuleName); } public IReadOnlyList GetAllModules() => _modules.Values.ToList(); public ITsakModule? GetModule(string moduleName) => _modules.GetValueOrDefault(moduleName); public IReadOnlyList GetModulesByStatus(TsakModuleStatus status) => _modules.Values.Where(m => m.Status == status).ToList(); /// /// Discovers ITsakModule implementations and InitRoute.main() conventions in an assembly. /// Uses for dedup — if the same DLL was already /// loaded (by another module or a .tpkg package), the existing Assembly instance is reused. /// internal static List DiscoverModulesInAssembly(string assemblyPath) { // Load from bytes to avoid locking the file (enables hot-copy while running) var bytes = File.ReadAllBytes(assemblyPath); var asmName = Path.GetFileNameWithoutExtension(assemblyPath); var assembly = Modules.LoadedAssemblyTracker.LoadOrReuse(asmName, bytes); var sourceDir = Path.GetDirectoryName(Path.GetFullPath(assemblyPath)); return DiscoverModulesInAssembly(assembly, sourceDir); } internal static List DiscoverModulesInAssembly(Assembly assembly, string? sourceDirectory = null, string? embeddedConfigJson = null) { var modules = new List(); // 1. Find ITsakModule implementations foreach (var type in assembly.GetExportedTypes()) { if (type.IsAbstract || type.IsInterface) continue; if (typeof(ITsakModule).IsAssignableFrom(type)) { if (Activator.CreateInstance(type) is ITsakModule module) modules.Add(module); } } // 2. Find the InitRoute.main convention: one public static main in either supported form, synchronous // or Task. A main that fits neither form, or more than one main, is an explicit error // (InitRouteConvention.Resolve) instead of a module that silently never appears; an InitRoute type // without main does not claim to be a module. foreach (var type in assembly.GetExportedTypes()) { if (type.Name != Modules.InitRouteConvention.TypeName) continue; var mains = type.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => m.Name == Modules.InitRouteConvention.MethodName) .ToList(); if (mains.Count == 0) continue; var mainMethod = Modules.InitRouteConvention.Resolve(type, mains); var moduleName = type.Namespace ?? type.Assembly.GetName().Name ?? "Unknown"; var version = assembly.GetName().Version?.ToString() ?? "0.0.0"; modules.Add(new Modules.StaticMethodModule(moduleName, version, mainMethod, sourceDirectory, embeddedConfigJson)); } return modules; } } Path: redb-tsak/src/redb.Tsak.Core/Services/TsakNodeIdentity.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/Services/TsakNodeIdentity.cs ---- using Microsoft.Extensions.Configuration; namespace redb.Tsak.Core.Services; /// /// The identity of this worker node: Tsak:Cluster:NodeId, or the host name when it is not set. One rule for the /// Tsak cluster (its node record, locks, leader election) and for the Quartz schedulers of the contexts, whose /// quartz.scheduler.instanceId = NODE stands for this value. /// public static class TsakNodeIdentity { /// The value of quartz.scheduler.instanceId that Tsak replaces with the node id. public const string QuartzInstanceIdOfNode = "NODE"; /// The node id from a configured value: the value when set, the host name otherwise. public static string Resolve(string? configuredNodeId) => string.IsNullOrWhiteSpace(configuredNodeId) ? Environment.MachineName : configuredNodeId.Trim(); /// The node id of (Tsak:Cluster:NodeId). public static string Resolve(IConfiguration configuration) => Resolve(configuration["Tsak:Cluster:NodeId"]); } Path: redb-tsak/src/redb.Tsak.Core/redb.Tsak.Core.csproj 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/redb.Tsak.Core.csproj ---- Kernel of redb.Tsak — runtime container for redb.Route contexts. Provides hot-reload module loading, REST management API, scheduler, monitoring, security and pluggable cluster bootstrap. redb;tsak;runtime;route;esb;hot-reload;quartz;cluster;rest;management README.md