Framework/Scripting/Addons/AddonRegistry.cs

Addon registry for the roleplay framework. Scans lua/addons/*/addon.json on a BaseFileSystem, validates each manifest, marks addons Disabled, Incompatible, Invalid (bad json or dependency cycle) or Blocked (missing or mismatched dependency), then builds LoadOrder with dependencies first and alphabetical ties so server and clients agree.

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

namespace RoleplayFramework.Scripting;

public enum AddonStatus
{
	/// <summary>Will be loaded (or was loaded) for this world.</summary>
	Active,
	/// <summary>Switched off in framework.json ("DisabledAddons").</summary>
	Disabled,
	/// <summary>Not made for the running gamemode ("gamemodes" in addon.json).</summary>
	Incompatible,
	/// <summary>A dependency is missing, switched off, incompatible or the wrong version.</summary>
	Blocked,
	/// <summary>addon.json is broken, or the addon is part of a dependency cycle.</summary>
	Invalid,
}

public sealed class AddonEntry
{
	public string Id { get; init; }
	public AddonManifest Manifest { get; init; }
	public AddonStatus Status { get; set; }
	public string Reason { get; set; }
}

/// <summary>
/// Finds the addons under <c>lua/addons/*/addon.json</c> and decides which run with a given gamemode chain:
/// valid, not switched off, made for the gamemode, and every dependency active in a matching version.
/// <see cref="LoadOrder"/> lists the active ones with dependencies first, otherwise alphabetical, so the server and
/// every client load them in the same order. Folders starting with "_" (templates) are ignored.
/// </summary>
public sealed class AddonRegistry
{
	public const string AddonsRoot = "lua/addons";
	public const int MaxAddons = 256;

	readonly Dictionary<string, AddonEntry> _all = new();
	public IReadOnlyDictionary<string, AddonEntry> All => _all;
	public List<AddonManifest> LoadOrder { get; } = new();

	/// <summary>The resolution used by the running server (for diagnostics and rp_addons).</summary>
	public static AddonRegistry Current { get; set; } = new();

