CultLib/src/GameCult.Caching.MessagePack/CultCacheMessagePack.cs

75 lines
2.3 KiB
C#
Raw Normal View History

2026-05-09 13:32:30 +01:00
using System;
2026-05-31 17:32:42 +01:00
using System.IO;
2026-05-09 13:32:30 +01:00
using System.Threading.Tasks;
namespace GameCult.Caching.MessagePack
{
public sealed class CultCacheOpenOptions
{
public CultDocumentRegistry? Registry { get; set; }
public bool PullOnOpen { get; set; } = true;
public bool FlushOnDispose { get; set; }
public bool StoreFlushOnDispose { get; set; }
2026-05-31 17:32:42 +01:00
public bool UseDirectoryStore { get; set; }
2026-05-09 13:32:30 +01:00
}
public static class CultCacheMessagePack
{
public static CultCache Create(string filePath, CultCacheOpenOptions? options = null)
{
options ??= new CultCacheOpenOptions();
return CreateCore(filePath, options, initializeGlobals: true);
}
public static async Task<CultCache> OpenAsync(string filePath, CultCacheOpenOptions? options = null)
{
options ??= new CultCacheOpenOptions();
var cache = CreateCore(filePath, options, initializeGlobals: false);
if (options.PullOnOpen)
{
await cache.PullAllBackingStoresAsync().ConfigureAwait(false);
}
cache.MaterializeMissingGlobals();
return cache;
}
private static CultCache CreateCore(
string filePath,
CultCacheOpenOptions options,
bool initializeGlobals)
2026-05-09 13:32:30 +01:00
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("File path must be non-empty.", nameof(filePath));
}
var cache = new CultCache(options.Registry, initializeGlobals)
2026-05-09 13:32:30 +01:00
{
FlushAttachedStoresOnDispose = options.FlushOnDispose
};
if (options.UseDirectoryStore || Directory.Exists(DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(filePath)))
2026-05-09 13:32:30 +01:00
{
cache.AddBackingStore(new DirectoryMessagePackBackingStore(filePath)
2026-05-31 17:32:42 +01:00
{
FlushOnDispose = options.StoreFlushOnDispose
});
2026-05-31 17:32:42 +01:00
}
else
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(filePath)
2026-05-31 17:32:42 +01:00
{
FlushOnDispose = options.StoreFlushOnDispose
});
2026-05-31 17:32:42 +01:00
}
2026-05-09 13:32:30 +01:00
return cache;
}
}
}