41 lines
2.5 KiB
C#
41 lines
2.5 KiB
C#
using PlotLine.Models;
|
|
namespace PlotLine.Services;
|
|
|
|
// Author-bound immutable uploads. Register before reading so slow earlier requests cannot supersede newer files.
|
|
public sealed class BookRecoveryUploads
|
|
{
|
|
private sealed record Entry(int User, string Json, DateTime Expires, string Name);
|
|
private readonly object gate = new();
|
|
private readonly Dictionary<Guid, Entry> items = [];
|
|
private readonly Dictionary<int, (Guid Version, DateTime Expires)> generations = [];
|
|
public Guid Begin(int user)
|
|
{
|
|
lock (gate)
|
|
{
|
|
foreach (var key in items.Where(p => p.Value.Expires < DateTime.UtcNow || p.Value.User == user).Select(p => p.Key).ToArray()) items.Remove(key);
|
|
foreach (var key in generations.Where(p => p.Value.Expires < DateTime.UtcNow).Select(p => p.Key).ToArray()) generations.Remove(key);
|
|
if (!generations.ContainsKey(user) && generations.Count >= 4096) throw new ArgumentException("Backup workspace is busy. Try again shortly.");
|
|
var version = Guid.NewGuid(); generations[user] = (version, DateTime.UtcNow.AddMinutes(30)); return version;
|
|
}
|
|
}
|
|
public Guid Add(int user, string json, string name = "", Guid? generation = null)
|
|
{
|
|
lock (gate)
|
|
{
|
|
var version = generation ?? Begin(user);
|
|
if (!generations.TryGetValue(user, out var latest) || latest.Version != version || latest.Expires < DateTime.UtcNow) throw new ArgumentException("A newer backup replaced this request. Choose your latest file again.");
|
|
if (json.Length * 2L + items.Values.Sum(x => x.Json.Length * 2L) > 128 * 1024 * 1024) throw new ArgumentException("Backup workspace is busy. Try again shortly.");
|
|
var filename = Path.GetFileName(name.Replace('\\', '/')); if (filename.Length > 200) filename = filename[..200];
|
|
items.Add(version, new(user, json, latest.Expires, filename)); return version;
|
|
}
|
|
}
|
|
private Entry EntryFor(int user, Guid id)
|
|
{
|
|
if (!items.TryGetValue(id, out var entry) || entry.User != user) throw new UnauthorizedAccessException();
|
|
if (entry.Expires < DateTime.UtcNow) throw new ArgumentException("Upload expired. Choose the file again.");
|
|
return entry;
|
|
}
|
|
public string Name(int user, Guid id) { lock (gate) return EntryFor(user, id).Name; }
|
|
public BookBackupPackage Get(int user, Guid id) { string json; lock (gate) json = EntryFor(user, id).Json; return BookRecoveryService.Read(json); }
|
|
}
|