Framework/Scripting/LuaRealm.cs

One Lua environment (server or client) for the roleplay framework. Wraps a LuaState, loads framework files, gamemodes and addons from a BaseFileSystem in GMod order (sh_ then sv_/cl_), implements include(), file.Find/file.Exists, timer.* with pause/stop/adjust, runs due timers in Tick, and funnels every engine to Lua call through PCall so script errors are logged and kept in a 50 entry list instead of throwing.

File Access
using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Lua;

namespace RoleplayFramework.Scripting;

public enum LuaRealmKind
{
	/// <summary>Only used to classify files (sh_). Shared files run inside both the server and the client state.</summary>
	Shared,
	Server,
	Client,
}

public readonly record struct ScriptError( DateTime TimeUtc, string Realm, string Gamemode, string Message, string Traceback );

/// <summary>
/// One Lua environment: the server state or the client state. Shared (sh_) files run in both, like Garry's Mod.
/// Owns file loading (<c>include</c>), timers and error reporting. Every engine→Lua call goes through
/// <see cref="Call"/>, which never throws: script failures are reported and the host keeps running.
/// </summary>
public sealed class LuaRealm
{
	public const string FrameworkRoot = "lua/framework";
	const int MaxIncludeDepth = 16;
	const int MaxTimers = 512;

	public LuaRealmKind Kind { get; }
	public LuaState State { get; }
	public string Name => Kind == LuaRealmKind.Server ? "server" : "client";
	public GamemodeManifest Gamemode { get; private set; }
	public LuaTable GM { get; private set; }
	public IReadOnlyList<string> LoadedFiles => _loaded;

	// Per-realm state for the API libraries.
	internal LuaTable PlayerMeta;
	internal readonly Dictionary<Guid, LuaUserData> PlayerCache = new();
	internal readonly Dictionary<string, LuaNet.Receiver> NetReceivers = new();
	internal LuaTable EntityMeta;

	/// <summary>Method tables Lua may extend via FindMetaTable(name): "Player", "Entity", "Panel".</summary>
	internal readonly Dictionary<string, LuaTable> MethodTables = new();
	internal readonly Dictionary<Guid, LuaUserData> EntityCache = new();
	internal int EntitiesCreated;

	/// <summary>Objects created through ents.Create; removed when the realm stops (reload, world end).</summary>
	internal readonly List<GameObject> CreatedObjects = new();

	readonly BaseFileSystem _fs;

	/// <summary>The file system this realm loads scripts from (snapshot or downloaded server copy).</summary>
	public BaseFileSystem Files => _fs;
	readonly List<string> _loaded = new();
	readonly Stack<string> _roots = new();

	static readonly List<ScriptError> _errors = new();
	public static IReadOnlyList<ScriptError> RecentErrors => _errors;

	/// <summary>Raised for each script error (used by tests and diagnostics).</summary>
	public static event Action<ScriptError> OnScriptError;

	public LuaRealm( LuaRealmKind kind, BaseFileSystem fs )
	{
		if ( kind == LuaRealmKind.Shared ) throw new ArgumentException( "A realm is Server or Client; shared files run in both" );

		Kind = kind;
		_fs = fs;
		State = new LuaState( Name );
		State.PrintHandler = line => RpLog.Info( "lua", $"[{Name}] {line}" );

		var G = State.Globals;
		G.Set( "SERVER", kind == LuaRealmKind.Server );
		G.Set( "CLIENT", kind == LuaRealmKind.Client );
		G.Set( "REALM", Name );
		G.Set( "FRAMEWORK_VERSION", Core.FrameworkInfo.Version );
		G.Set( "LUA_API_VERSION", Core.FrameworkInfo.LuaApiVersion );

		State.Register( "include", ( L, a ) => Include( LuaState.CheckString( a, 0, "include" ) ) );
		State.Register( "ErrorNoHalt", ( L, a ) =>
		{
			var msg = string.Join( " ", a.Select( v => L.ToStringMeta( v ) ) );
			Report( msg, null );
			return null;
		} );
		State.Register( "FindMetaTable", ( L, a ) =>
		{
			var name = LuaState.CheckString( a, 0, "FindMetaTable" );
			return new[] { MethodTables.TryGetValue( name, out var t ) ? LuaValue.FromTable( t ) : LuaValue.Nil };
		} );
		State.Register( "CurTime", ( L, a ) => new LuaValue[] { Time.Now } );
		State.Register( "RealTime", ( L, a ) => new LuaValue[] { RealTime.Now } );
		State.Register( "SysTime", ( L, a ) => new LuaValue[] { RealTime.NowDouble } );

		RegisterTimers();
		RegisterFileLibrary();
	}

