1
0
mirror of https://github.com/ppy/osu.git synced 2024-11-06 15:17:28 +08:00
osu-lazer/osu.Game/Database/DatabaseContextFactory.cs

137 lines
5.1 KiB
C#
Raw Normal View History

2018-04-13 17:19:50 +08:00
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Linq;
2018-04-13 17:19:50 +08:00
using System.Threading;
using Microsoft.EntityFrameworkCore.Storage;
2018-04-13 17:19:50 +08:00
using osu.Framework.Platform;
namespace osu.Game.Database
{
public class DatabaseContextFactory : IDatabaseContextFactory
{
private readonly GameHost host;
private const string database_name = @"client";
private ThreadLocal<OsuDbContext> threadContexts;
private readonly object writeLock = new object();
private bool currentWriteDidWrite;
private bool currentWriteDidError;
2018-04-13 17:19:50 +08:00
private int currentWriteUsages;
private IDbContextTransaction currentWriteTransaction;
2018-04-13 17:19:50 +08:00
public DatabaseContextFactory(GameHost host)
{
this.host = host;
recycleThreadContexts();
}
/// <summary>
/// Get a context for the current thread for read-only usage.
/// If a <see cref="DatabaseWriteUsage"/> is in progress, the existing write-safe context will be returned.
/// </summary>
public OsuDbContext Get() => threadContexts.Value;
/// <summary>
/// Request a context for write usage. Can be consumed in a nested fashion (and will return the same underlying context).
/// This method may block if a write is already active on a different thread.
/// </summary>
/// <param name="withTransaction">Whether to start a transaction for this write.</param>
2018-04-13 17:19:50 +08:00
/// <returns>A usage containing a usable context.</returns>
public DatabaseWriteUsage GetForWrite(bool withTransaction = true)
2018-04-13 17:19:50 +08:00
{
Monitor.Enter(writeLock);
OsuDbContext context;
2018-04-13 17:19:50 +08:00
try
{
if (currentWriteTransaction == null && withTransaction)
{
// this mitigates the fact that changes on tracked entities will not be rolled back with the transaction by ensuring write operations are always executed in isolated contexts.
// if this results in sub-optimal efficiency, we may need to look into removing Database-level transactions in favour of running SaveChanges where we currently commit the transaction.
if (threadContexts.IsValueCreated)
recycleThreadContexts();
context = threadContexts.Value;
currentWriteTransaction = context.Database.BeginTransaction();
}
else
{
// we want to try-catch the retrieval of the context because it could throw an error (in CreateContext).
context = threadContexts.Value;
}
}
catch (Exception e)
{
// retrieval of a context could trigger a fatal error.
Monitor.Exit(writeLock);
throw;
}
2018-04-13 17:19:50 +08:00
Interlocked.Increment(ref currentWriteUsages);
return new DatabaseWriteUsage(context, usageCompleted) { IsTransactionLeader = currentWriteTransaction != null && currentWriteUsages == 1 };
2018-04-13 17:19:50 +08:00
}
private void usageCompleted(DatabaseWriteUsage usage)
{
int usages = Interlocked.Decrement(ref currentWriteUsages);
try
{
currentWriteDidWrite |= usage.PerformedWrite;
currentWriteDidError |= usage.Errors.Any();
2018-04-13 17:19:50 +08:00
if (usages == 0)
2018-04-13 17:19:50 +08:00
{
if (currentWriteDidError)
currentWriteTransaction?.Rollback();
else
currentWriteTransaction?.Commit();
if (currentWriteDidWrite || currentWriteDidError)
{
// explicitly dispose to ensure any outstanding flushes happen as soon as possible (and underlying resources are purged).
usage.Context.Dispose();
// once all writes are complete, we want to refresh thread-specific contexts to make sure they don't have stale local caches.
recycleThreadContexts();
}
currentWriteTransaction = null;
currentWriteDidWrite = false;
currentWriteDidError = false;
2018-04-13 17:19:50 +08:00
}
}
finally
{
Monitor.Exit(writeLock);
}
}
private void recycleThreadContexts() => threadContexts = new ThreadLocal<OsuDbContext>(CreateContext);
protected virtual OsuDbContext CreateContext() => new OsuDbContext(host.Storage.GetDatabaseConnectionString(database_name))
2018-04-13 17:19:50 +08:00
{
Database = { AutoTransactionsEnabled = false }
};
2018-04-13 17:19:50 +08:00
public void ResetDatabase()
{
lock (writeLock)
{
recycleThreadContexts();
GC.Collect();
GC.WaitForPendingFinalizers();
2018-04-13 17:19:50 +08:00
host.Storage.DeleteDatabase(database_name);
}
}
}
}