Framework/Diagnostics/DiagnosticsReport.cs

Builds a human-readable status report for a Roleplay Framework package: framework/API/protocol versions, startup stages, gamemode and addon registries, Lua realm and module state, event counts and recent script/log errors. Also adds the rp_status and rp_lua_selftest console commands that print the report or run the Lua self tests.

using System;
using System.Linq;
using System.Text;
using RoleplayFramework.Bootstrap;
using RoleplayFramework.Core;

namespace RoleplayFramework.Diagnostics;

/// <summary>Human-readable framework status, used by the rp_status command and the menu's Diagnostics page.</summary>
public static class DiagnosticsReport
{
	public static string Build()
	{
		var sb = new StringBuilder();
		sb.AppendLine( $"{FrameworkInfo.Name} {FrameworkInfo.Version}" );
		sb.AppendLine( $"  Lua API version   v{FrameworkInfo.LuaApiVersion}" );
		sb.AppendLine( $"  Lua runtime       {FrameworkInfo.LuaRuntime}" );
		sb.AppendLine( $"  Protocol          v{FrameworkInfo.ProtocolVersion}" );
		sb.AppendLine( $"  Process role      {RealmInfo.Describe()}" );
		sb.AppendLine( $"  Startup state     {FrameworkHost.State}{(FrameworkHost.FailureReason is null ? "" : " - " + FrameworkHost.FailureReason)}" );

		foreach ( var s in FrameworkHost.Stages )
			sb.AppendLine( $"    {s.Name,-12} {s.Result,-8} {s.Milliseconds,6:F1} ms  {s.Detail}" );

		var cfg = FrameworkHost.Config;
		sb.AppendLine( $"  Default gamemode  {cfg.DefaultGamemode}" );
		var reg = Scripting.GamemodeRegistry.Current;
		sb.AppendLine( $"  Gamemodes found   {(reg.Valid.Count == 0 ? "none" : string.Join( ", ", reg.Valid.Values.Select( g => $"{g.Id} {g.Version}" ) ))}{(reg.Invalid.Count > 0 ? $"  (rejected: {string.Join( ", ", reg.Invalid.Keys )})" : "")}" );
		sb.AppendLine( $"  Active gamemode   {(Scripting.LuaRuntime.ActiveGamemode is { } gm ? $"{gm} {Scripting.LuaRuntime.ActiveGamemodeVersion}" : "none (not in a world)")}" );
		sb.AppendLine( $"  Lua files         {(Scripting.LuaSource.UsesDataFolder ? Scripting.LuaSource.DataFolderPath + "  (edit here, then rp_lua_reload)" : "built-in (LuaSource = builtin)")}" );
		var mounted = Core.ContentPackages.Mounted;
		sb.AppendLine( $"  Packages          {(mounted.Count == 0 ? "none" : string.Join( ", ", mounted.Select( kv => $"{kv.Key} ({kv.Value})" ) ))}" );
		sb.AppendLine( $"  Server realm      {RealmLine( Scripting.LuaRuntime.Server )}" );
		sb.AppendLine( $"  Client realm      {RealmLine( Scripting.LuaRuntime.Client )}" );
		sb.AppendLine( $"  Gamemode modules  {ModulesLine( Scripting.LuaRuntime.Server ?? Scripting.LuaRuntime.Client )}" );
		var realmForAddons = Scripting.LuaRuntime.Server ?? Scripting.LuaRuntime.Client;
		sb.AppendLine( $"  Addons            {(realmForAddons is null ? "not in a world (rp_addons lists installed ones)" : realmForAddons.Addons.Count == 0 ? "none" : string.Join( ", ", realmForAddons.Addons.Select( a => $"{a.Manifest.Id} {a.Manifest.Version}{(a.Loaded ? "" : " (FAILED)")}" ) ))}" );
		foreach ( var e in Scripting.AddonRegistry.Current.All.Values.Where( e => e.Status != Scripting.AddonStatus.Active ) )
			sb.AppendLine( $"    {e.Id}: {e.Status.ToString().ToLowerInvariant()} - {e.Reason}" );
		sb.AppendLine( $"  Scene             {Game.ActiveScene?.Name ?? "(none)"}" );

		var players = Networking.IsActive ? Connection.All.Count().ToString() : "0 (not networked)";
		sb.AppendLine( $"  Connections       {players}" );

		var scriptErrors = Scripting.LuaRealm.RecentErrors;
		sb.AppendLine( $"  Script errors     {(scriptErrors.Count == 0 ? "none" : scriptErrors.Count.ToString())}" );
		foreach ( var e in scriptErrors.Skip( Math.Max( 0, scriptErrors.Count - 3 ) ) )
			sb.AppendLine( $"    {e.TimeUtc:HH:mm:ss} [{e.Realm}|{e.Gamemode}] {e.Message}" );

		var errors = RpLog.Recent( 5, RpLogLevel.Warning );
		sb.AppendLine( $"  Recent problems   {(errors.Count == 0 ? "none" : "")}" );
		foreach ( var e in errors )
			sb.AppendLine( $"    {e.TimeUtc:HH:mm:ss} {e.Level} [{e.Category}] {e.Message}" );

		return sb.ToString().TrimEnd();
	}

	/// <summary>GM.LoadedModules of the base gamemode's module loader (e.g. "gamemode/modules/chat").</summary>
	static string ModulesLine( Scripting.LuaRealm r )
	{
		if ( r?.GM is null ) return "not in a world";
		var list = r.GM.Get( "LoadedModules" );
		if ( !list.IsTable ) return "none (the gamemode doesn't use GM:LoadModules)";
		var names = list.AsTable.Pairs().Select( kv => kv.Value.IsString ? kv.Value.AsString.Substring( kv.Value.AsString.LastIndexOf( '/' ) + 1 ) : "?" ).ToList();
		return names.Count == 0 ? "none" : $"{names.Count}: {string.Join( ", ", names )}";
	}

	static string RealmLine( Scripting.LuaRealm r ) => r is null
		? "not running"
		: $"running, {r.LoadedFiles.Count} files, {r.TimerCount} timers, {r.NetReceivers.Count} net receivers";
}

public static class DiagnosticsCommands
{
	[ConCmd( "rp_status", Help = "Show Roleplay Framework status: versions, realm, startup stages, recent problems" )]
	public static void Status()
	{
		foreach ( var line in DiagnosticsReport.Build().Split( '\n' ) )
			Log.Info( line.TrimEnd( '\r' ) );
	}

	[ConCmd( "rp_lua_selftest", Help = "Run the Lua runtime conformance and sandbox tests" )]
	public static void LuaSelfTest()
	{
		var summary = Lua.Diagnostics.LuaSelfTest.RunAll();
		if ( summary.Failed == 0 ) RpLog.Info( "lua", summary.Report );
		else RpLog.Error( "lua", summary.Report );
	}
}