Files
crystall-punk-14/Content.Server/Database/ServerDbSqlite.cs
Ed 684ec72541 Upstrearm sync (#94)
* Fix for the salvage ice labs map. (#26928)

* done

* more work

* Automatic changelog update

* Update Credits (#26938)

Co-authored-by: PJBot <pieterjan.briers+bot@gmail.com>

* Fix cryostorage identifying unknown characters as captain (#26927)

Fixed cryostorage getting captain's record for unknown jobs.
Also localized Unknown job string.

* Automatic changelog update

* Fixed Honkbot/jonkbot honking like crazy, gave honkbot/jonkbot standard idle ai. (#26939)

* Fixed Honkbot/jonkbot honking like crazy, gave honkbot/jonkbot standard idle ai.

* Update Resources/Prototypes/Entities/Mobs/NPCs/silicon.yml

---------

Co-authored-by: Tayrtahn <tayrtahn@gmail.com>

* Automatic changelog update

* Bug fix: Force cancellation of RCD constructions if the construction type is changed (#26935)

Force cancellation of RCD constructions if the construction type is changed

* Fix standart -> standard and dressfilled test fail (#26942)

Fix standart -> standard

* Add Ability to stop sound when MobState is Dead (#26905)

* Add stopsWhenEntityDead to sound components

* Convert component

* Review

* Fix dupe sub

---------

Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>

* Automatic changelog update

* Fix rockets and lasers looking like they have nothing loaded (#26933)

* Automatic changelog update

* You can now see paper on crates (with color!) (#26834)

* Implement changes on not-cooked branch

* Made it work

* Fix update appearance calls

* Fix extra indents, clean-up code, fix tests hopefully

* Fix hammy cagecrate

* Fix messing up the yml, add artifact crate specific labels back in

* Visual Studio hates yml, sad

* Seperate the colors for cargonia

* sorry json

* make label move with artifact door

* Apply suggestion changes

Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>

* Fix remaining crate offsets, add a few for livestock and graves (why are you labeling graves) and coffin label sprites (why are you labeling coffins??)

---------

Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>

* Make UtensilSystem and SharpSystem not run AfterInteract if it has already been handled (#25826)

* Make UtensilSystem and SharpSystem not run AfterInteract if it has already been handled

* merge conflicts

---------

Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>

* Automatic changelog update

* Add two-message overload to PopupPredicted (#26907)

Added two-message overload to PopupPredicted

* Update submodule to 218.0.0 (#26945)

* Autism pins! (#25597)

* hee hee he ha ha

* added gold varients, forgive me for my spritework

* maints loot, copying from past PRs

* Trying to fix RSI

* speedran these sprites in break time, pictures will be later

* Fixed/Tweaked glows

* consensus

* gregregation

* dam copiryte

* oops i forgot to delete 2 fields hope this works

* Automatic changelog update

* Fix database round start date issues (#26838)

How can ONE DATABASE COLUMN have so many cursed issues I don't know, but it certainly pissed off the devil in its previous life.

The start_date column on round entities in the database was added by https://github.com/space-wizards/space-station-14/pull/21153. For some reason, this PR gave the column a nonsensical default value instead of making it nullable. This default value causes the code from #25280 to break. It actually trips an assert though that's not what the original issue report ran into.

This didn't get noticed on wizden servers because we at some point backfilled the start_date column based on the stored admin logs.

So I change the database model to make this column nullable, updated the C# code to match, and made the existing migration set the invalid values to be NULL instead. Cool.

Wait how's SQLite handle in this scenario anyways? Well actually turns out the column was *completely broken* in the first place!

The code for inserting into the round table was copy pasted between SQLite and PostgreSQL, with the only difference being that the SQLite key manually assigned the primary key instead of letting SQLite AUTOINCREMENT it. And then the code to give a start_date value was only added to the PostgreSQL version (which is actually in the base class already). So for SQLite that column's been filled up with the same invalid default the whole time.

Why was the code manually assigning a PK? I checked the SQLite docs for AUTOINCREMENT[1], and the behavior seems appropriate.

I removed the SQLite-specific code path and it just seems to work regardless. The migration just sets the old values to NULL too.

BUT WAIT, THERE'S MORE!

Turns out just doing the migration on SQLite is a pain in the ass! EF Core has to create a new table to apply the nullability change, because SQLite doesn't support proper ALTER COLUMN. This causes the generated SQL commands to be weird and the UPDATE for the migration goes BEFORE the nullability change... I ended up having to make TWO migrations for SQLite. Yay.

Fixes #26800

[1]: https://www.sqlite.org/autoinc.html

* Fix options menu crashing in replays (#26911)

Not having the nullable set properly is annoying but fixing that would probably be a significant amount of work.

* Greyscale color clothing (#26943)

* greyscales color gloves, color jumpsuits, and shoes

* remove popbob

* fix test fails

* Automatic changelog update

* WT550 Buffs + Burst Mode for WT550 & C-20R (#26886)

* Slightly increased WT550 Firerate, drastically reduced recoil, and given it the option to fire in 5 round bursts.

* Given the C-20 a 5 round burst aswell

* Automatic changelog update

* make holoparasites actually holographic (#26862)

it's over

* Automatic changelog update

* Add character sheets to board game crate (#26926)

add character sheets to board game crate

* Automatic changelog update

* Game server admin API (#26880)

* Reapply "Game server api" (#26871)

This reverts commit 3aee197923.

* Rewrite 75% of the code it's good now

* Wield recoil components (#26915)

* WieldRecoilComponents

* WieldRecoilComponents

* Update Content.Shared/Weapons/Ranged/Components/GunWieldBonusComponent.cs

Co-authored-by: Whisper <121047731+QuietlyWhisper@users.noreply.github.com>

* Update Content.Shared/Weapons/Ranged/Components/GunWieldBonusComponent.cs

---------

Co-authored-by: Whisper <121047731+QuietlyWhisper@users.noreply.github.com>
Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>

* Clown shoes make you waddle, as God intended (#26338)

* Clown shoes make you waddle, as God intended

* OOPS

* Toned down, client system name fix

* Tidy namespacing for @deltanedas

* Refactor to handle prediction better, etc.

* Resolve PR comments.

* Automatic changelog update

* Use round time instead of server time for criminal history (#26949)

make criminal records computer use round time for history instead of the server time

* Rotate and Offset station CCVar nuke (#26175)

* no content

* add noRot to Europa

* bruh. and this

* yay

* fix

* Update debug.yml

---------

Co-authored-by: Boaz1111 <149967078+Boaz1111@users.noreply.github.com>
Co-authored-by: PJBot <pieterjan.briers+bot@gmail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Tayrtahn <tayrtahn@gmail.com>
Co-authored-by: superjj18 <gagnonjake@gmail.com>
Co-authored-by: chromiumboy <50505512+chromiumboy@users.noreply.github.com>
Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
Co-authored-by: GreaseMonk <1354802+GreaseMonk@users.noreply.github.com>
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
Co-authored-by: DrSmugleaf <10968691+DrSmugleaf@users.noreply.github.com>
Co-authored-by: Verm <32827189+Vermidia@users.noreply.github.com>
Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
Co-authored-by: Terraspark4941 <terraspark4941@gmail.com>
Co-authored-by: Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
Co-authored-by: Flareguy <78941145+Flareguy@users.noreply.github.com>
Co-authored-by: BramvanZijp <56019239+BramvanZijp@users.noreply.github.com>
Co-authored-by: Mr. 27 <45323883+Dutch-VanDerLinde@users.noreply.github.com>
Co-authored-by: Tyzemol <85772526+Tyzemol@users.noreply.github.com>
Co-authored-by: Froffy025 <78222136+Froffy025@users.noreply.github.com>
Co-authored-by: Whisper <121047731+QuietlyWhisper@users.noreply.github.com>
Co-authored-by: Hannah Giovanna Dawson <karakkaraz@gmail.com>
Co-authored-by: ilya.mikheev.coder <imc-ext+github@ilyamikcoder.com>
2024-04-14 20:34:16 +03:00

621 lines
21 KiB
C#

using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Content.Server.Administration.Logs;
using Content.Server.IP;
using Content.Server.Preferences.Managers;
using Content.Shared.CCVar;
using Microsoft.EntityFrameworkCore;
using Robust.Shared.Configuration;
using Robust.Shared.Network;
using Robust.Shared.Utility;
namespace Content.Server.Database
{
/// <summary>
/// Provides methods to retrieve and update character preferences.
/// Don't use this directly, go through <see cref="ServerPreferencesManager" /> instead.
/// </summary>
public sealed class ServerDbSqlite : ServerDbBase
{
private readonly Func<DbContextOptions<SqliteServerDbContext>> _options;
private readonly ConcurrencySemaphore _prefsSemaphore;
private readonly Task _dbReadyTask;
private int _msDelay;
public ServerDbSqlite(
Func<DbContextOptions<SqliteServerDbContext>> options,
bool inMemory,
IConfigurationManager cfg,
bool synchronous,
ISawmill opsLog)
: base(opsLog)
{
_options = options;
var prefsCtx = new SqliteServerDbContext(options());
// When inMemory we re-use the same connection, so we can't have any concurrency.
var concurrency = inMemory ? 1 : cfg.GetCVar(CCVars.DatabaseSqliteConcurrency);
_prefsSemaphore = new ConcurrencySemaphore(concurrency, synchronous);
if (synchronous)
{
prefsCtx.Database.Migrate();
_dbReadyTask = Task.CompletedTask;
prefsCtx.Dispose();
}
else
{
_dbReadyTask = Task.Run(() =>
{
prefsCtx.Database.Migrate();
prefsCtx.Dispose();
});
}
cfg.OnValueChanged(CCVars.DatabaseSqliteDelay, v => _msDelay = v, true);
}
#region Ban
public override async Task<ServerBanDef?> GetServerBanAsync(int id)
{
await using var db = await GetDbImpl();
var ban = await db.SqliteDbContext.Ban
.Include(p => p.Unban)
.Where(p => p.Id == id)
.SingleOrDefaultAsync();
return ConvertBan(ban);
}
public override async Task<ServerBanDef?> GetServerBanAsync(
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId)
{
await using var db = await GetDbImpl();
var exempt = await GetBanExemptionCore(db, userId);
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var bans = await GetAllBans(db.SqliteDbContext, includeUnbanned: false, exempt);
return bans.FirstOrDefault(b => BanMatches(b, address, userId, hwId, exempt)) is { } foundBan
? ConvertBan(foundBan)
: null;
}
public override async Task<List<ServerBanDef>> GetServerBansAsync(IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId, bool includeUnbanned)
{
await using var db = await GetDbImpl();
var exempt = await GetBanExemptionCore(db, userId);
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var queryBans = await GetAllBans(db.SqliteDbContext, includeUnbanned, exempt);
return queryBans
.Where(b => BanMatches(b, address, userId, hwId, exempt))
.Select(ConvertBan)
.ToList()!;
}
private static async Task<List<ServerBan>> GetAllBans(
SqliteServerDbContext db,
bool includeUnbanned,
ServerBanExemptFlags? exemptFlags)
{
IQueryable<ServerBan> query = db.Ban.Include(p => p.Unban);
if (!includeUnbanned)
{
query = query.Where(p =>
p.Unban == null && (p.ExpirationTime == null || p.ExpirationTime.Value > DateTime.UtcNow));
}
if (exemptFlags is { } exempt)
{
query = query.Where(b => (b.ExemptFlags & exempt) == 0);
}
return await query.ToListAsync();
}
private static bool BanMatches(ServerBan ban,
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId,
ServerBanExemptFlags? exemptFlags)
{
if (!exemptFlags.GetValueOrDefault(ServerBanExemptFlags.None).HasFlag(ServerBanExemptFlags.IP)
&& address != null && ban.Address is not null && address.IsInSubnet(ban.Address.ToTuple().Value))
{
return true;
}
if (userId is { } id && ban.PlayerUserId == id.UserId)
{
return true;
}
return hwId is { Length: > 0 } hwIdVar && hwIdVar.AsSpan().SequenceEqual(ban.HWId);
}
public override async Task AddServerBanAsync(ServerBanDef serverBan)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.Ban.Add(new ServerBan
{
Address = serverBan.Address.ToNpgsqlInet(),
Reason = serverBan.Reason,
Severity = serverBan.Severity,
BanningAdmin = serverBan.BanningAdmin?.UserId,
HWId = serverBan.HWId?.ToArray(),
BanTime = serverBan.BanTime.UtcDateTime,
ExpirationTime = serverBan.ExpirationTime?.UtcDateTime,
RoundId = serverBan.RoundId,
PlaytimeAtNote = serverBan.PlaytimeAtNote,
PlayerUserId = serverBan.UserId?.UserId
});
await db.SqliteDbContext.SaveChangesAsync();
}
public override async Task AddServerUnbanAsync(ServerUnbanDef serverUnban)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.Unban.Add(new ServerUnban
{
BanId = serverUnban.BanId,
UnbanningAdmin = serverUnban.UnbanningAdmin?.UserId,
UnbanTime = serverUnban.UnbanTime.UtcDateTime
});
await db.SqliteDbContext.SaveChangesAsync();
}
#endregion
#region Role Ban
public override async Task<ServerRoleBanDef?> GetServerRoleBanAsync(int id)
{
await using var db = await GetDbImpl();
var ban = await db.SqliteDbContext.RoleBan
.Include(p => p.Unban)
.Where(p => p.Id == id)
.SingleOrDefaultAsync();
return ConvertRoleBan(ban);
}
public override async Task<List<ServerRoleBanDef>> GetServerRoleBansAsync(
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId,
bool includeUnbanned)
{
await using var db = await GetDbImpl();
// SQLite can't do the net masking stuff we need to match IP address ranges.
// So just pull down the whole list into memory.
var queryBans = await GetAllRoleBans(db.SqliteDbContext, includeUnbanned);
return queryBans
.Where(b => RoleBanMatches(b, address, userId, hwId))
.Select(ConvertRoleBan)
.ToList()!;
}
private static async Task<List<ServerRoleBan>> GetAllRoleBans(
SqliteServerDbContext db,
bool includeUnbanned)
{
IQueryable<ServerRoleBan> query = db.RoleBan.Include(p => p.Unban);
if (!includeUnbanned)
{
query = query.Where(p =>
p.Unban == null && (p.ExpirationTime == null || p.ExpirationTime.Value > DateTime.UtcNow));
}
return await query.ToListAsync();
}
private static bool RoleBanMatches(
ServerRoleBan ban,
IPAddress? address,
NetUserId? userId,
ImmutableArray<byte>? hwId)
{
if (address != null && ban.Address is not null && address.IsInSubnet(ban.Address.ToTuple().Value))
{
return true;
}
if (userId is { } id && ban.PlayerUserId == id.UserId)
{
return true;
}
return hwId is { Length: > 0 } hwIdVar && hwIdVar.AsSpan().SequenceEqual(ban.HWId);
}
public override async Task<ServerRoleBanDef> AddServerRoleBanAsync(ServerRoleBanDef serverBan)
{
await using var db = await GetDbImpl();
var ban = new ServerRoleBan
{
Address = serverBan.Address.ToNpgsqlInet(),
Reason = serverBan.Reason,
Severity = serverBan.Severity,
BanningAdmin = serverBan.BanningAdmin?.UserId,
HWId = serverBan.HWId?.ToArray(),
BanTime = serverBan.BanTime.UtcDateTime,
ExpirationTime = serverBan.ExpirationTime?.UtcDateTime,
RoundId = serverBan.RoundId,
PlaytimeAtNote = serverBan.PlaytimeAtNote,
PlayerUserId = serverBan.UserId?.UserId,
RoleId = serverBan.Role,
};
db.SqliteDbContext.RoleBan.Add(ban);
await db.SqliteDbContext.SaveChangesAsync();
return ConvertRoleBan(ban);
}
public override async Task AddServerRoleUnbanAsync(ServerRoleUnbanDef serverUnban)
{
await using var db = await GetDbImpl();
db.SqliteDbContext.RoleUnban.Add(new ServerRoleUnban
{
BanId = serverUnban.BanId,
UnbanningAdmin = serverUnban.UnbanningAdmin?.UserId,
UnbanTime = serverUnban.UnbanTime.UtcDateTime
});
await db.SqliteDbContext.SaveChangesAsync();
}
[return: NotNullIfNotNull(nameof(ban))]
private static ServerRoleBanDef? ConvertRoleBan(ServerRoleBan? ban)
{
if (ban == null)
{
return null;
}
NetUserId? uid = null;
if (ban.PlayerUserId is { } guid)
{
uid = new NetUserId(guid);
}
NetUserId? aUid = null;
if (ban.BanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
var unban = ConvertRoleUnban(ban.Unban);
return new ServerRoleBanDef(
ban.Id,
uid,
ban.Address.ToTuple(),
ban.HWId == null ? null : ImmutableArray.Create(ban.HWId),
// SQLite apparently always reads DateTime as unspecified, but we always write as UTC.
DateTime.SpecifyKind(ban.BanTime, DateTimeKind.Utc),
ban.ExpirationTime == null ? null : DateTime.SpecifyKind(ban.ExpirationTime.Value, DateTimeKind.Utc),
ban.RoundId,
ban.PlaytimeAtNote,
ban.Reason,
ban.Severity,
aUid,
unban,
ban.RoleId);
}
private static ServerRoleUnbanDef? ConvertRoleUnban(ServerRoleUnban? unban)
{
if (unban == null)
{
return null;
}
NetUserId? aUid = null;
if (unban.UnbanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
return new ServerRoleUnbanDef(
unban.Id,
aUid,
// SQLite apparently always reads DateTime as unspecified, but we always write as UTC.
DateTime.SpecifyKind(unban.UnbanTime, DateTimeKind.Utc));
}
#endregion
private static ServerBanDef? ConvertBan(ServerBan? ban)
{
if (ban == null)
{
return null;
}
NetUserId? uid = null;
if (ban.PlayerUserId is { } guid)
{
uid = new NetUserId(guid);
}
NetUserId? aUid = null;
if (ban.BanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
var unban = ConvertUnban(ban.Unban);
return new ServerBanDef(
ban.Id,
uid,
ban.Address.ToTuple(),
ban.HWId == null ? null : ImmutableArray.Create(ban.HWId),
// SQLite apparently always reads DateTime as unspecified, but we always write as UTC.
DateTime.SpecifyKind(ban.BanTime, DateTimeKind.Utc),
ban.ExpirationTime == null ? null : DateTime.SpecifyKind(ban.ExpirationTime.Value, DateTimeKind.Utc),
ban.RoundId,
ban.PlaytimeAtNote,
ban.Reason,
ban.Severity,
aUid,
unban);
}
private static ServerUnbanDef? ConvertUnban(ServerUnban? unban)
{
if (unban == null)
{
return null;
}
NetUserId? aUid = null;
if (unban.UnbanningAdmin is { } aGuid)
{
aUid = new NetUserId(aGuid);
}
return new ServerUnbanDef(
unban.Id,
aUid,
// SQLite apparently always reads DateTime as unspecified, but we always write as UTC.
DateTime.SpecifyKind(unban.UnbanTime, DateTimeKind.Utc));
}
public override async Task<int> AddConnectionLogAsync(
NetUserId userId,
string userName,
IPAddress address,
ImmutableArray<byte> hwId,
ConnectionDenyReason? denied,
int serverId)
{
await using var db = await GetDbImpl();
var connectionLog = new ConnectionLog
{
Address = address,
Time = DateTime.UtcNow,
UserId = userId.UserId,
UserName = userName,
HWId = hwId.ToArray(),
Denied = denied,
ServerId = serverId
};
db.SqliteDbContext.ConnectionLog.Add(connectionLog);
await db.SqliteDbContext.SaveChangesAsync();
return connectionLog.Id;
}
public override async Task<((Admin, string? lastUserName)[] admins, AdminRank[])> GetAllAdminAndRanksAsync(
CancellationToken cancel)
{
await using var db = await GetDbImpl();
var admins = await db.SqliteDbContext.Admin
.Include(a => a.Flags)
.GroupJoin(db.SqliteDbContext.Player, a => a.UserId, p => p.UserId, (a, grouping) => new {a, grouping})
.SelectMany(t => t.grouping.DefaultIfEmpty(), (t, p) => new {t.a, p!.LastSeenUserName})
.ToArrayAsync(cancel);
var adminRanks = await db.DbContext.AdminRank.Include(a => a.Flags).ToArrayAsync(cancel);
return (admins.Select(p => (p.a, p.LastSeenUserName)).ToArray(), adminRanks)!;
}
protected override IQueryable<AdminLog> StartAdminLogsQuery(ServerDbContext db, LogFilter? filter = null)
{
IQueryable<AdminLog> query = db.AdminLog;
if (filter?.Search != null)
query = query.Where(log => EF.Functions.Like(log.Message, $"%{filter.Search}%"));
return query;
}
public override async Task<int> AddAdminNote(AdminNote note)
{
await using (var db = await GetDb())
{
var nextId = 1;
if (await db.DbContext.AdminNotes.AnyAsync())
{
nextId = await db.DbContext.AdminNotes.MaxAsync(adminNote => adminNote.Id) + 1;
}
note.Id = nextId;
}
return await base.AddAdminNote(note);
}
public override async Task<int> AddAdminWatchlist(AdminWatchlist watchlist)
{
await using (var db = await GetDb())
{
var nextId = 1;
if (await db.DbContext.AdminWatchlists.AnyAsync())
{
nextId = await db.DbContext.AdminWatchlists.MaxAsync(adminWatchlist => adminWatchlist.Id) + 1;
}
watchlist.Id = nextId;
}
return await base.AddAdminWatchlist(watchlist);
}
public override async Task<int> AddAdminMessage(AdminMessage message)
{
await using (var db = await GetDb())
{
var nextId = 1;
if (await db.DbContext.AdminMessages.AnyAsync())
{
nextId = await db.DbContext.AdminMessages.MaxAsync(adminMessage => adminMessage.Id) + 1;
}
message.Id = nextId;
}
return await base.AddAdminMessage(message);
}
protected override DateTime NormalizeDatabaseTime(DateTime time)
{
DebugTools.Assert(time.Kind == DateTimeKind.Unspecified);
return DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
private async Task<DbGuardImpl> GetDbImpl([CallerMemberName] string? name = null)
{
LogDbOp(name);
await _dbReadyTask;
if (_msDelay > 0)
await Task.Delay(_msDelay);
await _prefsSemaphore.WaitAsync();
var dbContext = new SqliteServerDbContext(_options());
return new DbGuardImpl(this, dbContext);
}
protected override async Task<DbGuard> GetDb([CallerMemberName] string? name = null)
{
return await GetDbImpl(name).ConfigureAwait(false);
}
private sealed class DbGuardImpl : DbGuard
{
private readonly ServerDbSqlite _db;
private readonly SqliteServerDbContext _ctx;
public DbGuardImpl(ServerDbSqlite db, SqliteServerDbContext dbContext)
{
_db = db;
_ctx = dbContext;
}
public override ServerDbContext DbContext => _ctx;
public SqliteServerDbContext SqliteDbContext => _ctx;
public override async ValueTask DisposeAsync()
{
await _ctx.DisposeAsync();
_db._prefsSemaphore.Release();
}
}
private sealed class ConcurrencySemaphore
{
private readonly bool _synchronous;
private readonly SemaphoreSlim _semaphore;
private Thread? _holdingThread;
public ConcurrencySemaphore(int maxCount, bool synchronous)
{
if (synchronous && maxCount != 1)
throw new ArgumentException("If synchronous, max concurrency must be 1");
_synchronous = synchronous;
_semaphore = new SemaphoreSlim(maxCount, maxCount);
}
public Task WaitAsync()
{
var task = _semaphore.WaitAsync();
if (_synchronous)
{
if (!task.IsCompleted)
{
if (Thread.CurrentThread == _holdingThread)
{
throw new InvalidOperationException(
"Multiple database requests from same thread on synchronous database!");
}
throw new InvalidOperationException(
$"Different threads trying to access the database at once! " +
$"Holding thread: {DiagThread(_holdingThread)}, " +
$"current thread: {DiagThread(Thread.CurrentThread)}");
}
_holdingThread = Thread.CurrentThread;
}
return task;
}
public void Release()
{
if (_synchronous)
{
if (Thread.CurrentThread != _holdingThread)
throw new InvalidOperationException("Released on different thread than took lock???");
_holdingThread = null;
}
_semaphore.Release();
}
private static string DiagThread(Thread? thread)
{
if (thread != null)
return $"{thread.Name} ({thread.ManagedThreadId})";
return "<null thread>";
}
}
}
}