177 lines
6.1 KiB
C#
177 lines
6.1 KiB
C#
using System;
|
|
using System.Data;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using MySqlConnector;
|
|
|
|
namespace Server.Data;
|
|
|
|
public sealed class DatabaseManager : IDatabaseManager, IAsyncDisposable
|
|
{
|
|
private readonly DatabaseOptions _options;
|
|
private readonly ILogger<DatabaseManager> _logger;
|
|
|
|
public DatabaseManager(IOptions<DatabaseOptions> options, ILogger<DatabaseManager> logger)
|
|
{
|
|
_options = options.Value;
|
|
_logger = logger;
|
|
}
|
|
|
|
// ---------------------------
|
|
// Public API
|
|
// ---------------------------
|
|
|
|
public async Task<T> ExecuteAsync<T>(
|
|
Func<IDbConnection, Task<T>> operation,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
return await RetryAsync(async ct =>
|
|
{
|
|
await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct);
|
|
return await operation(mysqlConnection);
|
|
}, cancellationToken);
|
|
}
|
|
|
|
public async Task ExecuteAsync(
|
|
Func<IDbConnection, Task> operation,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
await RetryAsync(async ct =>
|
|
{
|
|
await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct);
|
|
await operation(mysqlConnection);
|
|
return true; // dummy value for non-generic path
|
|
}, cancellationToken);
|
|
}
|
|
|
|
public async Task<T> WithTransactionAsync<T>(
|
|
Func<IDbConnection, IDbTransaction, Task<T>> operation,
|
|
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
return await RetryAsync(async ct =>
|
|
{
|
|
await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct);
|
|
var transaction = await mysqlConnection.BeginTransactionAsync(isolationLevel, ct);
|
|
|
|
try
|
|
{
|
|
T result = await operation(mysqlConnection, transaction);
|
|
await transaction.CommitAsync(ct);
|
|
await DisposeTransactionAsync(transaction);
|
|
return result;
|
|
}
|
|
catch
|
|
{
|
|
await SafeRollbackAsync(transaction, ct);
|
|
await DisposeTransactionAsync(transaction);
|
|
throw;
|
|
}
|
|
}, cancellationToken);
|
|
}
|
|
|
|
public async Task WithTransactionAsync(
|
|
Func<IDbConnection, IDbTransaction, Task> operation,
|
|
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
await RetryAsync(async ct =>
|
|
{
|
|
await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct);
|
|
var transaction = await mysqlConnection.BeginTransactionAsync(isolationLevel, ct);
|
|
|
|
try
|
|
{
|
|
await operation(mysqlConnection, transaction);
|
|
await transaction.CommitAsync(ct);
|
|
await DisposeTransactionAsync(transaction);
|
|
return true;
|
|
}
|
|
catch
|
|
{
|
|
await SafeRollbackAsync(transaction, ct);
|
|
await DisposeTransactionAsync(transaction);
|
|
throw;
|
|
}
|
|
}, cancellationToken);
|
|
}
|
|
|
|
// ---------------------------
|
|
// Internals
|
|
// ---------------------------
|
|
|
|
private async Task<MySqlConnection> OpenNewConnectionAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(_options.ConnectionString))
|
|
throw new InvalidOperationException("Database connection string is not configured.");
|
|
|
|
var connection = new MySqlConnection(_options.ConnectionString);
|
|
await connection.OpenAsync(cancellationToken);
|
|
return connection;
|
|
}
|
|
|
|
private static async Task SafeRollbackAsync(IDbTransaction transaction, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
if (transaction is MySqlTransaction mySqlTx)
|
|
await mySqlTx.RollbackAsync(cancellationToken);
|
|
else
|
|
transaction.Rollback();
|
|
}
|
|
catch
|
|
{
|
|
// swallow rollback exceptions
|
|
}
|
|
}
|
|
|
|
private static async Task DisposeTransactionAsync(IDbTransaction transaction)
|
|
{
|
|
if (transaction is IAsyncDisposable asyncDisposableTx)
|
|
await asyncDisposableTx.DisposeAsync();
|
|
else
|
|
transaction.Dispose();
|
|
}
|
|
|
|
// Simple, robust retry with jittered backoff (replaces Polly to avoid API mismatch)
|
|
private async Task<T> RetryAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken)
|
|
{
|
|
int maxAttempts = Math.Max(1, _options.MaxRetryCount + 1); // attempts = retries + initial try
|
|
int baseDelayMs = Math.Max(10, _options.RetryBaseDelayMs);
|
|
|
|
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
|
{
|
|
try
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
return await operation(cancellationToken);
|
|
}
|
|
catch (Exception ex) when (IsTransient(ex) && attempt < maxAttempts)
|
|
{
|
|
var backoff = TimeSpan.FromMilliseconds(baseDelayMs * Math.Pow(2, attempt - 1));
|
|
var jitter = TimeSpan.FromMilliseconds(Random.Shared.Next(0, 50));
|
|
var delay = backoff + jitter;
|
|
|
|
_logger.LogWarning(ex, "DB transient error, attempt {Attempt}/{Max}. Retrying in {Delay} ms",
|
|
attempt, maxAttempts, (int)delay.TotalMilliseconds);
|
|
|
|
try { await Task.Delay(delay, cancellationToken); }
|
|
catch (OperationCanceledException) { throw; }
|
|
}
|
|
}
|
|
|
|
// Should never reach; loop either returns or throws.
|
|
throw new InvalidOperationException("Retry loop exited unexpectedly.");
|
|
}
|
|
|
|
private static bool IsTransient(Exception ex)
|
|
{
|
|
// Expand as needed with specific MySQL transient codes.
|
|
return ex is MySqlException or TimeoutException or InvalidOperationException;
|
|
}
|
|
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|