Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/TestRedbSetup.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Infrastructure/TestRedbSetup.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Core.Extensions;
using redb.Core.Models.Configuration;
using redb.Core.Pro.Extensions;
// Provider extensions. Pro variants are tier-agnostic — they dispatch on
// AddRedb (Free) vs AddRedbPro (Pro). Do NOT also import the non-Pro
// extensions; the resulting overload set would be ambiguous.
using redb.Postgres.Pro.Extensions;
using redb.MSSql.Pro.Extensions;
using redb.SQLite.Pro.Extensions;
using redb.SQLite.Data;
namespace redb.Identity.Tests.Infrastructure;
///
/// Test-only helper that wires redb to a (provider × tier) combination
/// chosen via two environment variables. Default: SQLite Pro with the
/// license bundled at redb.license in the test working dir.
///
/// -
/// REDB_PROVIDER — picks storage. Values: sqlite
/// (default), postgres, mssql. Case-insensitive.
///
/// -
/// REDB_USE_PRO — picks tier. Default true (Pro);
/// set to false for the free
/// path.
///
///
/// Per-provider connection strings come from environment overrides if
/// set, otherwise from the local-dev defaults baked here. SQLite
/// auto-creates a unique temp-file database per call so parallel test
/// collections never collide.
///
public static class TestRedbSetup
{
public enum Provider { Sqlite, Postgres, MsSql }
private static readonly Lazy LicenseToken = new(LoadLicenseToken);
private static int _sqliteExtensionResolved;
private static int _sqliteScratchCleaned;
public static Provider SelectedProvider =>
(Environment.GetEnvironmentVariable("REDB_PROVIDER")?.Trim().ToLowerInvariant()) switch
{
"postgres" or "pg" or "pgsql" => Provider.Postgres,
"mssql" or "sqlserver" or "ms" => Provider.MsSql,
_ => Provider.Sqlite,
};
public static bool UsePro =>
!string.Equals(
Environment.GetEnvironmentVariable("REDB_USE_PRO")?.Trim(),
"false",
StringComparison.OrdinalIgnoreCase);
///
/// PVT prefilter, on by default so the suite exercises it. Set REDB_PVT_PREFILTER=false to
/// take it out of the picture — worth doing when a failure needs to be attributed, since the
/// prefilter is a superset that must never change a result.
///
public static bool UsePvtPrefilter =>
!string.Equals(
Environment.GetEnvironmentVariable("REDB_PVT_PREFILTER")?.Trim(),
"false",
StringComparison.OrdinalIgnoreCase);
///
/// Add redb to . The
/// is the historical local-dev default — used verbatim when REDB_PROVIDER=postgres
/// and as a sentinel otherwise. SQLite / MSSQL pull their connection strings from
/// env-var overrides or their respective defaults below.
///
public static IServiceCollection AddRedbForTests(
this IServiceCollection services,
string postgresConnString,
Action? configure = null)
{
if (SelectedProvider == Provider.Sqlite)
EnsureSqliteNativeExtensionResolved();
if (UsePro)
{
return services.AddRedbPro(options =>
{
ApplyProvider(options, postgresConnString);
ApplyLicense(options);
options.Configure(c =>
{
c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking;
c.EnablePropsCache = false;
// PVT prefilter: narrows the object set before the pivot aggregate, so a selective
// filter stops costing a full scheme scan. It is a superset and must never change a
// result — which is exactly what running this suite with it on is worth proving.
// Implemented by all three Pro providers, so it is not gated on the provider here.
c.EnablePvtPrefilter = UsePvtPrefilter;
configure?.Invoke(c);
});
});
}
return services.AddRedb(options =>
{
ApplyProvider(options, postgresConnString);
ApplyLicense(options);
options.Configure(c =>
{
c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert;
c.EnablePropsCache = false;
configure?.Invoke(c);
});
});
}
private static void ApplyProvider(RedbOptionsBuilder options, string postgresConnString)
{
switch (SelectedProvider)
{
case Provider.Postgres:
options.UsePostgres(ResolvePostgresConnectionString(postgresConnString));
break;
case Provider.MsSql:
options.UseMsSql(ResolveMsSqlConnectionString());
break;
default:
options.UseSqlite(ResolveSqliteConnectionString());
break;
}
}
private static void ApplyLicense(RedbOptionsBuilder options)
{
var token = LicenseToken.Value;
if (!string.IsNullOrEmpty(token))
options.WithLicense(token);
}
// ── Per-provider connection-string resolution ────────────────────────
///
/// Resolves the Postgres connection string in this priority order:
///
/// - REDB_POSTGRES_CS env var when set and non-empty;
/// - the argument (typically
/// config.GetConnectionString("Postgres") read from
/// appsettings.json) when non-empty;
/// - the local-dev default below — Max Pool Size=100 to match
/// MSSql/appsettings.json so the test-bench pool ceiling is uniform
/// across providers and survives WithRedb-per-scope amplification.
///
/// The hardcoded default makes the same Host/Port/credentials/database
/// match the literal connection strings used by the Audit*IntegrationTests
/// classes so a test that drops below appsettings.json (or one whose
/// fixture doesn't load it) still lands on the same database.
///
public static string ResolvePostgresConnectionString(string fallback) =>
Environment.GetEnvironmentVariable("REDB_POSTGRES_CS")?.Trim() is { Length: > 0 } cs
? cs
: !string.IsNullOrEmpty(fallback)
? fallback
: "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Maximum Pool Size=100;Include Error Detail=true";
///
/// The Postgres connection string of the run, for every place that needs it: the fixtures that
/// hand it to and the tests that open their own connection. One
/// resolution (: REDB_POSTGRES_CS, then
/// appsettings.json, then the local default), so a test's own connection reaches the same
/// database the server under test writes to, not whatever listens on the port named in the file.
///
public static string GetPostgresConnectionString(this Microsoft.Extensions.Configuration.IConfiguration configuration) =>
ResolvePostgresConnectionString(
Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(configuration, "Postgres") ?? string.Empty);
public static string ResolveMsSqlConnectionString() =>
Environment.GetEnvironmentVariable("REDB_MSSQL_CS")?.Trim() is { Length: > 0 } cs
? cs
// Max Pool Size=100 explicitly so the test-bench ceiling matches the PG
// appsettings.json value; Microsoft.Data.SqlClient's default is also 100
// but stating it makes the limit explicit when comparing logs across
// providers and matches the WithRedb-per-scope amplification headroom.
: "Server=127.0.0.1,1433;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;Max Pool Size=100;";
///
/// The SQLite database of this test process: one file per process under the temp dir, shared by every
/// fixture of the process, never by another process. Override via REDB_SQLITE_CS for a pinned path
/// or :memory:. Use when a single test needs to share storage
/// across multiple redb instances (multi-replica probes).
///
public static string ResolveSqliteConnectionString()
{
var pinned = Environment.GetEnvironmentVariable("REDB_SQLITE_CS")?.Trim();
if (!string.IsNullOrEmpty(pinned))
return pinned;
var path = CreateSqliteScratchPath();
// Once per test process, before anyone opens it: remove the files of test processes that no longer
// run (a killed run leaves its database with its -wal and -shm) and whatever an earlier process with
// this process id left, and remove this process's files when it ends. Guarded with Interlocked so
// that, of the fixtures resolving the path at once, only the first one sweeps.
if (Interlocked.Exchange(ref _sqliteScratchCleaned, 1) == 0)
{
SweepSqliteScratchFiles();
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
DeleteSqliteFiles(SqliteScratchPath);
};
}
return BuildSqliteConnectionString(path);
}
private const string SqliteScratchPrefix = "redb-test-identity-";
// Two test processes on one machine (two worktrees, or two sessions) must never share a database: a delivery
// worker of one process would deliver the outbox rows of the other.
private static readonly string SqliteScratchPath =
Path.Combine(Path.GetTempPath(), $"{SqliteScratchPrefix}{Environment.ProcessId}.db");
///
/// The SQLite database file of this test process. Use the resulting path in
/// twice (or more) when a test
/// needs multiple redb instances pointing at the same physical DB.
///
public static string CreateSqliteScratchPath() => SqliteScratchPath;
private static void SweepSqliteScratchFiles()
{
foreach (var file in Directory.EnumerateFiles(Path.GetTempPath(), SqliteScratchPrefix + "*.db"))
{
var pid = Path.GetFileNameWithoutExtension(file)[SqliteScratchPrefix.Length..];
if (!int.TryParse(pid, out var id)) continue;
if (id == Environment.ProcessId || !IsRunning(id)) DeleteSqliteFiles(file);
}
}
private static bool IsRunning(int processId)
{
try { using var process = System.Diagnostics.Process.GetProcessById(processId); return !process.HasExited; }
catch (ArgumentException) { return false; }
catch (InvalidOperationException) { return false; }
}
private static void DeleteSqliteFiles(string path)
{
foreach (var f in new[] { path, path + "-wal", path + "-shm" })
{
try { if (File.Exists(f)) File.Delete(f); }
catch (IOException) { /* still held: the next start sweeps it */ }
catch (UnauthorizedAccessException) { /* still held: the next start sweeps it */ }
}
}
/// Compose a SQLite connection string from a file path with the
/// per-test defaults (file-based, ReadWriteCreate, no shared cache —
/// shared cache would break WAL's reader-during-writer guarantee).
public static string BuildSqliteConnectionString(string filePath) =>
$"Data Source={filePath};Mode=ReadWriteCreate";
// ── SQLite native extension (Free path only; harmless on Pro) ────────
///
/// Free SQLite needs the native extension on every connection
/// (get_object_json / pvt_build_*_sql live inside it). Pro doesn't,
/// but setting the path is harmless. Best-effort: honour
/// REDB_SQLITE_EXTENSION if set, else walk parents looking for
/// redb.SQLite/native/build/redbsqlite.{dll,so,dylib}. Runs once per
/// process via interlocked flag.
///
private static void EnsureSqliteNativeExtensionResolved()
{
if (Interlocked.CompareExchange(ref _sqliteExtensionResolved, 1, 0) != 0) return;
if (!string.IsNullOrEmpty(SqliteDataSource.NativeExtensionPath)) return;
var fromEnv = Environment.GetEnvironmentVariable("REDB_SQLITE_EXTENSION")?.Trim();
if (!string.IsNullOrEmpty(fromEnv) && File.Exists(fromEnv))
{
SqliteDataSource.NativeExtensionPath = fromEnv;
return;
}
var suffix = OperatingSystem.IsWindows() ? ".dll"
: OperatingSystem.IsMacOS() ? ".dylib"
: ".so";
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent)
{
// Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src).
var candidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", "redbsqlite" + suffix);
if (!File.Exists(candidate))
candidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", "redbsqlite" + suffix);
if (File.Exists(candidate))
{
SqliteDataSource.NativeExtensionPath = candidate;
return;
}
}
}
// ── License loading ──────────────────────────────────────────────────
///
/// Read the Pro license JWT from redb.license next to the test
/// assembly. The file is shipped in the test project and copied to the
/// output dir by the csproj. Missing file → null, callers proceed with
/// the free tier.
///
private static string? LoadLicenseToken()
{
var path = Path.Combine(AppContext.BaseDirectory, "redb.license");
if (!File.Exists(path)) return null;
try
{
var token = File.ReadAllText(path).Trim();
return string.IsNullOrEmpty(token) ? null : token;
}
catch
{
return null;
}
}
}