	// ------------------------------------------------------------ errors

	public void Report( string message, string traceback )
	{
		var e = new ScriptError( DateTime.UtcNow, Name, (Gamemode?.Id ?? "-") + (_loadingAddon is null ? "" : $"+{_loadingAddon}"), message, traceback );
		lock ( _errors )
		{
			_errors.Add( e );
			if ( _errors.Count > 50 ) _errors.RemoveAt( 0 );
		}
		RpLog.Error( "lua", $"[{Name}|{e.Gamemode}] {message}{(string.IsNullOrEmpty( traceback ) ? "" : "\n" + traceback)}" );
		try { OnScriptError?.Invoke( e ); } catch { }
	}

	public static void ClearErrors()
	{
		lock ( _errors ) _errors.Clear();
	}

	/// <summary>Protected call from the host. Returns the results, or null if the script failed (already reported).</summary>
	public LuaValue[] Call( LuaValue fn, params LuaValue[] args )
	{
		var r = State.PCall( fn, args );
		if ( r.Success ) return r.Results;
		Report( r.Error, r.Traceback );
		return null;
	}

	// ------------------------------------------------------------ file loading

	/// <summary>Whether a file of <paramref name="fileRealm"/> may run in this realm.</summary>
	public bool Accepts( LuaRealmKind fileRealm ) => fileRealm == LuaRealmKind.Shared || fileRealm == Kind;

	/// <summary>
	/// Runs one file by full path (e.g. "lua/gamemodes/darkrp/gamemode/sh_init.lua"). Throws <see cref="LuaException"/>
	/// on failure so callers decide whether it is fatal.
	/// </summary>
	public LuaValue[] RunFile( string fullPath )
	{
		var rel = fullPath.StartsWith( "lua/" ) ? fullPath.Substring( 4 ) : fullPath;
		var realm = LuaPaths.RealmOf( fullPath );

		if ( realm is null )
			throw new LuaRuntimeException( $"cannot run '{rel}': Lua file names must start with sh_, sv_ or cl_" );
		if ( !Accepts( realm.Value ) )
			throw new LuaRuntimeException( $"cannot run '{rel}' in the {Name} realm (it is a {realm.Value.ToString().ToLowerInvariant()} file)" );
		if ( !_fs.FileExists( fullPath ) )
			throw new LuaRuntimeException( $"file not found: '{rel}'" );

		var source = _fs.ReadAllText( fullPath );
		var fn = State.Load( source, rel );
		_loaded.Add( rel );
		return State.Call( LuaValue.FromFunction( fn ) );
	}

	/// <summary>Lua include(path): relative to the gamemode (or framework) folder currently loading.</summary>
	static readonly System.Text.RegularExpressions.Regex DirPattern = new( @"^[a-z0-9_]+(/[a-z0-9_]+)*$" );
	static readonly System.Text.RegularExpressions.Regex MaskPattern = new( @"^[a-z0-9_*.]{1,64}$" );

	/// <summary>Folder that gamemode-relative paths resolve against: the file being included, else the running gamemode.</summary>
	string CurrentRoot => _roots.Count > 0 ? _roots.Peek()
		: Gamemode?.Root ?? throw new LuaRuntimeException( "no gamemode is loaded" );

