|
| 1 | +using System; |
| 2 | +using System.Collections.Concurrent; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Globalization; |
| 5 | +using System.IO; |
| 6 | +using System.Text; |
| 7 | +using System.Threading; |
| 8 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 9 | + |
| 10 | +namespace Stunts |
| 11 | +{ |
| 12 | + /// <summary>What the generator needs from a stunt besides its text.</summary> |
| 13 | + [Flags] |
| 14 | + enum StuntCacheFlags |
| 15 | + { |
| 16 | + None = 0, |
| 17 | + /// <summary>The processors left the scaffold unchanged, so nothing is emitted.</summary> |
| 18 | + Unchanged = 1, |
| 19 | + /// <summary>The stunt has no instance constructor (ST006).</summary> |
| 20 | + NoConstructor = 2, |
| 21 | + GenericMethods = 4, |
| 22 | + AotQueryable = 8, |
| 23 | + AotRefStruct = 16, |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary>A cached generation result.</summary> |
| 27 | + sealed class StuntCacheEntry |
| 28 | + { |
| 29 | + public StuntCacheEntry(StuntCacheFlags flags, IReadOnlyList<string> defaults, string? code) |
| 30 | + => (Flags, Defaults, Code) = (flags, defaults, code); |
| 31 | + |
| 32 | + public StuntCacheFlags Flags { get; } |
| 33 | + |
| 34 | + /// <summary>Interfaces whose default implementation class the stunt calls, as <see cref="StuntFingerprint.Name"/>.</summary> |
| 35 | + public IReadOnlyList<string> Defaults { get; } |
| 36 | + |
| 37 | + /// <summary>The source added for the stunt, before registration nests forwarders in it.</summary> |
| 38 | + public string? Code { get; } |
| 39 | + |
| 40 | + internal string Write() |
| 41 | + { |
| 42 | + var builder = new StringBuilder() |
| 43 | + .Append(Header).Append('\n') |
| 44 | + .Append("flags ").Append(((int)Flags).ToString(CultureInfo.InvariantCulture)).Append('\n'); |
| 45 | + foreach (var name in Defaults) |
| 46 | + builder.Append("default ").Append(name).Append('\n'); |
| 47 | + |
| 48 | + var code = Code ?? ""; |
| 49 | + return builder.Append("code ").Append(code.Length.ToString(CultureInfo.InvariantCulture)).Append('\n') |
| 50 | + .Append(code).ToString(); |
| 51 | + } |
| 52 | + |
| 53 | + internal static StuntCacheEntry? Read(string text) |
| 54 | + { |
| 55 | + var position = 0; |
| 56 | + if (Line(text, ref position) != Header) |
| 57 | + return null; |
| 58 | + |
| 59 | + var flags = StuntCacheFlags.None; |
| 60 | + var defaults = new List<string>(); |
| 61 | + while (Line(text, ref position) is string line) |
| 62 | + { |
| 63 | + if (line.StartsWith("flags ", StringComparison.Ordinal) && |
| 64 | + int.TryParse(line.Substring(6), NumberStyles.None, CultureInfo.InvariantCulture, out var value)) |
| 65 | + flags = (StuntCacheFlags)value; |
| 66 | + else if (line.StartsWith("default ", StringComparison.Ordinal)) |
| 67 | + defaults.Add(line.Substring(8)); |
| 68 | + else if (line.StartsWith("code ", StringComparison.Ordinal) && |
| 69 | + int.TryParse(line.Substring(5), NumberStyles.None, CultureInfo.InvariantCulture, out var length)) |
| 70 | + // A length mismatch is a damaged or foreign file: regenerate. |
| 71 | + return text.Length - position == length |
| 72 | + ? new StuntCacheEntry(flags, defaults, (flags & (StuntCacheFlags.Unchanged | StuntCacheFlags.NoConstructor)) != 0 ? null : text.Substring(position)) |
| 73 | + : null; |
| 74 | + else |
| 75 | + return null; |
| 76 | + } |
| 77 | + |
| 78 | + return null; |
| 79 | + } |
| 80 | + |
| 81 | + const string Header = "stunts-cache 1"; |
| 82 | + |
| 83 | + static string? Line(string text, ref int position) |
| 84 | + { |
| 85 | + var end = text.IndexOf('\n', position); |
| 86 | + if (end < 0) |
| 87 | + return null; |
| 88 | + |
| 89 | + var line = text.Substring(position, end - position); |
| 90 | + position = end + 1; |
| 91 | + return line; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + /// <summary> |
| 96 | + /// Generation results shared by builds and projects, keyed by <see cref="StuntFingerprint"/>. |
| 97 | + /// Entries live in a folder per generator version under <c>StuntsCacheDir</c>, plus an |
| 98 | + /// in-memory copy for the lifetime of the compiler server process. |
| 99 | + /// </summary> |
| 100 | + sealed class StuntCache |
| 101 | + { |
| 102 | + const string Extension = ".stunt"; |
| 103 | + // Characters of cached code kept in memory before it is dropped. |
| 104 | + const long MemoryBudget = 32L * 1024 * 1024; |
| 105 | + static readonly TimeSpan PruneInterval = TimeSpan.FromDays(1); |
| 106 | + static readonly TimeSpan TouchAge = TimeSpan.FromDays(7); |
| 107 | + static readonly TimeSpan EntryAge = TimeSpan.FromDays(30); |
| 108 | + static readonly TimeSpan VersionAge = TimeSpan.FromDays(7); |
| 109 | + |
| 110 | + static readonly ConcurrentDictionary<string, StuntCacheEntry> memory = new(StringComparer.Ordinal); |
| 111 | + static long memorySize; |
| 112 | + |
| 113 | + readonly string root; |
| 114 | + readonly string directory; |
| 115 | + int hits; |
| 116 | + int misses; |
| 117 | + |
| 118 | + StuntCache(string root, string directory) => (this.root, this.directory) = (root, directory); |
| 119 | + |
| 120 | + /// <summary>Opens the cache under <c>StuntsCacheDir</c>, or returns null when it is not set.</summary> |
| 121 | + public static StuntCache? Create(AnalyzerConfigOptions options, string version) |
| 122 | + { |
| 123 | + if (BuildProperties.StuntsCacheDir(options) is not string root) |
| 124 | + return null; |
| 125 | + |
| 126 | + try |
| 127 | + { |
| 128 | + root = Path.GetFullPath(root); |
| 129 | + var directory = Path.Combine(root, version); |
| 130 | + Directory.CreateDirectory(directory); |
| 131 | + var cache = new StuntCache(root, directory); |
| 132 | + cache.Prune(); |
| 133 | + return cache; |
| 134 | + } |
| 135 | + catch (Exception ex) when (IsIOException(ex)) |
| 136 | + { |
| 137 | + return null; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + public int Hits => hits; |
| 142 | + |
| 143 | + public int Misses => misses; |
| 144 | + |
| 145 | + public StuntCacheEntry? Get(string key) |
| 146 | + { |
| 147 | + var path = Path.Combine(directory, key + Extension); |
| 148 | + // Keyed by path, so each cache folder keeps its own entries. |
| 149 | + if (memory.TryGetValue(path, out var entry)) |
| 150 | + { |
| 151 | + Interlocked.Increment(ref hits); |
| 152 | + return entry; |
| 153 | + } |
| 154 | + |
| 155 | + try |
| 156 | + { |
| 157 | + var info = new FileInfo(path); |
| 158 | + if (!info.Exists) |
| 159 | + { |
| 160 | + Interlocked.Increment(ref misses); |
| 161 | + return null; |
| 162 | + } |
| 163 | + |
| 164 | + entry = StuntCacheEntry.Read(File.ReadAllText(path, Encoding.UTF8)); |
| 165 | + if (entry == null) |
| 166 | + { |
| 167 | + Interlocked.Increment(ref misses); |
| 168 | + return null; |
| 169 | + } |
| 170 | + |
| 171 | + // Entries in use survive pruning. |
| 172 | + if (DateTime.UtcNow - info.LastWriteTimeUtc > TouchAge) |
| 173 | + File.SetLastWriteTimeUtc(path, DateTime.UtcNow); |
| 174 | + } |
| 175 | + catch (Exception ex) when (IsIOException(ex)) |
| 176 | + { |
| 177 | + Interlocked.Increment(ref misses); |
| 178 | + return null; |
| 179 | + } |
| 180 | + |
| 181 | + Remember(path, entry); |
| 182 | + Interlocked.Increment(ref hits); |
| 183 | + return entry; |
| 184 | + } |
| 185 | + |
| 186 | + public void Add(string key, StuntCacheEntry entry) |
| 187 | + { |
| 188 | + var path = Path.Combine(directory, key + Extension); |
| 189 | + Remember(path, entry); |
| 190 | + var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; |
| 191 | + try |
| 192 | + { |
| 193 | + if (File.Exists(path)) |
| 194 | + return; |
| 195 | + |
| 196 | + File.WriteAllText(temp, entry.Write(), new UTF8Encoding(false)); |
| 197 | + // Another build may have stored the same entry since. Its content is identical. |
| 198 | + try |
| 199 | + { |
| 200 | + File.Move(temp, path); |
| 201 | + } |
| 202 | + catch (IOException) |
| 203 | + { |
| 204 | + File.Delete(temp); |
| 205 | + } |
| 206 | + } |
| 207 | + catch (Exception ex) when (IsIOException(ex)) |
| 208 | + { |
| 209 | + try { File.Delete(temp); } catch (Exception e) when (IsIOException(e)) { } |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + /// <summary>Drops the in-memory entries, so the next reads come from disk.</summary> |
| 214 | + internal static void ClearMemory() |
| 215 | + { |
| 216 | + memory.Clear(); |
| 217 | + Interlocked.Exchange(ref memorySize, 0); |
| 218 | + } |
| 219 | + |
| 220 | + static void Remember(string path, StuntCacheEntry entry) |
| 221 | + { |
| 222 | + if (memory.TryAdd(path, entry) && |
| 223 | + Interlocked.Add(ref memorySize, entry.Code?.Length ?? 0) > MemoryBudget) |
| 224 | + ClearMemory(); |
| 225 | + } |
| 226 | + |
| 227 | + // At most once a day: entries not read for a month, temporary files, and the |
| 228 | + // folders of generator versions no build has written to for a week. |
| 229 | + void Prune() |
| 230 | + { |
| 231 | + var marker = Path.Combine(root, ".pruned"); |
| 232 | + var now = DateTime.UtcNow; |
| 233 | + if (File.Exists(marker) && now - File.GetLastWriteTimeUtc(marker) < PruneInterval) |
| 234 | + return; |
| 235 | + |
| 236 | + File.WriteAllText(marker, now.ToString("o", CultureInfo.InvariantCulture)); |
| 237 | + foreach (var version in Directory.EnumerateDirectories(root)) |
| 238 | + { |
| 239 | + try |
| 240 | + { |
| 241 | + if (!string.Equals(version, directory, StringComparison.OrdinalIgnoreCase) && |
| 242 | + now - Directory.GetLastWriteTimeUtc(version) > VersionAge) |
| 243 | + { |
| 244 | + Directory.Delete(version, true); |
| 245 | + continue; |
| 246 | + } |
| 247 | + |
| 248 | + foreach (var file in Directory.EnumerateFiles(version)) |
| 249 | + { |
| 250 | + var age = now - File.GetLastWriteTimeUtc(file); |
| 251 | + if (file.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) ? age > PruneInterval : age > EntryAge) |
| 252 | + File.Delete(file); |
| 253 | + } |
| 254 | + } |
| 255 | + catch (Exception ex) when (IsIOException(ex)) |
| 256 | + { |
| 257 | + } |
| 258 | + } |
| 259 | + } |
| 260 | + |
| 261 | + static bool IsIOException(Exception ex) |
| 262 | + => ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or NotSupportedException or ArgumentException; |
| 263 | + } |
| 264 | +} |
0 commit comments