Path: redb/redb.Core/Caching/GlobalListCache.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Caching/GlobalListCache.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
namespace redb.Core.Caching
{
///
/// Cache entry with TTL.
///
internal class ListCacheEntry
{
public T Value { get; set; } = default!;
public DateTime ExpiresAt { get; set; }
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
}
///
/// Domain-isolated cache data for lists.
///
internal class ListCacheDomain
{
public bool Enabled = true;
public TimeSpan Ttl = TimeSpan.FromMinutes(5);
// Lists cache
public readonly ConcurrentDictionary> ListsById = new();
public readonly ConcurrentDictionary> ListsByName = new();
// Items cache
public readonly ConcurrentDictionary>> ItemsByListId = new();
public readonly ConcurrentDictionary> ItemsById = new();
public void Clear()
{
ListsById.Clear();
ListsByName.Clear();
ItemsByListId.Clear();
ItemsById.Clear();
}
}
///
/// Domain-isolated cache for lists and their items.
/// Hybrid model: TTL for eventual consistency + local invalidation on changes.
/// Instance is bound to specific domain, static data is shared.
///
public sealed class GlobalListCache
{
private static readonly ConcurrentDictionary _domains = new();
private readonly string _domain;
///
/// Domain identifier for this cache instance.
///
public string Domain => _domain;
///
/// Create cache instance for specific domain.
///
public GlobalListCache(string? domain = null, bool? enabled = null)
{
CollectibleContextCleanup.EnsureWatching();
_domain = domain ?? "default";
var cache = GetCache();
if (enabled.HasValue)
cache.Enabled = enabled.Value;
}
private ListCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new ListCacheDomain());
///
/// Drops, in every domain, the cached items whose loaded object is of a type
/// answers true for, and the item lists that hold one: the types of a collectible AssemblyLoadContext that
/// unloads (). Such an item comes back from the database on next read.
///
internal static void RemoveObjectsOfTypes(Func unloading)
{
bool Holds(RedbListItem item) => item.LoadedObject is { } loaded && unloading(loaded.GetType());
foreach (var domain in _domains.Values)
{
foreach (var entry in domain.ItemsById)
if (Holds(entry.Value.Value))
domain.ItemsById.TryRemove(entry);
foreach (var entry in domain.ItemsByListId)
if (entry.Value.Value.Any(Holds))
domain.ItemsByListId.TryRemove(entry);
}
}
///
/// Enable or disable cache for this domain.
///
public void SetEnabled(bool enabled)
{
var cache = GetCache();
cache.Enabled = enabled;
if (!enabled)
cache.Clear();
}
///
/// Check if cache is enabled.
///
public bool IsEnabled => GetCache().Enabled;
///
/// Set TTL for the cache.
///
public void SetTtl(TimeSpan ttl)
{
if (ttl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than 0");
GetCache().Ttl = ttl;
}
// ===== LISTS =====
///
/// Get list by ID.
///
public RedbList? GetList(long id)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ListsById.TryGetValue(id, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ListsById.TryRemove(id, out _);
}
return null;
}
///
/// Get list by name.
///
public RedbList? GetListByName(string name)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ListsByName.TryGetValue(name, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ListsByName.TryRemove(name, out _);
}
return null;
}
///
/// Cache list.
///
public void CacheList(RedbList list)
{
var cache = GetCache();
if (!cache.Enabled) return;
var entry = new ListCacheEntry
{
Value = list,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ListsById[list.Id] = entry;
cache.ListsByName[list.Name] = entry;
}
// ===== ITEMS =====
///
/// Get list items by list ID.
///
public List? GetListItems(long listId)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ItemsByListId.TryGetValue(listId, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ItemsByListId.TryRemove(listId, out _);
}
return null;
}
///
/// Get list item by ID.
///
public RedbListItem? GetListItem(long itemId)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ItemsById.TryGetValue(itemId, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ItemsById.TryRemove(itemId, out _);
}
return null;
}
///
/// Cache list items.
///
public void CacheListItems(long listId, List items)
{
var cache = GetCache();
if (!cache.Enabled) return;
var itemsEntry = new ListCacheEntry>
{
Value = items,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ItemsByListId[listId] = itemsEntry;
foreach (var item in items)
{
// Shared by every scope from now on, with the object it may already carry: Object loads on the reader's
// scope and, inside the reader's transaction, keeps nothing (owner decision 2026-09-15).
Utils.LazyReferenceInstaller.MarkShared(item);
item._cacheDomain ??= _domain;
var itemEntry = new ListCacheEntry
{
Value = item,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ItemsById[item.Id] = itemEntry;
}
}
// ===== INVALIDATION =====
///
/// Invalidate list and its items.
///
public void InvalidateList(long listId)
{
var cache = GetCache();
if (cache.ListsById.TryRemove(listId, out var listEntry))
{
cache.ListsByName.TryRemove(listEntry.Value.Name, out _);
}
InvalidateListItems(listId);
}
///
/// Invalidate list items.
///
public void InvalidateListItems(long listId)
{
var cache = GetCache();
if (cache.ItemsByListId.TryRemove(listId, out var itemsEntry))
{
foreach (var item in itemsEntry.Value)
{
cache.ItemsById.TryRemove(item.Id, out _);
}
}
}
///
/// Invalidate single list item.
///
public void InvalidateListItem(long itemId)
{
GetCache().ItemsById.TryRemove(itemId, out _);
}
///
/// Clear cache for this domain.
///
public void Clear()
{
GetCache().Clear();
}
///
/// Get cache size statistics.
///
public (int Lists, int Items) GetCacheSize()
{
var cache = GetCache();
return (cache.ListsById.Count, cache.ItemsById.Count);
}
}
}