	/// <summary>
	/// <c>file.Find("gamemode/modules/*")</c> → files, folders (sorted) inside the gamemode's own Lua folder;
	/// <c>file.Exists("gamemode/x.lua")</c>. Read-only and limited to the gamemode's scripts, so on a client it only sees
	/// the shared and client files the server sent. <c>AddCSLuaFile</c> exists for GMod compatibility and does nothing
	/// (sh_ and cl_ files are always sent).
	/// </summary>
	void RegisterFileLibrary()
	{
		var t = State.GetOrCreateLibrary( "file" );
		(string Dir, string Mask) Split( string pattern, string fname )
		{
			if ( pattern.Length > 128 || pattern.Contains( ".." ) || pattern.StartsWith( "/" ) || pattern.Contains( ':' ) || pattern.Contains( "\\" ) )
				throw LuaState.ArgError( 0, fname, "relative path inside the gamemode folder expected" );
			int slash = pattern.LastIndexOf( '/' );
			var dir = slash > 0 ? pattern.Substring( 0, slash ) : "";
			var mask = slash >= 0 ? pattern.Substring( slash + 1 ) : pattern;
			if ( (dir != "" && !DirPattern.IsMatch( dir )) || !MaskPattern.IsMatch( mask ) )
				throw LuaState.ArgError( 0, fname, "only lowercase a-z, 0-9, _, '/' and '*' are allowed" );
			return (dir == "" ? CurrentRoot : $"{CurrentRoot}/{dir}", mask);
		}

		LuaState.Register( t, "Find", ( L, a ) =>
		{
			var (full, mask) = Split( LuaState.CheckString( a, 0, "file.Find" ), "file.Find" );
			var files = new LuaTable();
			var dirs = new LuaTable();
			if ( _fs.DirectoryExists( full ) )
			{
				foreach ( var f in _fs.FindFile( full, mask, false ).OrderBy( x => x, StringComparer.Ordinal ) ) files.Append( f );
				foreach ( var d in _fs.FindDirectory( full, mask, false ).OrderBy( x => x, StringComparer.Ordinal ) ) dirs.Append( d );
			}
			return new LuaValue[] { files, dirs };
		} );
		LuaState.Register( t, "Exists", ( L, a ) =>
		{
			var path = LuaState.CheckString( a, 0, "file.Exists" );
			var (full, mask) = Split( path, "file.Exists" );
			return new LuaValue[] { !mask.Contains( '*' ) && (_fs.FileExists( $"{full}/{mask}" ) || _fs.DirectoryExists( $"{full}/{mask}" )) };
		} );
		State.Register( "AddCSLuaFile", ( L, a ) => null );
	}

	LuaValue[] Include( string path )
	{
		if ( _roots.Count == 0 )
			throw new LuaRuntimeException( "include() can only be used while a gamemode is loading" );
		if ( _roots.Count > MaxIncludeDepth )
			throw new LuaRuntimeException( "include() nested too deeply (possible include loop)" );

		var problem = LuaPaths.CheckRelative( path );
		if ( problem is not null )
			throw new LuaRuntimeException( $"include('{path}'): {problem}" );

		var root = _roots.Peek();
		var full = $"{root}/{path}";
		_roots.Push( root );
		try
		{
			return RunFile( full );
		}
		catch ( LuaSyntaxException e )
		{
			// Make syntax errors in included files catchable like any other Lua error.
			throw new LuaRuntimeException( LuaValue.FromString( e.Message ), true );
		}
		finally
		{
			_roots.Pop();
		}
	}

	/// <summary>Runs every framework file for this realm (lua/framework/sh_*, then sv_* or cl_*), in name order.</summary>
	public void LoadFrameworkFiles()
	{
		if ( !_fs.DirectoryExists( FrameworkRoot ) ) return;

		var files = _fs.FindFile( FrameworkRoot, "*.lua", false )
			.Where( f => LuaPaths.RealmOf( f ) is { } r && Accepts( r ) )
			.OrderBy( f => LuaPaths.RealmOf( f ) == LuaRealmKind.Shared ? 0 : 1 )
			.ThenBy( f => f, StringComparer.Ordinal )
			.ToList();

		_roots.Push( FrameworkRoot );
		try
		{
			foreach ( var f in files ) RunFile( $"{FrameworkRoot}/{f}" );
		}
		finally { _roots.Pop(); }
	}

