using System.Diagnostics; using System.Globalization; namespace EvilEngine.Host; public sealed record MemoryBudget(long Soft, long Hard) { public const string SoftVariable = "EVIL_MEMORY_SOFT_GB"; public const string HardVariable = "EVIL_MEMORY_HARD_GB"; public static readonly MemoryBudget Default = new(Gigabytes(6), Gigabytes(8)); public static MemoryBudget Read(Func variable) { var soft = Parse(variable(SoftVariable)) ?? Default.Soft; var hard = Parse(variable(HardVariable)) ?? Math.Max(Default.Hard, soft); return new MemoryBudget(Math.Min(soft, hard), hard); } private static long? Parse(string? text) { return double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var gigabytes) && gigabytes > 0 ? (long)(gigabytes * Gigabytes(1)) : null; } private static long Gigabytes(long count) { return count * 1024 * 1024 * 1024; } } public sealed class MemoryGuard( MemoryBudget budget, Func resident, Action line, Action fail) : IDisposable { private readonly List<(string Name, Func Bytes)> _holders = []; private readonly Lock _lock = new(); private readonly List> _trimmers = []; private bool _failed; private Timer? _timer; private bool _warned; public MemoryBudget Budget { get; } = budget; public void Dispose() { _timer?.Dispose(); } public void Hold(string name, Func bytes) { lock (_lock) { _holders.Add((name, bytes)); } } public void Trim(Func release) { lock (_lock) { _trimmers.Add(release); } } public void Start(TimeSpan every) { _timer ??= new Timer(_ => Check(), null, every, every); } public void Check() { if (!_lock.TryEnter()) return; try { if (_failed) return; var now = resident(); if (now >= Budget.Hard) { _failed = true; fail( $"Memory reached {Size(now)}, over the {Size(Budget.Hard)} hard budget, so the engine quit rather than take the desktop down with it.{Holders(now)}"); return; } if (now < Budget.Soft) { if (now < Budget.Soft * 9 / 10) _warned = false; return; } var released = _trimmers.Sum(trim => trim()); if (released > 0) GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); if (_warned) return; _warned = true; line(TranscriptTag.Warn, $"Memory reached {Size(now)}, over the {Size(Budget.Soft)} soft budget; released {Size(released)} of cached content.{Holders(now)}"); } finally { _lock.Exit(); } } public static long Resident() { try { var fields = File.ReadAllText("/proc/self/statm").Split(' '); return long.Parse(fields[1], CultureInfo.InvariantCulture) * Environment.SystemPageSize; } catch (Exception error) when (error is IOException or UnauthorizedAccessException or FormatException or IndexOutOfRangeException) { using var process = Process.GetCurrentProcess(); return process.WorkingSet64; } } public static string Size(long bytes) { return bytes >= 1L << 30 ? $"{(bytes / (double)(1L << 30)).ToString("0.0", CultureInfo.InvariantCulture)} GB" : $"{(bytes / (double)(1L << 20)).ToString("0", CultureInfo.InvariantCulture)} MB"; } private string Holders(long resident) { if (_holders.Count == 0) return ""; var held = _holders.Select(holder => (holder.Name, Bytes: holder.Bytes())).ToList(); held.Add(("everything else", Math.Max(0, resident - held.Sum(holder => holder.Bytes)))); var named = held.OrderByDescending(holder => holder.Bytes) .Select(holder => $"{holder.Name} {Size(holder.Bytes)}"); return $" Largest holders: {string.Join(", ", named)}."; } }