Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

commit: 0c9688e9

Branches

main
ContentCache.cs 1.1 kB · 34 lines RawHistory
using Microsoft.Extensions.Caching.Memory;

namespace Forge.Features.Browse;

/// <summary>
/// Cache for things derived from git objects. Keys include the object's SHA, and content under
/// a SHA never changes, so entries never need invalidating; they only age out to bound memory.
/// It owns its <see cref="MemoryCache"/> so the size limit applies to these entries alone.
/// </summary>
public sealed class ContentCache : IDisposable
{
    private readonly MemoryCache _cache = new(new MemoryCacheOptions { SizeLimit = 64 * 1024 * 1024 });

    public IMemoryCache Cache => _cache;

    public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> create, Func<T, long> sizeOf)
        where T : notnull
    {
        if (_cache.TryGetValue(key, out T? cached) && cached is not null)
        {
            return cached;
        }

        var value = await create();
        _cache.Set(key, value, new MemoryCacheEntryOptions
        {
            Size = Math.Max(1, sizeOf(value)),
            SlidingExpiration = TimeSpan.FromHours(6),
        });
        return value;
    }

    public void Dispose() => _cache.Dispose();
}

Keyboard shortcuts

/
Search repositories
s
Search file names and code
y
Open the permalink of the file being viewed
?
Show this help