Skip to content
0.2.0-dev Download ZIP
414 lines ·14.5 KB Raw
1using System.Collections.Concurrent;
2using System.Diagnostics;
3using System.Reflection;
4using System.Runtime.Loader;
5using System.Security.Cryptography;
6using System.Text;
7using System.Threading.Channels;
8using EvilEngine.Formats;
9using EvilEngine.Mounts;
10
11namespace EvilEngine.Conversion;
12
13public sealed record StoredInput(VirtualPath Path, string? Layer, long Length, string? Hash);
14
15public sealed record StoredEntry(ContentKind Kind, ContentId Id, string Code, string Hash, long Length)
16{
17 public required string Converter { get; init; }
18
19 public required int ConverterVersion { get; init; }
20
21 public required string Bindings { get; init; }
22
23 public IReadOnlyList<StoredInput> Inputs { get; init; } = [];
24
25 public IReadOnlyList<ConversionListing> Listings { get; init; } = [];
26
27 public IReadOnlyList<ContentReference> References { get; init; } = [];
28
29 public IReadOnlyList<string> Diagnostics { get; init; } = [];
30}
31
32public sealed class DiskConversionCache : IDisposable
33{
34 private const int Format = 1;
35 private static readonly byte[] Magic = "EVCE"u8.ToArray();
36 private static readonly ConcurrentDictionary<Type, string> Codes = new();
37 private readonly Lock _trimming = new();
38
39 private readonly Func<TimeSpan, TimeSpan, bool> _worth;
40 private readonly Task _writer;
41
42 private readonly Channel<(ConvertedContent Content, string Code, TimeSpan Took)> _writes =
43 Channel.CreateBounded<(ConvertedContent, string, TimeSpan)>(new BoundedChannelOptions(256)
44 { FullMode = BoundedChannelFullMode.Wait, SingleReader = true });
45
46 private long _bytes = -1;
47 private int _pending;
48
49 public DiskConversionCache(string root, long budget, Func<TimeSpan, TimeSpan, bool>? worth = null)
50 {
51 Root = root;
52 Budget = budget;
53 _worth = worth ?? ((took, check) => took > check);
54 _writer = Task.Run(Write);
55 }
56
57 public string Root { get; }
58
59 public long Budget { get; }
60
61 public int Written { get; private set; }
62
63 public int Skipped { get; private set; }
64
65 public void Dispose()
66 {
67 _writes.Writer.TryComplete();
68 _writer.Wait();
69 }
70
71 public static string Code(IEnumerable<IConverter> converters)
72 {
73 return string.Join(';', converters.Select(converter => Codes.GetOrAdd(converter.GetType(), Closure)));
74 }
75
76 public StoredEntry? Find(ContentKind kind, ContentId id)
77 {
78 var path = EntryPath(kind, id);
79 try
80 {
81 if (!File.Exists(path))
82 return null;
83 using var reader = new BinaryReader(File.OpenRead(path), Encoding.UTF8);
84 var entry = ReadEntry(reader);
85 if (entry is null || entry.Kind != kind || entry.Id != id)
86 return null;
87 File.SetLastWriteTimeUtc(path, DateTime.UtcNow);
88 return entry;
89 }
90 catch (Exception error) when (error is IOException or UnauthorizedAccessException or EndOfStreamException
91 or FormatException or ArgumentException)
92 {
93 return null;
94 }
95 }
96
97 public byte[]? Read(StoredEntry entry)
98 {
99 try
100 {
101 var bytes = File.ReadAllBytes(ObjectPath(entry.Hash));
102 return bytes.Length == entry.Length ? bytes : null;
103 }
104 catch (Exception error) when (error is IOException or UnauthorizedAccessException)
105 {
106 return null;
107 }
108 }
109
110 public void Store(ConvertedContent content, string code, TimeSpan took)
111 {
112 Interlocked.Increment(ref _pending);
113 if (!_writes.Writer.TryWrite((content, code, took)))
114 Interlocked.Decrement(ref _pending);
115 }
116
117 public void Flush()
118 {
119 SpinWait.SpinUntil(() => Volatile.Read(ref _pending) == 0);
120 }
121
122 public long Trim(long keep)
123 {
124 return Sweep(keep, keep);
125 }
126
127 public void Measure()
128 {
129 Sweep(Budget, Budget * 9 / 10);
130 }
131
132 private long Sweep(long limit, long keep)
133 {
134 lock (_trimming)
135 {
136 var entries = new List<(string Path, DateTime Used, string Hash)>();
137 foreach (var path in Files("entries"))
138 try
139 {
140 using var reader = new BinaryReader(File.OpenRead(path), Encoding.UTF8);
141 if (ReadEntry(reader) is { } entry)
142 entries.Add((path, File.GetLastWriteTimeUtc(path), entry.Hash));
143 else
144 Delete(path);
145 }
146 catch (Exception error) when (error is IOException or UnauthorizedAccessException
147 or EndOfStreamException or FormatException or ArgumentException)
148 {
149 Delete(path);
150 }
151
152 var sizes = new Dictionary<string, long>(StringComparer.Ordinal);
153 foreach (var path in Files("objects"))
154 sizes[Path.GetFileName(path)] = new FileInfo(path).Length;
155
156 var users = entries.GroupBy(entry => entry.Hash).ToDictionary(group => group.Key, group => group.Count());
157 var released = 0L;
158 foreach (var (hash, size) in sizes)
159 if (!users.ContainsKey(hash))
160 {
161 Delete(ObjectPath(hash));
162 released += size;
163 }
164
165 var total = users.Keys.Sum(hash => sizes.GetValueOrDefault(hash));
166 var target = total > limit ? keep : long.MaxValue;
167 foreach (var entry in entries.OrderBy(entry => entry.Used))
168 {
169 if (total <= target)
170 break;
171 Delete(entry.Path);
172 if (--users[entry.Hash] > 0 || !sizes.TryGetValue(entry.Hash, out var size))
173 continue;
174 Delete(ObjectPath(entry.Hash));
175 total -= size;
176 released += size;
177 }
178
179 Interlocked.Exchange(ref _bytes, total);
180 return released;
181 }
182 }
183
184 private async Task Write()
185 {
186 await foreach (var (content, code, took) in _writes.Reader.ReadAllAsync())
187 try
188 {
189 Persist(content, code, took);
190 }
191 catch (Exception error) when (error is IOException or UnauthorizedAccessException
192 or InvalidOperationException or FileNotFoundException)
193 {
194 Skipped++;
195 }
196 finally
197 {
198 Interlocked.Decrement(ref _pending);
199 }
200 }
201
202 private void Persist(ConvertedContent content, string code, TimeSpan took)
203 {
204 var clock = Stopwatch.StartNew();
205 var inputs = content.Inputs
206 .Select(input => new StoredInput(input.Path, input.Layer, input.Stamp?.Length ?? 0, input.Stamp?.Hash))
207 .ToArray();
208 if (!_worth(took, clock.Elapsed))
209 {
210 Skipped++;
211 return;
212 }
213
214 var objectPath = ObjectPath(content.Hash);
215 var added = 0L;
216 if (!File.Exists(objectPath) || new FileInfo(objectPath).Length != content.Data.Length)
217 {
218 Atomic(objectPath, stream => stream.Write(content.Data.Span));
219 added += content.Data.Length;
220 }
221
222 var entry = new StoredEntry(content.Kind, content.Id, code, content.Hash, content.Data.Length)
223 {
224 Converter = content.Converter,
225 ConverterVersion = content.ConverterVersion,
226 Bindings = content.Bindings,
227 Inputs = inputs,
228 Listings = content.Listings,
229 References = content.References,
230 Diagnostics = content.Diagnostics
231 };
232 Atomic(EntryPath(content.Kind, content.Id), stream =>
233 {
234 using var writer = new BinaryWriter(stream, Encoding.UTF8, true);
235 WriteEntry(writer, entry);
236 });
237 Written++;
238 if (added > 0 && Interlocked.Read(ref _bytes) is >= 0 and var bytes &&
239 Interlocked.Add(ref _bytes, added) > Budget && bytes <= Budget)
240 _ = Task.Run(() => Trim(Budget * 9 / 10));
241 }
242
243 private static void WriteEntry(BinaryWriter writer, StoredEntry entry)
244 {
245 writer.Write(Magic);
246 writer.Write(Format);
247 writer.Write(entry.Kind.Name);
248 writer.Write(entry.Id.ToString());
249 writer.Write(entry.Code);
250 writer.Write(entry.Hash);
251 writer.Write(entry.Length);
252 writer.Write(entry.Converter);
253 writer.Write(entry.ConverterVersion);
254 writer.Write(entry.Bindings);
255 writer.Write(entry.Inputs.Count);
256 foreach (var input in entry.Inputs)
257 {
258 writer.Write(input.Path.Value);
259 writer.Write(input.Layer is not null);
260 if (input.Layer is not null)
261 writer.Write(input.Layer);
262 writer.Write(input.Length);
263 writer.Write(input.Hash is not null);
264 if (input.Hash is not null)
265 writer.Write(input.Hash);
266 }
267
268 writer.Write(entry.Listings.Count);
269 foreach (var listing in entry.Listings)
270 {
271 writer.Write(listing.Directory.Value);
272 writer.Write(listing.Recursive);
273 writer.Write(listing.Hash);
274 }
275
276 writer.Write(entry.References.Count);
277 foreach (var reference in entry.References)
278 {
279 writer.Write(reference.Kind.Name);
280 writer.Write(reference.Id.ToString());
281 }
282
283 writer.Write(entry.Diagnostics.Count);
284 foreach (var diagnostic in entry.Diagnostics)
285 writer.Write(diagnostic);
286 }
287
288 private static StoredEntry? ReadEntry(BinaryReader reader)
289 {
290 if (!reader.ReadBytes(Magic.Length).AsSpan().SequenceEqual(Magic) || reader.ReadInt32() != Format)
291 return null;
292 var kind = new ContentKind(reader.ReadString());
293 var id = ContentId.Parse(reader.ReadString());
294 var code = reader.ReadString();
295 var hash = reader.ReadString();
296 var length = reader.ReadInt64();
297 var converter = reader.ReadString();
298 var version = reader.ReadInt32();
299 var bindings = reader.ReadString();
300 var inputs = new StoredInput[reader.ReadInt32()];
301 for (var i = 0; i < inputs.Length; i++)
302 {
303 var path = VirtualPath.Parse(reader.ReadString());
304 var layer = reader.ReadBoolean() ? reader.ReadString() : null;
305 var size = reader.ReadInt64();
306 inputs[i] = new StoredInput(path, layer, size, reader.ReadBoolean() ? reader.ReadString() : null);
307 }
308
309 var listings = new ConversionListing[reader.ReadInt32()];
310 for (var i = 0; i < listings.Length; i++)
311 listings[i] = new ConversionListing(VirtualPath.Parse(reader.ReadString()), reader.ReadBoolean(),
312 reader.ReadString());
313 var references = new ContentReference[reader.ReadInt32()];
314 for (var i = 0; i < references.Length; i++)
315 references[i] =
316 new ContentReference(new ContentKind(reader.ReadString()), ContentId.Parse(reader.ReadString()));
317 var diagnostics = new string[reader.ReadInt32()];
318 for (var i = 0; i < diagnostics.Length; i++)
319 diagnostics[i] = reader.ReadString();
320 return new StoredEntry(kind, id, code, hash, length)
321 {
322 Converter = converter,
323 ConverterVersion = version,
324 Bindings = bindings,
325 Inputs = inputs,
326 Listings = listings,
327 References = references,
328 Diagnostics = diagnostics
329 };
330 }
331
332 private static string Closure(Type type)
333 {
334 var context = AssemblyLoadContext.GetLoadContext(type.Assembly) ?? AssemblyLoadContext.Default;
335 var loaded = context.Assemblies.Concat(AssemblyLoadContext.Default.Assemblies)
336 .GroupBy(assembly => assembly.GetName().Name ?? "", StringComparer.Ordinal)
337 .ToDictionary(group => group.Key, group => group.First(), StringComparer.Ordinal);
338 var seen = new SortedDictionary<string, Guid>(StringComparer.Ordinal);
339 var pending = new Stack<Assembly>([type.Assembly]);
340 while (pending.TryPop(out var assembly))
341 {
342 var name = assembly.GetName().Name ?? "";
343 if (Framework(name) || !seen.TryAdd(name, assembly.ManifestModule.ModuleVersionId))
344 continue;
345 foreach (var reference in assembly.GetReferencedAssemblies())
346 if (reference.Name is { } referenced && !Framework(referenced) &&
347 loaded.TryGetValue(referenced, out var next))
348 pending.Push(next);
349 }
350
351 var text = string.Join('\n', seen.Select(pair => $"{pair.Key} {pair.Value}"));
352 return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16];
353 }
354
355 private static bool Framework(string name)
356 {
357 return name is "mscorlib" or "netstandard" || name.StartsWith("System", StringComparison.Ordinal) ||
358 name.StartsWith("Microsoft.", StringComparison.Ordinal);
359 }
360
361 private string EntryPath(ContentKind kind, ContentId id)
362 {
363 var key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes($"{kind.Name}\n{id}")));
364 return Path.Combine(Root, "entries", key[..2], key);
365 }
366
367 private string ObjectPath(string hash)
368 {
369 return Path.Combine(Root, "objects", hash[..2], hash);
370 }
371
372 private IEnumerable<string> Files(string folder)
373 {
374 var path = Path.Combine(Root, folder);
375 if (!Directory.Exists(path))
376 yield break;
377 foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
378 if (Path.GetExtension(file) != ".tmp")
379 yield return file;
380 else if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddHours(-1))
381 Delete(file);
382 }
383
384 private static void Atomic(string path, Action<Stream> write)
385 {
386 Directory.CreateDirectory(Path.GetDirectoryName(path)!);
387 var temporary = $"{path}.{Guid.NewGuid():N}.tmp";
388 try
389 {
390 using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
391 {
392 write(stream);
393 }
394
395 File.Move(temporary, path, true);
396 }
397 finally
398 {
399 if (File.Exists(temporary))
400 File.Delete(temporary);
401 }
402 }
403
404 private static void Delete(string path)
405 {
406 try
407 {
408 File.Delete(path);
409 }
410 catch (Exception error) when (error is IOException or UnauthorizedAccessException)
411 {
412 }
413 }
414}