using Titano.Data;
using Titano.Server.Configuration;
namespace Titano.Server.Hosting;
/// Opens and migrates the server database at startup (BRIEF ยง6.1), waiting for a PostgreSQL container that is still starting.
public static class ServerDatabase
{
private const int Attempts = 10;
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(3);
public static async Task OpenAsync(ServerOptions options, ILogger logger, CancellationToken cancellationToken)
{
var settings = options.ToDatabaseOptions();
for (var attempt = 1; ; attempt++)
{
try
{
var db = await TitanoDatabase.OpenAsync(settings, cancellationToken).ConfigureAwait(false);
logger.LogInformation("Database {Dialect} ready, schema version {Version}", db.Dialect, db.SchemaVersion);
return db;
}
catch (DatabaseConnectionException ex) when (attempt < Attempts)
{
logger.LogWarning("Database not reachable yet ({Reason}); retry {Attempt} of {Attempts} in {Delay} s",
ex.Message, attempt, Attempts - 1, RetryDelay.TotalSeconds);
await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false);
}
}
}
/// Engine and version, e.g. "PostgreSQL 17.2" or "SQLite 3.45.1".
public static async Task DescribeAsync(TitanoDatabase db, CancellationToken cancellationToken)
{
await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false);
var postgres = db.Dialect == Dialect.Postgres;
var version = await session.ScalarAsync(postgres ? "SHOW server_version" : "SELECT sqlite_version()", [], cancellationToken).ConfigureAwait(false);
var number = version?.Split(' ', 2)[0] ?? string.Empty;
return (postgres ? "PostgreSQL " : "SQLite ") + number;
}
}