	/// <summary>
	/// Loads a gamemode and its dependencies (dependencies first). For each: the shared entry, then this realm's entry.
	/// Throws on any failure; the caller treats that as "gamemode failed to load".
	/// </summary>
	public void LoadGamemode( GamemodeRegistry registry, string id )
	{
		var order = registry.LoadOrder( id ) ?? throw new LuaRuntimeException( registry.Invalid.TryGetValue( id, out var p )
			? $"gamemode '{id}' is invalid: {string.Join( "; ", p )}"
			: $"gamemode '{id}' was not found in {GamemodeRegistry.GamemodesRoot}" );

		var main = order[^1];
		Gamemode = main;

		GM = new LuaTable();
		GM.Set( "Name", main.Title );
		GM.Set( "FolderName", main.Id );
		GM.Set( "Version", main.Version );
		GM.Set( "Author", main.Author ?? "" );
		State.Globals.Set( "GM", GM );
		State.Globals.Set( "GAMEMODE", GM );

		foreach ( var m in order )
		{
			_roots.Push( m.Root );
			try
			{
				if ( m.Entry.Shared is not null ) RunFile( $"{m.Root}/{m.Entry.Shared}" );
				var own = Kind == LuaRealmKind.Server ? m.Entry.Server : m.Entry.Client;
				if ( own is not null ) RunFile( $"{m.Root}/{own}" );
			}
			finally { _roots.Pop(); }

			// Derivation: the next gamemode sees what this one defined as GM.BaseClass, so overrides can call
			// self.BaseClass.Method(self, ...) like Garry's Mod.
			if ( m != main )
			{
				var baseClass = new LuaTable();
				foreach ( var kv in GM.Pairs() ) baseClass.Set( kv.Key, kv.Value );
				GM.Set( "BaseClass", baseClass );
			}
		}
	}

	// ------------------------------------------------------------ addons

	public sealed class AddonLoad
	{
		public AddonManifest Manifest;
		public bool Loaded;
		public string Error;
	}

	readonly List<AddonLoad> _addons = new();
	/// <summary>Addons this realm tried to load, in load order, with the outcome.</summary>
	public IReadOnlyList<AddonLoad> Addons => _addons;

	/// <summary>Addon whose files are running right now (for error messages), else null.</summary>
	string _loadingAddon;

	/// <summary>
	/// Loads addons after the gamemode, in the given order. Unlike the gamemode, a broken addon is not fatal: it is
	/// reported and skipped, and the others still load. (Hooks it registered before failing stay registered.)
	/// </summary>
	public void LoadAddons( IEnumerable<AddonManifest> order )
	{
		foreach ( var m in order )
		{
			var rec = new AddonLoad { Manifest = m };
			_addons.Add( rec );

			var missing = m.Dependencies.Keys.FirstOrDefault( d => !_addons.Any( a => a.Loaded && a.Manifest.Id == d ) );
			if ( missing is not null )
			{
				rec.Error = $"skipped: dependency '{missing}' failed to load";
				Report( $"Addon '{m.Id}' {rec.Error}", null );
				continue;
			}

			_roots.Push( m.Root );
			_loadingAddon = m.Id;
			try
			{
				if ( m.Entry is not null )
				{
					if ( m.Entry.Shared is not null ) RunFile( $"{m.Root}/{m.Entry.Shared}" );
					var own = Kind == LuaRealmKind.Server ? m.Entry.Server : m.Entry.Client;
					if ( own is not null ) RunFile( $"{m.Root}/{own}" );
				}
				else
				{
					var files = _fs.FindFile( m.Root, "*.lua", false ).ToList();
					foreach ( var f in files.Where( f => f.StartsWith( "sh_" ) ).OrderBy( f => f, StringComparer.Ordinal ) ) RunFile( $"{m.Root}/{f}" );
					var prefix = Kind == LuaRealmKind.Server ? "sv_" : "cl_";
					foreach ( var f in files.Where( f => f.StartsWith( prefix ) ).OrderBy( f => f, StringComparer.Ordinal ) ) RunFile( $"{m.Root}/{f}" );
				}
				rec.Loaded = true;
			}
			catch ( LuaException e )
			{
				rec.Error = e.Message;
				Report( $"Addon '{m.Id}' failed to load and was skipped: {e.Message}", (e as LuaRuntimeException)?.LuaTraceback );
			}
			finally
			{
				_loadingAddon = null;
				_roots.Pop();
			}
		}

		int ok = _addons.Count( a => a.Loaded );
		if ( _addons.Count > 0 )
			RpLog.Info( "addons", $"[{Name}] {ok}/{_addons.Count} addon(s) loaded: {string.Join( ", ", _addons.Select( a => $"{a.Manifest.Id} {a.Manifest.Version}{(a.Loaded ? "" : " (failed)")}" ) )}" );
	}

