PlotDirector/PlotLine.Tests/InvestigationMemoryRepository.cs

18 lines
2.6 KiB
C#

using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
// Isolated transport fixture. SQL isolation/concurrency/cascades are also qualified against Development separately.
internal sealed class InvestigationMemoryRepository:IInvestigationRepository
{
readonly Dictionary<string,string> catalogues=[];readonly Dictionary<Guid,string> rows=[];readonly Dictionary<Guid,List<string>> events=[];readonly object sync=new();string current="";
public InvestigationMemoryRepository(){var json=File.ReadAllText(Environment.GetEnvironmentVariable("PD_INV_CATALOGUE")??"Docs/Writer/Investigations/synthetic-catalogue.json");var c=CatalogueValidator.Parse(json);catalogues[c.Version]=json;current=c.Version;}
public Task<Catalogue?> Catalogue(string? version=null){lock(sync)return Task.FromResult(catalogues.TryGetValue(version??current,out var json)?CatalogueValidator.Parse(json):null);}
public Task Publish(string json,string actor){lock(sync){var c=CatalogueValidator.Parse(json);if(catalogues.ContainsKey(c.Version))throw new ArgumentException("Version already exists.");catalogues[c.Version]=json;current=c.Version;}return Task.CompletedTask;}
public Task<IReadOnlyList<Investigation>> List(int user,int book){lock(sync)return Task.FromResult<IReadOnlyList<Investigation>>(rows.Values.Select(Parse).Where(i=>i.UserID==user&&i.BookID==book).OrderByDescending(i=>i.UpdatedUtc).ToArray());}
public Task<Investigation?> Read(int user,int book,Guid id){lock(sync){var i=rows.TryGetValue(id,out var json)?Parse(json):null;return Task.FromResult(i?.UserID==user&&i.BookID==book?i:null);}}
public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;}
public Task<string[]> Replay(int user,int book,Guid id){lock(sync){if(!rows.TryGetValue(id,out var json)||Parse(json).UserID!=user||Parse(json).BookID!=book)throw new UnauthorizedAccessException();return Task.FromResult(events[id].ToArray());}}
static Investigation Parse(string json)=>JsonSerializer.Deserialize<Investigation>(json,CatalogueValidator.Json)!;
}