Static bootstrap host for a roleplay framework. Runs a fixed sequence of startup stages (environment, config, Lua runtime smoke test, gamemode discovery), records each stage's result and duration, and exposes State, FailureReason and BootedAtUtc for the rest of the code. EnsureBooted runs it once, Reboot forces a rerun.
using System;
using System.Collections.Generic;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
namespace RoleplayFramework.Bootstrap;
public enum StartupState
{
NotStarted,
Booting,
Ready,
Failed,
}
public enum StageResult { Ok, Warning, Failed }
public readonly record struct StartupStage( string Name, StageResult Result, double Milliseconds, string Detail );
/// <summary>
/// Process-wide framework lifetime. Boots once per game session, in a fixed order of stages,
/// and records each stage's result for diagnostics. Gameplay must not start unless <see cref="State"/> is Ready.
/// </summary>
public static class FrameworkHost
{
public static StartupState State { get; private set; } = StartupState.NotStarted;
public static string FailureReason { get; private set; }
public static DateTime? BootedAtUtc { get; private set; }
static readonly List<StartupStage> _stages = new();
public static IReadOnlyList<StartupStage> Stages => _stages;
public static FrameworkConfig Config => FrameworkConfigStore.Current;
/// <summary>Raised after boot completes (Ready or Failed).</summary>
public static event Action<StartupState> OnStateChanged;
/// <summary>Boots the framework if it hasn't been. Safe to call from any scene; does nothing after the first time.</summary>
public static void EnsureBooted()
{
if ( State != StartupState.NotStarted ) return;
Boot();
}
/// <summary>Forces a fresh boot (development / diagnostics only).</summary>
public static void Reboot()
{
State = StartupState.NotStarted;
Boot();
}
static void Boot()
{
State = StartupState.Booting;
FailureReason = null;
_stages.Clear();
RpLog.Info( "bootstrap", $"{FrameworkInfo.Name} {FrameworkInfo.Version} starting (Lua API v{FrameworkInfo.LuaApiVersion}, protocol v{FrameworkInfo.ProtocolVersion})" );
bool ok =
RunStage( "environment", StageEnvironment ) &&
RunStage( "config", StageConfig ) &&
RunStage( "lua-runtime", StageLuaRuntime ) &&
RunStage( "gamemodes", StageGamemodes );
if ( ok )
{
State = StartupState.Ready;
BootedAtUtc = DateTime.UtcNow;
RpLog.Info( "bootstrap", $"Ready ({_stages.Count} stages)" );
}
else
{
State = StartupState.Failed;
RpLog.Error( "bootstrap", $"Startup failed: {FailureReason}" );
}
try { OnStateChanged?.Invoke( State ); }
catch ( Exception e ) { RpLog.Error( "bootstrap", $"State listener failed: {e.Message}" ); }
}
/// <summary>A stage returns a detail string, or throws to fail. Returning a string starting with "!" marks a warning.</summary>
static bool RunStage( string name, Func<string> stage )
{
var start = DateTime.UtcNow;
StageResult result;
string detail;
try
{
detail = stage() ?? "";
result = detail.StartsWith( "!" ) ? StageResult.Warning : StageResult.Ok;
if ( result == StageResult.Warning ) detail = detail.Substring( 1 );
}
catch ( Exception e )
{
result = StageResult.Failed;
detail = e.Message;
FailureReason = $"stage '{name}': {e.Message}";
}
var ms = (DateTime.UtcNow - start).TotalMilliseconds;
_stages.Add( new StartupStage( name, result, ms, detail ) );
var line = $"stage {name}: {result} ({ms:F1} ms){(string.IsNullOrEmpty( detail ) ? "" : " - " + detail)}";
if ( result == StageResult.Failed ) RpLog.Error( "bootstrap", line );
else if ( result == StageResult.Warning ) RpLog.Warn( "bootstrap", line );
else RpLog.Info( "bootstrap", line );
return result != StageResult.Failed;
}
static string StageEnvironment()
{
return $"role={RealmInfo.Describe()}, editor={Application.IsEditor}, headless={Application.IsHeadless}";
}
static string StageConfig()
{
var before = RpLog.Recent( 1000, RpLogLevel.Warning ).Count;
var c = FrameworkConfigStore.Load();
var warnings = RpLog.Recent( 1000, RpLogLevel.Warning ).Count - before;
var detail = $"gamemode={c.DefaultGamemode}, maxPlayers={c.MaxPlayers}, devMode={c.DevMode}";
return warnings > 0 ? $"!{detail} ({warnings} correction(s), see log)" : detail;
}
static string StageGamemodes()
{
// Dedicated servers / real game: make the editable copy in the data folder first (never overwrites).
Scripting.LuaSource.EnsureDataCopy();
var reg = Scripting.GamemodeRegistry.Discover( Scripting.LuaSource.Snapshot() );
reg.LogSummary();
var id = Config.DefaultGamemode;
var source = Scripting.LuaSource.UsesDataFolder ? $"data folder ({Scripting.LuaSource.DataFolderPath})" : "built-in files";
var detail = $"{reg.Valid.Count} valid, {reg.Invalid.Count} rejected; default '{id}'; loading from {source}";
// Clients download the server's gamemode when joining, so a missing local copy only matters for hosting.
if ( !reg.Valid.ContainsKey( id ) ) return $"!{detail} is not available locally - joining servers still works, hosting will fail";
if ( reg.Invalid.Count > 0 ) return $"!{detail} (see log for rejected gamemodes)";
return detail;
}
static string StageLuaRuntime()
{
// Smoke-test the interpreter so a broken runtime fails startup loudly instead of at first script.
var L = new Lua.LuaState( "bootcheck" );
var r = L.DoString( "local t = {} for i = 1, 10 do t[#t+1] = i end return table.concat(t, ','), _VERSION", "bootcheck" );
if ( r.Length < 2 || r[0].AsString != "1,2,3,4,5,6,7,8,9,10" )
throw new InvalidOperationException( "Lua runtime smoke test returned an unexpected result" );
return FrameworkInfo.LuaRuntime;
}
}