	/// <summary>hook.Run(name, ...) from C#: hooks first, then GM:name. Errors are reported, never thrown.</summary>
	public LuaValue[] RunHook( string name, params LuaValue[] args )
	{
		var hook = State.Globals.Get( "hook" );
		if ( !hook.IsTable ) return null;
		var run = hook.AsTable.Get( "Run" );
		if ( !run.IsFunction ) return null;

		var full = new LuaValue[args.Length + 1];
		full[0] = name;
		args.CopyTo( full, 1 );
		return Call( run, full );
	}

	// ------------------------------------------------------------ timers

	sealed class LuaTimer
	{
		public string Id;
		public double Interval;
		public double Next;
		public int RepsLeft; // 0 = forever
		public LuaValue Fn;
		public bool Paused;
		public double Remaining; // while paused: seconds left
	}

	readonly Dictionary<string, LuaTimer> _timers = new();
	int _anon;

	public int TimerCount => _timers.Count;

	void RegisterTimers()
	{
		var T = State.GetOrCreateLibrary( "timer" );

		LuaState.Register( T, "Simple", ( L, a ) =>
		{
			var delay = Math.Max( 0, LuaState.CheckNumber( a, 0, "timer.Simple" ) );
			var fn = LuaState.CheckFunction( a, 1, "timer.Simple" );
			AddTimer( $"__simple{++_anon}", delay, 1, LuaValue.FromFunction( fn ) );
			return null;
		} );

		LuaState.Register( T, "Create", ( L, a ) =>
		{
			var id = LuaState.CheckString( a, 0, "timer.Create" );
			var delay = LuaState.CheckNumber( a, 1, "timer.Create" );
			var reps = LuaState.CheckInt( a, 2, "timer.Create" );
			var fn = LuaState.CheckFunction( a, 3, "timer.Create" );
			if ( delay < 0.01 ) throw LuaState.ArgError( 1, "timer.Create", "delay must be at least 0.01 seconds" );
			if ( reps < 0 ) throw LuaState.ArgError( 2, "timer.Create", "repetitions must be 0 (forever) or more" );
			AddTimer( "u:" + id, delay, reps, LuaValue.FromFunction( fn ) );
			return null;
		} );

		LuaState.Register( T, "Remove", ( L, a ) =>
		{
			_timers.Remove( "u:" + LuaState.CheckString( a, 0, "timer.Remove" ) );
			return null;
		} );

		LuaState.Register( T, "Exists", ( L, a ) =>
			new LuaValue[] { _timers.ContainsKey( "u:" + LuaState.CheckString( a, 0, "timer.Exists" ) ) } );

		// GMod extras. Each returns false when the timer doesn't exist (like GMod).
		LuaTimer Find( LuaValue[] a, string fname ) => _timers.TryGetValue( "u:" + LuaState.CheckString( a, 0, fname ), out var t ) ? t : null;

		T.Set( "Destroy", T.Get( "Remove" ) );

		LuaState.Register( T, "Adjust", ( L, a ) =>
		{
			var t = Find( a, "timer.Adjust" );
			if ( t is null ) return new LuaValue[] { false };
			var delay = LuaState.CheckNumber( a, 1, "timer.Adjust" );
			if ( delay < 0.01 ) throw LuaState.ArgError( 1, "timer.Adjust", "delay must be at least 0.01 seconds" );
			t.Interval = delay;
			if ( t.Paused ) t.Remaining = Math.Min( t.Remaining, delay ); else t.Next = Math.Min( t.Next, Time.Now + delay );
			if ( LuaState.Arg( a, 2 ).IsNumber ) t.RepsLeft = Math.Max( 0, (int)LuaState.Arg( a, 2 ).Number );
			if ( LuaState.Arg( a, 3 ).IsFunction ) t.Fn = LuaState.Arg( a, 3 );
			return new LuaValue[] { true };
		} );

		LuaState.Register( T, "Pause", ( L, a ) =>
		{
			var t = Find( a, "timer.Pause" );
			if ( t is null || t.Paused ) return new LuaValue[] { false };
			t.Paused = true;
			t.Remaining = Math.Max( 0, t.Next - Time.Now );
			return new LuaValue[] { true };
		} );

		LuaState.Register( T, "UnPause", ( L, a ) =>
		{
			var t = Find( a, "timer.UnPause" );
			if ( t is null || !t.Paused ) return new LuaValue[] { false };
			t.Paused = false;
			t.Next = Time.Now + t.Remaining;
			return new LuaValue[] { true };
		} );

		LuaState.Register( T, "Toggle", ( L, a ) =>
		{
			var t = Find( a, "timer.Toggle" );
			if ( t is null ) return new LuaValue[] { false };
			if ( t.Paused ) { t.Paused = false; t.Next = Time.Now + t.Remaining; }
			else { t.Paused = true; t.Remaining = Math.Max( 0, t.Next - Time.Now ); }
			return new LuaValue[] { !t.Paused };
		} );

		// Stop: paused and reset to a full interval; Start: (re)starts a full interval.
		LuaState.Register( T, "Stop", ( L, a ) =>
		{
			var t = Find( a, "timer.Stop" );
			if ( t is null ) return new LuaValue[] { false };
			t.Paused = true;
			t.Remaining = t.Interval;
			return new LuaValue[] { true };
		} );

		LuaState.Register( T, "Start", ( L, a ) =>
		{
			var t = Find( a, "timer.Start" );
			if ( t is null ) return new LuaValue[] { false };
			t.Paused = false;
			t.Next = Time.Now + t.Interval;
			return new LuaValue[] { true };
		} );

		LuaState.Register( T, "TimeLeft", ( L, a ) =>
		{
			var t = Find( a, "timer.TimeLeft" );
			if ( t is null ) return new[] { LuaValue.Nil };
			return new LuaValue[] { t.Paused ? -t.Remaining : Math.Max( 0, t.Next - Time.Now ) }; // GMod: negative while paused
		} );

		LuaState.Register( T, "RepsLeft", ( L, a ) =>
		{
			var t = Find( a, "timer.RepsLeft" );
			return new[] { t is null ? LuaValue.Nil : LuaValue.FromNumber( t.RepsLeft ) };
		} );
	}

