aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/Runs/Scripts/CheckpointCache.cs
blob: 1e1dd3ae8c61058ff56f5f8a709f26b629c3fde0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Provenance: own design — shared run scripts (spec §5.4)
using System.Buffers.Binary;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Godosa.Core.Runs.Scripts;

public sealed record LabelState(string Name, long Start, string File, int Line);

public sealed record RunnerState(long Frame, ulong Digest, List<ScopeState> Scopes, List<LabelState> Labels);

public sealed record CachedCheckpoint(RunnerState State, byte[] Game);

public static class CheckpointKeys
{
    public const string RunnerVersion = "run-scripts 1";

    public static IReadOnlyDictionary<int, string> Compute(ScriptProgram p, string contentVersion, ulong seed)
    {
        var d = new StateDigest();
        d.Add(RunnerVersion);
        d.Add(contentVersion);
        d.Add(seed);
        d.Add((int)p.Mode);
        foreach (var (k, v) in p.Vars.OrderBy(kv => kv.Key, StringComparer.Ordinal))
            d.Add($"{k}={v}");
        var keys = new Dictionary<int, string>();
        for (var i = 0; i < p.Code.Count; i++)
        {
            var instr = p.Code[i];
            d.Add((int)instr.Op);
            d.Add(instr.Format);
            d.Add(instr.At.File);
            d.Add(instr.Text);
            if (instr.Op == Op.Checkpoint)
                keys[i] = d.Hex;
        }
        return keys;
    }
}

public sealed class CheckpointCache(string dir, long capBytes)
{
    private static readonly byte[] Magic = "GRS1"u8.ToArray();
    private static readonly JsonSerializerOptions Json = new() { Converters = { new JsonStringEnumConverter() } };

    public CachedCheckpoint? Load(string key)
    {
        var path = Path.Combine(dir, key + ".snap");
        if (!File.Exists(path))
            return null;
        byte[] bytes;
        try
        {
            bytes = File.ReadAllBytes(path);
        }
        catch (Exception e) when (e is IOException or UnauthorizedAccessException)
        {
            return null;
        }
        if (bytes.Length < 8 || !bytes.AsSpan(0, 4).SequenceEqual(Magic))
            return null;
        var length = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4));
        if (length < 0 || 8 + length > bytes.Length)
            return null;
        RunnerState? state;
        try
        {
            state = JsonSerializer.Deserialize<RunnerState>(Encoding.UTF8.GetString(bytes, 8, length), Json);
        }
        catch (JsonException)
        {
            return null; // a corrupt entry is a miss
        }
        return state == null ? null : new CachedCheckpoint(state, bytes[(8 + length)..]);
    }

    public void Save(string key, CachedCheckpoint cp)
    {
        Directory.CreateDirectory(dir);
        var json = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(cp.State, Json));
        var path = Path.Combine(dir, key + ".snap");
        var tmp = path + ".tmp";
        using (var f = File.Create(tmp))
        {
            f.Write(Magic);
            Span<byte> len = stackalloc byte[4];
            BinaryPrimitives.WriteInt32LittleEndian(len, json.Length);
            f.Write(len);
            f.Write(json);
            f.Write(cp.Game);
        }
        File.Move(tmp, path, overwrite: true);
        Evict(path);
    }

    private void Evict(string keep)
    {
        var files = new DirectoryInfo(dir).GetFiles("*.snap").OrderBy(f => f.LastWriteTimeUtc).ToList();
        var total = files.Sum(f => f.Length);
        foreach (var f in files)
        {
            if (total <= capBytes)
                break;
            if (f.FullName == Path.GetFullPath(keep))
                continue;
            total -= f.Length;
            f.Delete();
        }
    }
}