Framework/Core/FrameworkConfig.cs

Framework-level configuration model and its JSON store. FrameworkConfig holds server defaults (gamemode, name, max players, map, Lua source, packages, disabled addons) and Validate() clamps or resets invalid values; FrameworkConfigStore loads roleplay/framework.json from FileSystem.Data, writes defaults when missing, backs up unparsable files and logs each correction.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RoleplayFramework.Diagnostics;

namespace RoleplayFramework.Core;

/// <summary>
/// Framework-level configuration (not gamemode config). Stored as JSON in the data folder at
/// <see cref="FrameworkConfigStore.Path"/>. Values are validated on load; anything invalid falls back to a default.
/// </summary>
public sealed class FrameworkConfig
{
	public const int CurrentSchemaVersion = 1;

	public int SchemaVersion { get; set; } = CurrentSchemaVersion;

	/// <summary>Gamemode id the server runs when none is chosen explicitly.</summary>
	public string DefaultGamemode { get; set; } = "darkrp";

	/// <summary>Default name for a locally hosted server.</summary>
	public string ServerName { get; set; } = "Roleplay Server";

	/// <summary>Default max players for a locally hosted server (clamped to the project's limit).</summary>
	public int MaxPlayers { get; set; } = 32;

	/// <summary>Enables development features such as Lua hot reload. Never enable on a public server.</summary>
	public bool DevMode { get; set; }

	/// <summary>Password for this machine's dedicated server lobby (empty = none). Server-local; never sent to clients.</summary>
	public string ServerPassword { get; set; } = "";

	/// <summary>
	/// Map for a dedicated server ("" = the gamemode's default map). A map given on the command line
	/// (+game &lt;game&gt; &lt;map&gt;) takes precedence.
	/// </summary>
	public string Map { get; set; } = "";

	/// <summary>
	/// Where gamemode Lua is loaded from: "data" (default: an editable copy in this machine's data folder, made on
	/// first start) or "builtin" (the game's own files; for framework developers editing Assets/lua).
	/// "auto" is accepted and means "data".
	/// </summary>
	public string LuaSource { get; set; } = "data";

	/// <summary>sbox.game packages this server requires (models, materials, ...). Players download them when joining.</summary>
	public List<string> Packages { get; set; } = new();

	/// <summary>
	/// Package collections: JSON files listing package idents, either a URL ("https://example.com/content.json") or a
	/// file in this server's data folder relative to "roleplay/" (e.g. "collections/content.json").
	/// </summary>
	public List<string> Collections { get; set; } = new();

	/// <summary>Lua addons (lua/addons/&lt;id&gt;) this server does NOT run. Every other installed addon is on.</summary>
	public List<string> DisabledAddons { get; set; } = new();

	public const int ProjectMaxPlayers = 64;
	static readonly Regex IdPattern = new( "^[a-z0-9_]{1,32}$" );

	public static bool IsValidId( string id ) => id is not null && IdPattern.IsMatch( id );

	/// <summary>Fixes invalid values in place and returns a description of each correction.</summary>
	public List<string> Validate()
	{
		var fixes = new List<string>();
		var defaults = new FrameworkConfig();

		if ( !IsValidId( DefaultGamemode ) )
		{
			fixes.Add( $"DefaultGamemode '{DefaultGamemode}' is not a valid id (a-z, 0-9, _), using '{defaults.DefaultGamemode}'" );
			DefaultGamemode = defaults.DefaultGamemode;
		}

		var name = (ServerName ?? "").Trim();
		if ( name.Length == 0 ) { fixes.Add( "ServerName was empty" ); name = defaults.ServerName; }
		if ( name.Length > 64 ) { fixes.Add( "ServerName longer than 64 characters was truncated" ); name = name.Substring( 0, 64 ); }
		ServerName = name;

		if ( MaxPlayers < 1 || MaxPlayers > ProjectMaxPlayers )
		{
			fixes.Add( $"MaxPlayers {MaxPlayers} out of range 1-{ProjectMaxPlayers}" );
			MaxPlayers = Math.Clamp( MaxPlayers, 1, ProjectMaxPlayers );
		}

		if ( LuaSource is not ("auto" or "data" or "builtin") )
		{
			fixes.Add( $"LuaSource '{LuaSource}' must be auto, data or builtin" );
			LuaSource = "auto";
		}

		if ( !string.IsNullOrEmpty( Map ) && MapCatalog.Validate( Map ) is { } badMap )
		{
			fixes.Add( $"Map: {badMap} Using the gamemode's default map." );
			Map = "";
		}

		Packages ??= new();
		Collections ??= new();
		DisabledAddons ??= new();
		foreach ( var a in DisabledAddons.ToList() )
		{
			if ( IsValidId( a ) ) continue;
			fixes.Add( $"DisabledAddons: '{a}' is not a valid addon id" );
			DisabledAddons.Remove( a );
		}
		foreach ( var c in Collections.ToList() )
		{
			if ( ContentPackages.CheckCollectionSource( c ) is not { } bad ) continue;
			fixes.Add( $"Collections: {bad}" );
			Collections.Remove( c );
		}

		return fixes;
	}
}

public static class FrameworkConfigStore
{
	public const string Directory = "roleplay";
	public const string Path = "roleplay/framework.json";

	public static FrameworkConfig Current { get; private set; } = new();

	/// <summary>Loads (or creates) the config. Never throws: missing or corrupt files fall back to defaults.</summary>
	public static FrameworkConfig Load()
	{
		var fs = FileSystem.Data;
		FrameworkConfig config = null;

		static bool Parses( string text ) => Json.TryDeserialize( text, out FrameworkConfig c ) && c is not null;

		try
		{
			if ( !SafeDataFile.Exists( Path ) )
			{
				config = new FrameworkConfig();
				Save( config );
				RpLog.Info( "config", $"No config found, wrote defaults to data/{Path}" );
			}
			else
			{
				var text = SafeDataFile.Read( Path, Parses, out bool recovered );
				if ( text is not null )
				{
					Json.TryDeserialize( text, out config );
					if ( recovered )
					{
						RpLog.Warn( "config", $"data/{Path} was damaged by an interrupted write; recovered the last saved copy" );
						Save( config );
					}
				}
				else
				{
					var backup = $"{Path}.corrupt-{DateTime.UtcNow:yyyyMMdd-HHmmss}";
					if ( fs.FileExists( Path ) ) fs.WriteAllText( backup, fs.ReadAllText( Path ) );
					RpLog.Warn( "config", $"data/{Path} could not be parsed; kept a copy at data/{backup} and using defaults" );
					config = new FrameworkConfig();
					Save( config );
				}
			}
		}
		catch ( Exception e )
		{
			RpLog.Error( "config", $"Failed to read data/{Path}: {e.Message}. Using defaults." );
			config = new FrameworkConfig();
		}

		if ( config.SchemaVersion > FrameworkConfig.CurrentSchemaVersion )
			RpLog.Warn( "config", $"Config schema {config.SchemaVersion} is newer than supported {FrameworkConfig.CurrentSchemaVersion}; unknown fields are ignored" );
		config.SchemaVersion = FrameworkConfig.CurrentSchemaVersion;

		foreach ( var fix in config.Validate() )
			RpLog.Warn( "config", fix );

		Current = config;
		return config;
	}

	public static void Save( FrameworkConfig config )
	{
		SafeDataFile.Write( Path, Json.Serialize( config ) );
	}
}