using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Loader; using System.Security.Cryptography; using System.Text; using System.Threading.Channels; using EvilEngine.Formats; using EvilEngine.Mounts; namespace EvilEngine.Conversion; public sealed record StoredInput(VirtualPath Path, string? Layer, long Length, string? Hash); public sealed record StoredEntry(ContentKind Kind, ContentId Id, string Code, string Hash, long Length) { public required string Converter { get; init; } public required int ConverterVersion { get; init; } public required string Bindings { get; init; } public IReadOnlyList Inputs { get; init; } = []; public IReadOnlyList Listings { get; init; } = []; public IReadOnlyList References { get; init; } = []; public IReadOnlyList Diagnostics { get; init; } = []; } public sealed class DiskConversionCache : IDisposable { private const int Format = 1; private static readonly byte[] Magic = "EVCE"u8.ToArray(); private static readonly ConcurrentDictionary Codes = new(); private readonly Lock _trimming = new(); private readonly Func _worth; private readonly Task _writer; private readonly Channel<(ConvertedContent Content, string Code, TimeSpan Took)> _writes = Channel.CreateBounded<(ConvertedContent, string, TimeSpan)>(new BoundedChannelOptions(256) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true }); private long _bytes = -1; private int _pending; public DiskConversionCache(string root, long budget, Func? worth = null) { Root = root; Budget = budget; _worth = worth ?? ((took, check) => took > check); _writer = Task.Run(Write); } public string Root { get; } public long Budget { get; } public int Written { get; private set; } public int Skipped { get; private set; } public void Dispose() { _writes.Writer.TryComplete(); _writer.Wait(); } public static string Code(IEnumerable converters) { return string.Join(';', converters.Select(converter => Codes.GetOrAdd(converter.GetType(), Closure))); } public StoredEntry? Find(ContentKind kind, ContentId id) { var path = EntryPath(kind, id); try { if (!File.Exists(path)) return null; using var reader = new BinaryReader(File.OpenRead(path), Encoding.UTF8); var entry = ReadEntry(reader); if (entry is null || entry.Kind != kind || entry.Id != id) return null; File.SetLastWriteTimeUtc(path, DateTime.UtcNow); return entry; } catch (Exception error) when (error is IOException or UnauthorizedAccessException or EndOfStreamException or FormatException or ArgumentException) { return null; } } public byte[]? Read(StoredEntry entry) { try { var bytes = File.ReadAllBytes(ObjectPath(entry.Hash)); return bytes.Length == entry.Length ? bytes : null; } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { return null; } } public void Store(ConvertedContent content, string code, TimeSpan took) { Interlocked.Increment(ref _pending); if (!_writes.Writer.TryWrite((content, code, took))) Interlocked.Decrement(ref _pending); } public void Flush() { SpinWait.SpinUntil(() => Volatile.Read(ref _pending) == 0); } public long Trim(long keep) { return Sweep(keep, keep); } public void Measure() { Sweep(Budget, Budget * 9 / 10); } private long Sweep(long limit, long keep) { lock (_trimming) { var entries = new List<(string Path, DateTime Used, string Hash)>(); foreach (var path in Files("entries")) try { using var reader = new BinaryReader(File.OpenRead(path), Encoding.UTF8); if (ReadEntry(reader) is { } entry) entries.Add((path, File.GetLastWriteTimeUtc(path), entry.Hash)); else Delete(path); } catch (Exception error) when (error is IOException or UnauthorizedAccessException or EndOfStreamException or FormatException or ArgumentException) { Delete(path); } var sizes = new Dictionary(StringComparer.Ordinal); foreach (var path in Files("objects")) sizes[Path.GetFileName(path)] = new FileInfo(path).Length; var users = entries.GroupBy(entry => entry.Hash).ToDictionary(group => group.Key, group => group.Count()); var released = 0L; foreach (var (hash, size) in sizes) if (!users.ContainsKey(hash)) { Delete(ObjectPath(hash)); released += size; } var total = users.Keys.Sum(hash => sizes.GetValueOrDefault(hash)); var target = total > limit ? keep : long.MaxValue; foreach (var entry in entries.OrderBy(entry => entry.Used)) { if (total <= target) break; Delete(entry.Path); if (--users[entry.Hash] > 0 || !sizes.TryGetValue(entry.Hash, out var size)) continue; Delete(ObjectPath(entry.Hash)); total -= size; released += size; } Interlocked.Exchange(ref _bytes, total); return released; } } private async Task Write() { await foreach (var (content, code, took) in _writes.Reader.ReadAllAsync()) try { Persist(content, code, took); } catch (Exception error) when (error is IOException or UnauthorizedAccessException or InvalidOperationException or FileNotFoundException) { Skipped++; } finally { Interlocked.Decrement(ref _pending); } } private void Persist(ConvertedContent content, string code, TimeSpan took) { var clock = Stopwatch.StartNew(); var inputs = content.Inputs .Select(input => new StoredInput(input.Path, input.Layer, input.Stamp?.Length ?? 0, input.Stamp?.Hash)) .ToArray(); if (!_worth(took, clock.Elapsed)) { Skipped++; return; } var objectPath = ObjectPath(content.Hash); var added = 0L; if (!File.Exists(objectPath) || new FileInfo(objectPath).Length != content.Data.Length) { Atomic(objectPath, stream => stream.Write(content.Data.Span)); added += content.Data.Length; } var entry = new StoredEntry(content.Kind, content.Id, code, content.Hash, content.Data.Length) { Converter = content.Converter, ConverterVersion = content.ConverterVersion, Bindings = content.Bindings, Inputs = inputs, Listings = content.Listings, References = content.References, Diagnostics = content.Diagnostics }; Atomic(EntryPath(content.Kind, content.Id), stream => { using var writer = new BinaryWriter(stream, Encoding.UTF8, true); WriteEntry(writer, entry); }); Written++; if (added > 0 && Interlocked.Read(ref _bytes) is >= 0 and var bytes && Interlocked.Add(ref _bytes, added) > Budget && bytes <= Budget) _ = Task.Run(() => Trim(Budget * 9 / 10)); } private static void WriteEntry(BinaryWriter writer, StoredEntry entry) { writer.Write(Magic); writer.Write(Format); writer.Write(entry.Kind.Name); writer.Write(entry.Id.ToString()); writer.Write(entry.Code); writer.Write(entry.Hash); writer.Write(entry.Length); writer.Write(entry.Converter); writer.Write(entry.ConverterVersion); writer.Write(entry.Bindings); writer.Write(entry.Inputs.Count); foreach (var input in entry.Inputs) { writer.Write(input.Path.Value); writer.Write(input.Layer is not null); if (input.Layer is not null) writer.Write(input.Layer); writer.Write(input.Length); writer.Write(input.Hash is not null); if (input.Hash is not null) writer.Write(input.Hash); } writer.Write(entry.Listings.Count); foreach (var listing in entry.Listings) { writer.Write(listing.Directory.Value); writer.Write(listing.Recursive); writer.Write(listing.Hash); } writer.Write(entry.References.Count); foreach (var reference in entry.References) { writer.Write(reference.Kind.Name); writer.Write(reference.Id.ToString()); } writer.Write(entry.Diagnostics.Count); foreach (var diagnostic in entry.Diagnostics) writer.Write(diagnostic); } private static StoredEntry? ReadEntry(BinaryReader reader) { if (!reader.ReadBytes(Magic.Length).AsSpan().SequenceEqual(Magic) || reader.ReadInt32() != Format) return null; var kind = new ContentKind(reader.ReadString()); var id = ContentId.Parse(reader.ReadString()); var code = reader.ReadString(); var hash = reader.ReadString(); var length = reader.ReadInt64(); var converter = reader.ReadString(); var version = reader.ReadInt32(); var bindings = reader.ReadString(); var inputs = new StoredInput[reader.ReadInt32()]; for (var i = 0; i < inputs.Length; i++) { var path = VirtualPath.Parse(reader.ReadString()); var layer = reader.ReadBoolean() ? reader.ReadString() : null; var size = reader.ReadInt64(); inputs[i] = new StoredInput(path, layer, size, reader.ReadBoolean() ? reader.ReadString() : null); } var listings = new ConversionListing[reader.ReadInt32()]; for (var i = 0; i < listings.Length; i++) listings[i] = new ConversionListing(VirtualPath.Parse(reader.ReadString()), reader.ReadBoolean(), reader.ReadString()); var references = new ContentReference[reader.ReadInt32()]; for (var i = 0; i < references.Length; i++) references[i] = new ContentReference(new ContentKind(reader.ReadString()), ContentId.Parse(reader.ReadString())); var diagnostics = new string[reader.ReadInt32()]; for (var i = 0; i < diagnostics.Length; i++) diagnostics[i] = reader.ReadString(); return new StoredEntry(kind, id, code, hash, length) { Converter = converter, ConverterVersion = version, Bindings = bindings, Inputs = inputs, Listings = listings, References = references, Diagnostics = diagnostics }; } private static string Closure(Type type) { var context = AssemblyLoadContext.GetLoadContext(type.Assembly) ?? AssemblyLoadContext.Default; var loaded = context.Assemblies.Concat(AssemblyLoadContext.Default.Assemblies) .GroupBy(assembly => assembly.GetName().Name ?? "", StringComparer.Ordinal) .ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal); var seen = new SortedDictionary(StringComparer.Ordinal); var pending = new Stack([type.Assembly]); while (pending.TryPop(out var assembly)) { var name = assembly.GetName().Name ?? ""; if (Framework(name) || !seen.TryAdd(name, assembly.ManifestModule.ModuleVersionId)) continue; foreach (var reference in assembly.GetReferencedAssemblies()) if (reference.Name is { } referenced && !Framework(referenced) && loaded.TryGetValue(referenced, out var next)) pending.Push(next); } var text = string.Join('\n', seen.Select(pair => $"{pair.Key} {pair.Value}")); return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16]; } private static bool Framework(string name) { return name is "mscorlib" or "netstandard" || name.StartsWith("System", StringComparison.Ordinal) || name.StartsWith("Microsoft.", StringComparison.Ordinal); } private string EntryPath(ContentKind kind, ContentId id) { var key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes($"{kind.Name}\n{id}"))); return Path.Combine(Root, "entries", key[..2], key); } private string ObjectPath(string hash) { return Path.Combine(Root, "objects", hash[..2], hash); } private IEnumerable Files(string folder) { var path = Path.Combine(Root, folder); if (!Directory.Exists(path)) yield break; foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) if (Path.GetExtension(file) != ".tmp") yield return file; else if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddHours(-1)) Delete(file); } private static void Atomic(string path, Action write) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); var temporary = $"{path}.{Guid.NewGuid():N}.tmp"; try { using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { write(stream); } File.Move(temporary, path, true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } private static void Delete(string path) { try { File.Delete(path); } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { } } }