diff --git a/docs/writing-plugins.md b/docs/writing-plugins.md index 18d32b64..3f1d300a 100644 --- a/docs/writing-plugins.md +++ b/docs/writing-plugins.md @@ -151,6 +151,10 @@ The following properties are recognized: Array of features the plugin needs from the instances it is loaded on, any of `"SavePatching"`, `"ScriptCommands"` and `"LuaUdp"`. See [Handling Invalid Configuration](#handling-invalid-configuration) +**requiredMods**: + Array of Factorio mods the plugin needs in the mod pack of the instances it is loaded on, written as Factorio dependency strings. + See [Handling Invalid Configuration](#handling-invalid-configuration) + **messages**: Array of request and event classes for this plugin. See guide for [defining link messages](#defining-link-messages) below. @@ -321,6 +325,25 @@ export const plugin = { Enabling the plugin on an instance that has the feature turned off then fails config validation, so the mistake is caught when the config is edited instead of when the instance starts. Instances that have the feature turned off get the plugin disabled by default when it is added. +If the plugin talks to a Factorio mod, list the mod under `requiredMods` using the same format as `dependencies` in a mod's info.json, without a prefix. +List a mod twice to give a version range: + +```js +export const plugin = { + name: "foo_frobber", + // ... + requiredMods: ["frobber >= 1.2.0", "frobber < 2.0.0"], +}; +``` + +An instance with the plugin loaded refuses to start if its mod pack is missing one of the mods, has it disabled, or has a version outside the range. +Leave out the dependencies of the required mods. Factorio checks those itself. +When the controller starts it downloads required mods it does not have, and their dependencies, from the mod portal for the Factorio version of the default mod pack. +This needs `controller.factorio_username` and `controller.factorio_token` to be set. +The mods still have to be added to the mod packs by hand. + +Forks of a required mod are not supported. + Other constraints on config fields are expressed with a `validator` on the field definition, which throws when the value is not acceptable. Use `dependsOn` when the check involves other fields so that the validator runs when those change too. See [Configuration System](config-system.md) for details. diff --git a/packages/controller/src/ControlConnection.ts b/packages/controller/src/ControlConnection.ts index 9f48aa53..052a2f4b 100644 --- a/packages/controller/src/ControlConnection.ts +++ b/packages/controller/src/ControlConnection.ts @@ -662,36 +662,7 @@ export default class ControlConnection extends BaseConnection { * @param request - Request object with mod name, version, and factorioVersion. */ async handleModPortalDownloadRequest(request: lib.ModPortalDownloadRequest) { - const factorioVersion = request.factorioVersion; - const toDownload = this._controller.modStore.filterInstalled(request.mods, false); - - if (toDownload.length > 0) { - // Get Factorio credentials from config - const username = this._controller.config.get("controller.factorio_username"); - const token = this._controller.config.get("controller.factorio_token"); - - if (!username || username === "" || !token || token === "") { - throw new lib.ConflictError("Factorio credentials (username, token) not configured on the controller."); - } - - try { - logger.info(`Downloading ${toDownload.length} mods for Factorio ${factorioVersion} from portal.`); - await this._controller.modStore.downloadMods(toDownload, username, token, factorioVersion); - - } catch (error: any) { - logger.error(`Error downloading mods from portal: ${error.message}`); - const errorMessage = "Mod portal download failed"; - if (error.message.includes("401") || error.message.includes("Unauthorized")) { - throw new lib.ConflictError( - `${errorMessage}: Authentication failed. Check Factorio username/token in controller config.` - ); - } - if (error.message.includes("404") || error.message.includes("Not Found")) { - throw new lib.NotFoundError(`${errorMessage}: Mod version not found on the portal.`); - } - throw new lib.InternalServerError(`${errorMessage}: ${error.message}`); - } - } + await this._controller.downloadModsFromPortal(request.mods, request.factorioVersion); // Verify all mods are present const modInfos = []; @@ -707,183 +678,9 @@ export default class ControlConnection extends BaseConnection { return modInfos; } - // eslint-disable-next-line complexity async handleModDependencyResolveRequest(request: lib.ModDependencyResolveRequest) { - const {factorioVersion, checkForUpdates} = request; - const searchQueue = [...request.mods]; - const localInfos = [...this._controller.modStore.mods()]; - - const builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion); - const skipSearch = new Set(builtInModNames); - - type ModPortalModType = InstanceType["mods"][number]; - type ModPortalReleaseType = NonNullable[number]; - const dependencyRequirements = new Map(); - const recommendedRequirements = new Map(); - const optionalRequirements = new Map(); - const candidateReleases = new Map(); - const errors = new Map(); - - const _modPortalReleases = new Map(); - async function fetchModReleases(modName: string) { - let releases = _modPortalReleases.get(modName); - if (releases === undefined) { - try { - releases = await lib.ModStore.fetchModReleases(modName); - } catch (error: any) { - if (!error.message.includes("404") && !error.message.includes("Not Found")) { - logger.error(`Error fetching mod from portal: ${error.message}`); - throw new lib.InternalServerError(`Dependency resolution failed: ${error.message}`); - } else { - releases = null; - } - } - } - _modPortalReleases.set(modName, releases); - return releases; - } - - function selectModRelease(releases: ModPortalModType | null, versionRange: lib.ModVersionRange) { - if (!releases || !releases.releases) { - return null; - } - - // Select the latest matching version for the mod pack's Factorio version - const release = releases.releases - .filter(info => ( - versionRange.testVersion(info.version) - && lib.normaliseMajorMinorVersion( - lib.normaliseSourceVersion(info.info_json.factorio_version) - ) === factorioVersion - )) - .reduce((max, cur) => ( - max && lib.integerSourceVersion(max.version) > lib.integerSourceVersion(cur.version) ? max : cur - ), undefined); - - if (!release) { - return null; - } - - // Create the mod info class from the selected - try { - return lib.ModInfo.fromJSON({ - ...release.info_json, // includes dependencies - sha1: release.sha1, - version: release.version, - name: releases.name, - author: releases.owner, - title: releases.title, - }); - } catch { - // Can error if there are invalid dependencies - errors.set(releases.name, "invalidDependency"); - return null; - } - } - - while (searchQueue.length > 0) { - // Dequeue the next mod, skip if incompatible - const mod = searchQueue.shift()!; - if (mod.incompatible) { - errors.set(mod.name, "incompatible"); - continue; - } - - // Get the current version range (dependencies can be promoted to a stricter requirement) - const versionRange = - dependencyRequirements.get(mod.name) - ?? recommendedRequirements.get(mod.name) - ?? optionalRequirements.get(mod.name) - ?? new lib.ModVersionRange(); - - if (mod.required) { - // Add to required, remove from recommended and optional - dependencyRequirements.set(mod.name, versionRange); - recommendedRequirements.delete(mod.name); - optionalRequirements.delete(mod.name); - - } else if (mod.recommended) { - // If not required, add to recommended and remove from optional - if (!dependencyRequirements.has(mod.name)) { - recommendedRequirements.set(mod.name, versionRange); - optionalRequirements.delete(mod.name); - } - - } else if ( - !dependencyRequirements.has(mod.name) - && !recommendedRequirements.has(mod.name) - ) { - // If not required or recommended, add to optional - optionalRequirements.set(mod.name, versionRange); - } - - // Update the version range if needed - if (mod.version) { - versionRange.combineVersion(mod.version); - if (!versionRange.valid) { - candidateReleases.delete(mod.name); - errors.set(mod.name, "unsatisfiable"); - continue; - } - } - - // Do not add dependencies for errors, skips, optionals, or valid candidates - const existingCandidate = candidateReleases.get(mod.name); - if (errors.has(mod.name) || skipSearch.has(mod.name) || optionalRequirements.has(mod.name) || ( - existingCandidate && versionRange.testVersion(existingCandidate.version) - )) { - continue; - } - - // Check if a local version fits the requirements - let candidate = localInfos - .filter(info => ( - info.name === mod.name - && info.factorioVersion === factorioVersion - && versionRange.testVersion(info.version) - )) - .reduce((max, cur) => ( - max && max.integerVersion > cur.integerVersion ? max : cur - ), undefined); - - // Check if a mod poral version fits the requirements - if (!candidate || checkForUpdates) { - const releases = await fetchModReleases(mod.name); - const release = selectModRelease(releases, versionRange); - // We only select the mod portal release if it is more recent than the local candidate - if (release && (!candidate || release.integerVersion > candidate.integerVersion)) { - candidate = release; - } - } - - // Queue the dependencies of the new candidate - if (candidate) { - candidateReleases.set(mod.name, candidate); - for (const dep of candidate.dependencies) { - searchQueue.push(dep); - } - } else { - candidateReleases.delete(mod.name); - skipSearch.add(mod.name); - } - } - - // Add the not found dependencies as errors - for (const modName of dependencyRequirements.keys()) { - if (!candidateReleases.has(modName) && !errors.has(modName)) { - errors.set(modName, "notFound"); - } - } - - // Remove incompatible and unsatisfiable dependencies if they aren't required by others - for (const [modName, error] of errors) { - if (!dependencyRequirements.has(modName) && (error === "incompatible" || error === "unsatisfiable")) { - errors.delete(modName); - } - } - - return new lib.ModDependencyResolveRequest.Response( - [...candidateReleases.values()], errors, + return await this._controller.resolveModDependencies( + request.mods, request.factorioVersion, request.checkForUpdates, ); } diff --git a/packages/controller/src/Controller.ts b/packages/controller/src/Controller.ts index da5f2369..11618c0d 100644 --- a/packages/controller/src/Controller.ts +++ b/packages/controller/src/Controller.ts @@ -512,6 +512,9 @@ export default class Controller { logger.info("Started controller"); this.startedAtMs = Date.now(); + this.downloadRequiredMods().catch( + err => logger.warn(`Unable to download mods required by plugins: ${err.message}`) + ); this.onAutosaveIntervalChanged(); this.onSystemMetricsIntervalChanged(); this._state = "running"; @@ -1169,6 +1172,265 @@ export default class Controller { } + /** + * Download mods from the Factorio mod portal to the mod store + * + * Mods already in the mod store are skipped. + * + * @throws {lib.ConflictError} if the Factorio credentials are not configured. + */ + async downloadModsFromPortal(mods: lib.ModNameVersionPair[], factorioVersion: lib.MajorMinorVersion) { + const toDownload = this.modStore.filterInstalled(mods, false); + + if (toDownload.length > 0) { + // Get Factorio credentials from config + const username = this.config.get("controller.factorio_username"); + const token = this.config.get("controller.factorio_token"); + + if (!username || username === "" || !token || token === "") { + throw new lib.ConflictError("Factorio credentials (username, token) not configured on the controller."); + } + + try { + logger.info(`Downloading ${toDownload.length} mods for Factorio ${factorioVersion} from portal.`); + await this.modStore.downloadMods(toDownload, username, token, factorioVersion); + + } catch (error: any) { + logger.error(`Error downloading mods from portal: ${error.message}`); + const errorMessage = "Mod portal download failed"; + if (error.message.includes("401") || error.message.includes("Unauthorized")) { + throw new lib.ConflictError( + `${errorMessage}: Authentication failed. Check Factorio username/token in controller config.` + ); + } + if (error.message.includes("404") || error.message.includes("Not Found")) { + throw new lib.NotFoundError(`${errorMessage}: Mod version not found on the portal.`); + } + throw new lib.InternalServerError(`${errorMessage}: ${error.message}`); + } + } + } + + /** + * Resolve mods and their dependencies against the mod store and the Factorio mod portal + */ + // eslint-disable-next-line complexity + async resolveModDependencies( + mods: lib.ModDependency[], + factorioVersion: lib.MajorMinorVersion, + checkForUpdates = false, + ) { + const searchQueue = [...mods]; + const localInfos = [...this.modStore.mods()]; + + const builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion); + const skipSearch = new Set(builtInModNames); + + type ModPortalModType = InstanceType["mods"][number]; + type ModPortalReleaseType = NonNullable[number]; + const dependencyRequirements = new Map(); + const recommendedRequirements = new Map(); + const optionalRequirements = new Map(); + const candidateReleases = new Map(); + const errors = new Map(); + + const _modPortalReleases = new Map(); + async function fetchModReleases(modName: string) { + let releases = _modPortalReleases.get(modName); + if (releases === undefined) { + try { + releases = await lib.ModStore.fetchModReleases(modName); + } catch (error: any) { + if (!error.message.includes("404") && !error.message.includes("Not Found")) { + logger.error(`Error fetching mod from portal: ${error.message}`); + throw new lib.InternalServerError(`Dependency resolution failed: ${error.message}`); + } else { + releases = null; + } + } + } + _modPortalReleases.set(modName, releases); + return releases; + } + + function selectModRelease(releases: ModPortalModType | null, versionRange: lib.ModVersionRange) { + if (!releases || !releases.releases) { + return null; + } + + // Select the latest matching version for the mod pack's Factorio version + const release = releases.releases + .filter(info => ( + versionRange.testVersion(info.version) + && lib.normaliseMajorMinorVersion( + lib.normaliseSourceVersion(info.info_json.factorio_version) + ) === factorioVersion + )) + .reduce((max, cur) => ( + max && lib.integerSourceVersion(max.version) > lib.integerSourceVersion(cur.version) ? max : cur + ), undefined); + + if (!release) { + return null; + } + + // Create the mod info class from the selected + try { + return lib.ModInfo.fromJSON({ + ...release.info_json, // includes dependencies + sha1: release.sha1, + version: release.version, + name: releases.name, + author: releases.owner, + title: releases.title, + }); + } catch { + // Can error if there are invalid dependencies + errors.set(releases.name, "invalidDependency"); + return null; + } + } + + while (searchQueue.length > 0) { + // Dequeue the next mod, skip if incompatible + const mod = searchQueue.shift()!; + if (mod.incompatible) { + errors.set(mod.name, "incompatible"); + continue; + } + + // Get the current version range (dependencies can be promoted to a stricter requirement) + const versionRange = + dependencyRequirements.get(mod.name) + ?? recommendedRequirements.get(mod.name) + ?? optionalRequirements.get(mod.name) + ?? new lib.ModVersionRange(); + + if (mod.required) { + // Add to required, remove from recommended and optional + dependencyRequirements.set(mod.name, versionRange); + recommendedRequirements.delete(mod.name); + optionalRequirements.delete(mod.name); + + } else if (mod.recommended) { + // If not required, add to recommended and remove from optional + if (!dependencyRequirements.has(mod.name)) { + recommendedRequirements.set(mod.name, versionRange); + optionalRequirements.delete(mod.name); + } + + } else if ( + !dependencyRequirements.has(mod.name) + && !recommendedRequirements.has(mod.name) + ) { + // If not required or recommended, add to optional + optionalRequirements.set(mod.name, versionRange); + } + + // Update the version range if needed + if (mod.version) { + versionRange.combineVersion(mod.version); + if (!versionRange.valid) { + candidateReleases.delete(mod.name); + errors.set(mod.name, "unsatisfiable"); + continue; + } + } + + // Do not add dependencies for errors, skips, optionals, or valid candidates + const existingCandidate = candidateReleases.get(mod.name); + if (errors.has(mod.name) || skipSearch.has(mod.name) || optionalRequirements.has(mod.name) || ( + existingCandidate && versionRange.testVersion(existingCandidate.version) + )) { + continue; + } + + // Check if a local version fits the requirements + let candidate = localInfos + .filter(info => ( + info.name === mod.name + && info.factorioVersion === factorioVersion + && versionRange.testVersion(info.version) + )) + .reduce((max, cur) => ( + max && max.integerVersion > cur.integerVersion ? max : cur + ), undefined); + + // Check if a mod poral version fits the requirements + if (!candidate || checkForUpdates) { + const releases = await fetchModReleases(mod.name); + const release = selectModRelease(releases, versionRange); + // We only select the mod portal release if it is more recent than the local candidate + if (release && (!candidate || release.integerVersion > candidate.integerVersion)) { + candidate = release; + } + } + + // Queue the dependencies of the new candidate + if (candidate) { + candidateReleases.set(mod.name, candidate); + for (const dep of candidate.dependencies) { + searchQueue.push(dep); + } + } else { + candidateReleases.delete(mod.name); + skipSearch.add(mod.name); + } + } + + // Add the not found dependencies as errors + for (const modName of dependencyRequirements.keys()) { + if (!candidateReleases.has(modName) && !errors.has(modName)) { + errors.set(modName, "notFound"); + } + } + + // Remove incompatible and unsatisfiable dependencies if they aren't required by others + for (const [modName, error] of errors) { + if (!dependencyRequirements.has(modName) && (error === "incompatible" || error === "unsatisfiable")) { + errors.delete(modName); + } + } + + return new lib.ModDependencyResolveRequest.Response( + [...candidateReleases.values()], errors, + ); + } + + /** + * Download the mods required by plugins that are missing from the mod store + * + * Resolves for the Factorio version of the default mod pack. Dependencies + * of the required mods are downloaded too. + */ + async downloadRequiredMods() { + const required = this.pluginInfos.flatMap(pluginInfo => lib.pluginRequiredMods(pluginInfo)); + const modPackId = this.config.get("controller.default_mod_pack_id"); + const modPack = modPackId !== null ? this.modPacks.get(modPackId) : undefined; + if (!required.length || !modPack) { + return; + } + + const factorioVersion = lib.normaliseMajorMinorVersion(modPack.factorioVersion); + const { dependencies, errors } = await this.resolveModDependencies(required, factorioVersion); + const builtInMods = new Set(lib.ModPack.getBuiltinModNames(factorioVersion)); + for (const [name, error] of errors) { + if (!builtInMods.has(name)) { + logger.warn(`Unable to resolve mod ${name} required by plugins: ${error}`); + } + } + const toDownload = this.modStore.filterInstalled(dependencies.map( + info => ({ name: info.name, version: new lib.ModVersionEquality("=", info.normalisedVersion) }) + ), false); + if (!toDownload.length) { + return; + } + + const names = toDownload.map(mod => `${mod.name} ${mod.version.version}`).join(", "); + logger.info(`Downloading mods required by plugins: ${names}`); + await this.downloadModsFromPortal(toDownload, factorioVersion); + } + modPacksUpdated(modPacks: lib.ModPack[]) { this.subscriptions.broadcast(new lib.ModPackUpdatesEvent(modPacks)); this.hooks.modPacksUpdated.invoke(modPacks); diff --git a/packages/host/src/Instance.ts b/packages/host/src/Instance.ts index d6cfe046..2048cdf8 100644 --- a/packages/host/src/Instance.ts +++ b/packages/host/src/Instance.ts @@ -1032,6 +1032,39 @@ end`.replace(/\r?\n/g, " "); } await this.syncMods(); + this.checkRequiredMods(this.activeModPack); + } + + /** + * Check that the mod pack has the mods required by the loaded plugins + * + * @throws {lib.ConflictError} if a required mod is missing, disabled or the wrong version. + */ + checkRequiredMods(modPack: lib.ModPack) { + const problems = []; + for (const pluginInfo of this.loadedPlugins) { + const unmet = []; + for (const dependency of lib.pluginRequiredMods(pluginInfo)) { + const mod = modPack.mods.get(dependency.name); + if (!mod) { + unmet.push(`${dependency.spec} (missing)`); + } else if (!mod.enabled) { + unmet.push(`${dependency.spec} (disabled)`); + } else if (dependency.version && !dependency.version.testVersion(mod.version)) { + unmet.push(`${dependency.spec} (found ${mod.version})`); + } + } + if (unmet.length) { + problems.push(`Plugin ${pluginInfo.name} requires ${unmet.join(", ")}.`); + } + } + if (problems.length) { + throw new lib.ConflictError( + `Mod pack ${modPack.name} does not have the mods required by the loaded plugins. ` + + `${problems.join(" ")} ` + + "Add the mods to the mod pack or set .load_plugin to false for this instance." + ); + } } /** diff --git a/packages/lib/src/plugin.ts b/packages/lib/src/plugin.ts index f98e0d4a..8e5b23db 100644 --- a/packages/lib/src/plugin.ts +++ b/packages/lib/src/plugin.ts @@ -9,6 +9,7 @@ import type { PermissionDefinition } from "./permissions.js"; import type { PlayerStats, Role } from "./data/index.js"; import type { SyncHook } from "./SyncHook.js"; import type { ErrorClass } from "./link/index.js"; +import { ModDependency } from "./data/ModInfo.js"; export const PluginFeatureFlags = [ /** The plugin requires module code to be patched into the save */ @@ -41,6 +42,11 @@ export type PluginDeclaration = { migrationEntrypoint?: string; features?: (typeof PluginFeatureFlags)[number][]; + /** + * Factorio mods the plugin needs in the instance's mod pack, as Factorio + * dependency strings like `"subspace_storage >= 2.3.0"`. + */ + requiredMods?: string[]; messages?: any[]; errors?: ErrorClass[]; @@ -65,6 +71,23 @@ export function pluginNeedsWebBuild(info: PluginDeclaration) { ); } +/** + * Parse the requiredMods of a plugin + * + * A mod listed more than once must satisfy every entry, which gives a range. + * + * @throws Error if an entry is invalid or has a dependency prefix. + */ +export function pluginRequiredMods(pluginInfo: PluginDeclaration) { + return (pluginInfo.requiredMods ?? []).map(spec => { + const dependency = new ModDependency(spec); + if (dependency.type !== "required") { + throw new Error(`requiredMods entry "${spec}" can not have a dependency prefix`); + } + return dependency; + }); +} + export type PluginNodeEnvInfo = PluginDeclaration & { /** * Path to the folder with the static files that should be hosted on the web diff --git a/packages/lib/src/plugin_loader.ts b/packages/lib/src/plugin_loader.ts index 1aec0eee..1832d36a 100644 --- a/packages/lib/src/plugin_loader.ts +++ b/packages/lib/src/plugin_loader.ts @@ -84,6 +84,12 @@ export async function loadPluginInfos(pluginList: Map, skippedNp ); } + try { + libPlugin.pluginRequiredMods(pluginInfo); + } catch (err: any) { + throw new libErrors.PluginError(pluginName, err); + } + // migrate: ignore incompatible old plugins if (pluginInfo.messages && !(pluginInfo.messages instanceof Array)) { logger.warn(`Ignoring incompatible pre alpha.14 plugin ${pluginName}`); diff --git a/plugins/subspace_storage/README.md b/plugins/subspace_storage/README.md index 9a4744ec..2cfb2739 100644 --- a/plugins/subspace_storage/README.md +++ b/plugins/subspace_storage/README.md @@ -12,6 +12,10 @@ Run the following commands in the folder Clusterio is installed to: Substitute clusteriocontroller with clusteriohost or clusterioctl if this a dedicate host or ctl installation respectively. +The plugin needs the [Subspace Storage mod](https://mods.factorio.com/mod/subspace_storage) in the mod pack of every instance it is loaded on. +The controller downloads it from the mod portal on start if the Factorio credentials are configured, but you have to add it to the mod packs yourself. +Instances with the plugin loaded refuse to start without it. Set `subspace_storage.load_plugin` to false on instances that should not use it. + ## Controller Configuration diff --git a/plugins/subspace_storage/index.ts b/plugins/subspace_storage/index.ts index 295268cd..b4a9b58e 100644 --- a/plugins/subspace_storage/index.ts +++ b/plugins/subspace_storage/index.ts @@ -19,6 +19,7 @@ export const plugin: lib.PluginDeclaration = { title: "Subspace Storage", description: "Provides shared storage across instances for the Subspace Storage mod", instanceEntrypoint: "dist/node/instance.js", + requiredMods: ["subspace_storage >= 1.99.0"], instanceConfigFields: { "subspace_storage.log_item_transfers": { title: "Log Item Transfers", diff --git a/test/controller/Controller.js b/test/controller/Controller.js index 1eaa26d9..d63d0605 100644 --- a/test/controller/Controller.js +++ b/test/controller/Controller.js @@ -305,6 +305,50 @@ describe("controller/src/Controller", function() { await assert.rejects(Controller.loadJsonObject(path.join(dir, "invalid.json")), SyntaxError); }); }); + describe(".downloadRequiredMods()", function() { + let ctrl, resolveCalls, downloadCalls, resolved; + function modInfo(name, version) { + return lib.ModInfo.fromJSON({ name, version, factorio_version: "2.0" }); + } + beforeEach(function() { + const config = new ControllerConfig("controller", { "controller.version": controllerVersion }); + ctrl = new Controller({}, [ + { name: "foo", title: "Foo", requiredMods: ["foo_mod >= 1.0.0"] }, + { name: "bar", title: "Bar" }, + ], config); + const modPack = ModPack.fromJSON({ id: 7, name: "default", factorio_version: "2.0.10" }); + ctrl.modPacks.set(modPack); + config.set("controller.default_mod_pack_id", 7); + resolveCalls = []; + downloadCalls = []; + resolved = [modInfo("foo_mod", "1.2.0"), modInfo("dep_mod", "0.1.0")]; + ctrl.resolveModDependencies = async (mods, factorioVersion) => { + resolveCalls.push([mods.map(mod => mod.spec), factorioVersion]); + return new lib.ModDependencyResolveRequest.Response(resolved, new Map()); + }; + ctrl.downloadModsFromPortal = async (mods, factorioVersion) => { + downloadCalls.push([mods.map(mod => `${mod.name} ${mod.version}`), factorioVersion]); + }; + }); + + it("should download required mods and their dependencies for the default mod pack", async function() { + await ctrl.downloadRequiredMods(); + assert.deepEqual(resolveCalls, [[["foo_mod >= 1.0.0"], "2.0"]]); + assert.deepEqual(downloadCalls, [[["foo_mod = 1.2.0", "dep_mod = 0.1.0"], "2.0"]]); + }); + + it("should skip mods already in the mod store", async function() { + ctrl.modStore = new lib.ModStore("mods", new Map(resolved.map(info => [info.filename, info]))); + await ctrl.downloadRequiredMods(); + assert.deepEqual(downloadCalls, []); + }); + + it("should do nothing when no plugin requires mods", async function() { + ctrl.pluginInfos = [{ name: "bar", title: "Bar" }]; + await ctrl.downloadRequiredMods(); + assert.deepEqual(resolveCalls, []); + }); + }); describe(".loggableHeaders()", function() { it("should redact credentials and keep other headers", function() { const headers = { diff --git a/test/host/Instance.js b/test/host/Instance.js index 80cca616..2d6893ed 100644 --- a/test/host/Instance.js +++ b/test/host/Instance.js @@ -336,6 +336,49 @@ describe("class Instance", function() { }); }); + describe(".checkRequiredMods()", function() { + beforeEach(function() { + instance.loadedPlugins = new Set([ + { name: "foo", requiredMods: ["foo_mod", "bar_mod >= 1.1.0", "bar_mod < 2.0.0"] }, + { name: "bar" }, + ]); + }); + function modPack(mods) { + return lib.ModPack.fromJSON({ name: "pack", mods }); + } + + it("should accept a mod pack with the required mods", function() { + instance.checkRequiredMods(modPack([ + { name: "foo_mod", enabled: true, version: "1.0.0" }, + { name: "bar_mod", enabled: true, version: "1.1.0" }, + ])); + }); + + it("should reject missing, disabled and out of range mods", function() { + const expected = (unmet) => new lib.ConflictError( + "Mod pack pack does not have the mods required by the loaded plugins. " + + `Plugin foo requires ${unmet}. ` + + "Add the mods to the mod pack or set .load_plugin to false for this instance." + ); + assert.throws( + () => instance.checkRequiredMods(modPack([{ name: "bar_mod", enabled: true, version: "1.0.0" }])), + expected("foo_mod (missing), bar_mod >= 1.1.0 (found 1.0.0)"), + ); + assert.throws( + () => instance.checkRequiredMods(modPack([ + { name: "foo_mod", enabled: false, version: "1.0.0" }, + { name: "bar_mod", enabled: true, version: "2.0.0" }, + ])), + expected("foo_mod (disabled), bar_mod < 2.0.0 (found 2.0.0)"), + ); + }); + + it("should ignore plugins that are not loaded", function() { + instance.loadedPlugins = new Set([{ name: "bar" }]); + instance.checkRequiredMods(modPack([])); + }); + }); + describe("save name checks", function() { it("should reject a start save outside the saves directory", async function() { await assert.rejects( diff --git a/test/integration/index.js b/test/integration/index.js index 09407e23..2f3fbadd 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -353,6 +353,22 @@ before(async function() { sourceDir: "packages/host/lua/clusterio_lib", outputDir: modsDir, }); + // Stand-in for the mod required by the subspace_storage plugin + const subspaceStorageDir = path.join("temp", "test", "subspace_storage"); + await fs.rm(subspaceStorageDir, { force: true, recursive: true }); + await fs.mkdir(subspaceStorageDir, { recursive: true }); + await fs.writeFile(path.join(subspaceStorageDir, "info.json"), JSON.stringify({ + name: "subspace_storage", + variants: [ + { version: "2.3.11", factorio_version: "1.1" }, + { version: "2.3.20", factorio_version: "2.0" }, + { version: "2.3.21", factorio_version: "2.1" }, + ], + title: "Subspace Storage test stub", + author: "Clusterio Team", + dependencies: ["base", "clusterio_lib"], + })); + await lib.build({ build: true, pack: true, sourceDir: subspaceStorageDir, outputDir: modsDir }); console.log("Setting Controller Config"); await execController("config create"); @@ -410,6 +426,9 @@ before(async function() { const [major, minor] = lib.normaliseMajorMinorVersion(latestFactorioVersion).split("."); testPack.mods.set("clusterio_lib", { name: "clusterio_lib", enabled: true, version: `2.1.${major}${minor}` }); + testPack.mods.set( + "subspace_storage", { name: "subspace_storage", enabled: true, version: `2.3.${major}${minor}` } + ); await control.sendTo("controller", new lib.ModPackCreateRequest(testPack)); await control.sendTo( diff --git a/test/lib/plugin.js b/test/lib/plugin.js index dd5ef087..babe2557 100644 --- a/test/lib/plugin.js +++ b/test/lib/plugin.js @@ -24,4 +24,22 @@ describe("lib/plugin", function() { } }); }); + describe("pluginRequiredMods()", function() { + it("should parse dependency strings", function() { + const mods = lib.pluginRequiredMods({ + name: "foo", title: "Foo", requiredMods: ["bar", "baz >= 1.2.0", "baz < 2.0.0"], + }); + assert.deepEqual(mods.map(mod => [mod.name, mod.version?.toString()]), [ + ["bar", undefined], ["baz", ">= 1.2.0"], ["baz", "< 2.0.0"], + ]); + }); + it("should return an empty list without requiredMods", function() { + assert.deepEqual(lib.pluginRequiredMods({ name: "foo", title: "Foo" }), []); + }); + it("should reject dependency prefixes and invalid versions", function() { + for (const spec of ["? bar", "! bar", "~ bar", "bar >= 1..2"]) { + assert.throws(() => lib.pluginRequiredMods({ name: "foo", title: "Foo", requiredMods: [spec] })); + } + }); + }); });