	void AddTimer( string id, double delay, int reps, LuaValue fn )
	{
		if ( !_timers.ContainsKey( id ) && _timers.Count >= MaxTimers )
			throw new LuaRuntimeException( $"too many timers (limit {MaxTimers})" );
		_timers[id] = new LuaTimer { Id = id, Interval = delay, Next = Time.Now + delay, RepsLeft = reps, Fn = fn };
	}

	/// <summary>Runs due timers. Called once per frame by the world.</summary>
	public void Tick( double now )
	{
		if ( _timers.Count == 0 ) return;

		foreach ( var t in _timers.Values.Where( t => !t.Paused && now >= t.Next ).ToList() )
		{
			if ( !_timers.TryGetValue( t.Id, out var current ) || current != t ) continue; // removed by another timer

			if ( t.RepsLeft == 1 ) _timers.Remove( t.Id );
			else
			{
				if ( t.RepsLeft > 1 ) t.RepsLeft--;
				t.Next = now + t.Interval;
			}

			if ( Call( t.Fn ) is null )
			{
				// A timer that errors is removed so it can't spam the log every interval.
				_timers.Remove( t.Id );
				RpLog.Warn( "lua", $"[{Name}] removed timer '{(t.Id.StartsWith( "u:" ) ? t.Id.Substring( 2 ) : "timer.Simple")}' after an error" );
			}
		}
	}
}