	public static AddonRegistry Resolve( BaseFileSystem fs, IReadOnlyCollection<string> gamemodeChain, IEnumerable<string> disabled )
	{
		var reg = new AddonRegistry();
		var off = new HashSet<string>( disabled ?? Enumerable.Empty<string>() );
		var chain = new HashSet<string>( gamemodeChain ?? new List<string>() );

		if ( fs.DirectoryExists( AddonsRoot ) )
		{
			foreach ( var folder in fs.FindDirectory( AddonsRoot, "*", false ).OrderBy( x => x, System.StringComparer.Ordinal ) )
			{
				if ( folder.StartsWith( "_" ) ) continue;
				var root = $"{AddonsRoot}/{folder}";
				if ( !fs.FileExists( $"{root}/addon.json" ) ) continue;
				if ( reg._all.Count >= MaxAddons ) { RpLog.Warn( "addons", $"More than {MaxAddons} addons; '{folder}' and later ones are ignored" ); break; }

				AddonManifest m = null;
				string problem = null;
				try
				{
					if ( !Json.TryDeserialize( fs.ReadAllText( $"{root}/addon.json" ), out m ) || m is null ) problem = "addon.json is not valid JSON";
				}
				catch ( System.Exception e ) { problem = $"addon.json could not be read: {e.Message}"; }

				if ( problem is null )
				{
					m.Root = root;
					var problems = m.Validate( folder );
					if ( problems.Count > 0 ) problem = string.Join( "; ", problems );
				}

				var entry = new AddonEntry { Id = folder, Manifest = problem is null ? m : null };
				if ( problem is not null ) { entry.Status = AddonStatus.Invalid; entry.Reason = problem; }
				else if ( off.Contains( folder ) ) { entry.Status = AddonStatus.Disabled; entry.Reason = "switched off in framework.json (DisabledAddons)"; }
				else if ( m.Gamemodes.Count > 0 && !m.Gamemodes.Any( chain.Contains ) )
				{
					entry.Status = AddonStatus.Incompatible;
					entry.Reason = $"made for {string.Join( ", ", m.Gamemodes )}, not this gamemode";
				}
				else entry.Status = AddonStatus.Active;
				reg._all[folder] = entry;
			}
		}

		// Cycles among the remaining addons: report every member.
		// Find every cycle before marking any, so all members are reported.
		var cycles = reg._all.Values.Where( e => e.Status == AddonStatus.Active )
			.Select( e => (Entry: e, Cycle: reg.FindCycle( e.Id )) ).Where( x => x.Cycle is not null && x.Cycle.Contains( x.Entry.Id ) ).ToList(); // depending on a cycle = blocked below
		foreach ( var (e, cycle) in cycles )
		{
			e.Status = AddonStatus.Invalid;
			e.Reason = $"dependency cycle: {string.Join( " -> ", cycle )}";
		}

		// Dependencies must be active in a matching version; repeat until nothing changes (blocking cascades).
		bool changed = true;
		while ( changed )
		{
			changed = false;
			foreach ( var e in reg._all.Values.Where( e => e.Status == AddonStatus.Active ) )
			{
				foreach ( var (dep, constraint) in e.Manifest.Dependencies )
				{
					string why = null;
					if ( !reg._all.TryGetValue( dep, out var d ) ) why = $"needs addon '{dep}', which is not installed";
					else if ( d.Status != AddonStatus.Active ) why = $"needs addon '{dep}', which is {d.Status.ToString().ToLowerInvariant()}";
					else if ( !VersionConstraint.Satisfies( d.Manifest.Version, constraint ) ) why = $"needs '{dep}' {constraint}, but {d.Manifest.Version} is installed";
					if ( why is null ) continue;
					e.Status = AddonStatus.Blocked;
					e.Reason = why;
					changed = true;
					break;
				}
				if ( changed ) break;
			}
		}

		// Load order: dependencies first, ties alphabetical.
		var seen = new HashSet<string>();
		void Add( string id )
		{
			if ( !seen.Add( id ) ) return;
			var m = reg._all[id].Manifest;
			foreach ( var d in m.Dependencies.Keys.OrderBy( x => x, System.StringComparer.Ordinal ) ) Add( d );
			reg.LoadOrder.Add( m );
		}
		foreach ( var e in reg._all.Values.Where( e => e.Status == AddonStatus.Active ).OrderBy( e => e.Id, System.StringComparer.Ordinal ).ToList() )
			Add( e.Id );

		return reg;
	}

	List<string> FindCycle( string start )
	{
		var path = new List<string>();
		var onPath = new HashSet<string>();
		List<string> Visit( string id )
		{
			if ( onPath.Contains( id ) )
			{
				var cyc = path.Skip( path.IndexOf( id ) ).ToList();
				cyc.Add( id );
				return cyc;
			}
			if ( !_all.TryGetValue( id, out var e ) || e.Manifest is null || e.Status != AddonStatus.Active ) return null;
			onPath.Add( id );
			path.Add( id );
			foreach ( var d in e.Manifest.Dependencies.Keys )
				if ( Visit( d ) is { } c ) return c;
			path.RemoveAt( path.Count - 1 );
			onPath.Remove( id );
			return null;
		}
		return Visit( start );
	}

	public void LogSummary()
	{
		if ( _all.Count == 0 ) return;
		foreach ( var e in _all.Values )
		{
			if ( e.Status == AddonStatus.Active ) RpLog.Info( "addons", $"Addon {e.Id} {e.Manifest.Version} \"{e.Manifest.Title}\" active" );
			else if ( e.Status is AddonStatus.Invalid or AddonStatus.Blocked ) RpLog.Warn( "addons", $"Addon '{e.Id}' not loaded ({e.Status.ToString().ToLowerInvariant()}): {e.Reason}" );
			else RpLog.Info( "addons", $"Addon '{e.Id}' not loaded ({e.Status.ToString().ToLowerInvariant()}): {e.Reason}" );
		}
	}
}