Server-side key/value storage exposed to Lua gamemodes as the `storage` library (Get, Set, Delete, Exists, Flush) plus a `log.Audit` binding. Each key becomes one validated JSON file under `roleplay/storage/<gamemode>/`, cached in memory and flushed on an interval, on explicit flush, or at gamemode change, with corrupt files copied aside and read as nil.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Lua;
namespace RoleplayFramework.Scripting;
/// <summary>
/// Server-side persistent storage for gamemodes: <c>storage.Get(key)</c>, <c>storage.Set(key, value)</c>,
/// <c>storage.Delete(key)</c>, <c>storage.Exists(key)</c>, <c>storage.Flush()</c>.
///
/// Values are any serializable Lua value (see <see cref="LuaSerializer.Storage"/> limits). Each key is one JSON file in
/// data/roleplay/storage/<gamemode>/<key>.json. Writes are cached and flushed every few seconds, on
/// <c>storage.Flush()</c> and at shutdown, through the crash-tolerant <see cref="SafeDataFile"/>. Corrupt files are
/// kept aside and read as nil. Gamemodes cannot read each other's storage or anything outside their folder.
/// </summary>
public static class LuaStorage
{
public const double FlushIntervalSeconds = 3;
static readonly Regex KeyPattern = new( @"^[a-z0-9_\-]+(/[a-z0-9_\-]+)*$" );
static readonly Dictionary<string, string> _cache = new(); // key -> serialized (null = deleted)
static readonly HashSet<string> _dirty = new();
static string _gamemode;
static double _lastFlush;
public static string CheckKey( string key )
{
if ( string.IsNullOrEmpty( key ) || key.Length > 96 ) return "keys are 1-96 characters";
if ( !KeyPattern.IsMatch( key ) ) return "keys use a-z, 0-9, _ and -, with '/' between parts";
return null;
}
static string PathFor( string key ) => $"roleplay/storage/{_gamemode}/{key}.json";
public static void Begin( string gamemode )
{
Flush();
_cache.Clear();
_dirty.Clear();
_gamemode = gamemode;
}
public static void Register( LuaRealm realm )
{
if ( realm.Kind != LuaRealmKind.Server ) return;
var t = realm.State.GetOrCreateLibrary( "storage" );
LuaState.Register( t, "Get", ( L, a ) =>
{
var key = Key( a, "storage.Get" );
var text = Read( key );
if ( text is null ) return new[] { LuaValue.Nil };
try { return new[] { LuaSerializer.Deserialize( text, LuaSerializer.Storage ) }; }
catch ( FormatException e )
{
RpLog.Error( "storage", $"Stored value '{key}' is unreadable ({e.Message}); returning nil" );
return new[] { LuaValue.Nil };
}
} );
LuaState.Register( t, "Set", ( L, a ) =>
{
var key = Key( a, "storage.Set" );
var v = LuaState.Arg( a, 1 );
if ( v.IsNil ) { Write( key, null ); return null; }
Write( key, LuaSerializer.Serialize( v, LuaSerializer.Storage ) );
return null;
} );
LuaState.Register( t, "Delete", ( L, a ) => { Write( Key( a, "storage.Delete" ), null ); return null; } );
LuaState.Register( t, "Exists", ( L, a ) => new LuaValue[] { Read( Key( a, "storage.Exists" ) ) is not null } );
LuaState.Register( t, "Flush", ( L, a ) => { Flush(); return null; } );
}
static string Key( LuaValue[] a, string fname )
{
if ( _gamemode is null ) throw new LuaRuntimeException( "storage is not available yet" );
var key = LuaState.CheckString( a, 0, fname );
var err = CheckKey( key );
if ( err is not null ) throw LuaState.ArgError( 0, fname, err );
return key;
}
static string Read( string key )
{
if ( _cache.TryGetValue( key, out var cached ) ) return cached;
var path = PathFor( key );
string text = null;
if ( SafeDataFile.Exists( path ) )
{
text = SafeDataFile.Read( path, t => { try { LuaSerializer.Deserialize( t, LuaSerializer.Storage ); return true; } catch ( FormatException ) { return false; } }, out bool recovered );
if ( text is null )
{
var fs = FileSystem.Data;
if ( fs.FileExists( path ) ) fs.WriteAllText( $"{path}.corrupt-{DateTime.UtcNow:yyyyMMdd-HHmmss}", fs.ReadAllText( path ) );
RpLog.Error( "storage", $"data/{path} was corrupt; kept a copy and treating it as empty" );
}
else if ( recovered ) RpLog.Warn( "storage", $"Recovered data/{path} from an interrupted write" );
}
_cache[key] = text;
return text;
}
static void Write( string key, string serialized )
{
_cache[key] = serialized;
_dirty.Add( key );
}
public static void Tick()
{
if ( _dirty.Count > 0 && RealTime.NowDouble - _lastFlush >= FlushIntervalSeconds ) Flush();
}
public static void Flush()
{
_lastFlush = RealTime.NowDouble;
if ( _gamemode is null || _dirty.Count == 0 ) return;
var fs = FileSystem.Data;
foreach ( var key in _dirty.ToList() )
{
try
{
var path = PathFor( key );
var value = _cache[key];
if ( value is null )
{
if ( fs.FileExists( path ) ) fs.DeleteFile( path );
}
else SafeDataFile.Write( path, value );
_dirty.Remove( key );
}
catch ( Exception e )
{
RpLog.Error( "storage", $"Failed to save '{key}': {e.Message}" );
}
}
}
}
/// <summary>Server-side logging helpers for Lua: <c>log.Audit(category, message)</c>.</summary>
public static class LuaLog
{
public static void Register( LuaRealm realm )
{
if ( realm.Kind != LuaRealmKind.Server ) return;
var t = realm.State.GetOrCreateLibrary( "log" );
LuaState.Register( t, "Audit", ( L, a ) =>
{
var category = Net.FrameworkRpc.Bound( LuaState.CheckString( a, 0, "log.Audit" ), 32 );
var message = Net.FrameworkRpc.Bound( LuaState.CheckString( a, 1, "log.Audit" ), 500 );
Rp.Audit.Record( $"{realm.Gamemode?.Id ?? "-"}.{category}", "lua", message );
return null;
} );
}
}