mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-18 06:43:13 +09:00
Fix stale values, the unsynced page, and three smaller review finds
- The page waited for nothing, so before the subscription delivered the records every feature looked enabled with its defaults, and an Apply in that window would have written that state. It now shows a spinner until synced, like the role page. - Values stored for a setting which was since renamed, removed, or changed type made every later save of that feature fail validation. The controller now reconciles the stored records with features.ts on start: stale values are dropped with a warning, records of removed features are deleted, and new features get their defaults. - update_config no longer stores overrides for unknown paths, so a stale key is warned about once instead of on every load. - The armor and gun inventory handlers of nuke protection are new to this branch and asserted on get_inventory, which is nil without a character. They return instead. - The AFK check ran every 30 minutes while afk_minutes and kick_minutes can be set as low as 1. It runs every minute. - sameValue lives in features.ts and isDefaultValue uses it, and the custom input branch of FieldInput is a single narrowed check. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
f8ca285ff6
commit
bff6a1c612
9 files changed
+124
-42
No files matched your search
@@ -6,7 +6,7 @@ import { GroupRecord, GroupPermissions, RoleMappingRecord } from "@expcluster/pe
|
||||
import { ControllerPlugin as RolesPlugin } from "@expcluster/roles/dist/node/controller.js";
|
||||
import { ControllerPlugin as GroupsPlugin } from "@expcluster/permission-groups/dist/node/controller.js";
|
||||
import * as messages from "./messages.js";
|
||||
import { features, validateFeatureValues } from "./features.js";
|
||||
import { features, pruneFeatureValues, validateFeatureValues } from "./features.js";
|
||||
import { SeedRole, SeedGroup, seedRoles, seedGroups, flattenSeedPermissions } from "./seed.js";
|
||||
|
||||
export class ControllerPlugin {
|
||||
@@ -30,11 +30,7 @@ export class ControllerPlugin {
|
||||
).bootstrap()
|
||||
);
|
||||
|
||||
// Features added since the last start begin with their defaults
|
||||
const missing = features.filter(feature => !this.features.has(feature.name));
|
||||
if (missing.length) {
|
||||
this.features.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true)));
|
||||
}
|
||||
this.reconcileFeatures();
|
||||
|
||||
this.controller.subscriptions.handle(messages.FeatureUpdatedEvent, this.handleFeatureSubscription.bind(this));
|
||||
this.features.on("update", this.featuresUpdated.bind(this));
|
||||
@@ -50,6 +46,36 @@ export class ControllerPlugin {
|
||||
await this.features.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the stored records in line with the features declared in features.ts.
|
||||
*
|
||||
* New features begin with their defaults, records of removed features are
|
||||
* deleted, and values which no longer match a field are dropped so the
|
||||
* feature can still be saved from the web interface.
|
||||
*/
|
||||
reconcileFeatures() {
|
||||
const declared = new Map(features.map(feature => [feature.name, feature]));
|
||||
for (const record of [...this.features.values()]) {
|
||||
const feature = declared.get(record.id);
|
||||
if (!feature) {
|
||||
this.logger.warn(`Dropping stored config of removed feature ${record.id}`);
|
||||
this.features.delete(record);
|
||||
continue;
|
||||
}
|
||||
|
||||
const { kept, dropped } = pruneFeatureValues(feature, record.values);
|
||||
if (dropped.length) {
|
||||
this.logger.warn(`Dropping stored values of ${record.id} which no longer match a setting: ${dropped.join(", ")}`);
|
||||
this.features.set(new messages.FeatureRecord(record.id, record.enabled, kept));
|
||||
}
|
||||
}
|
||||
|
||||
const missing = features.filter(feature => !this.features.has(feature.name));
|
||||
if (missing.length) {
|
||||
this.features.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true)));
|
||||
}
|
||||
}
|
||||
|
||||
featuresUpdated(updates: messages.FeatureRecord[]) {
|
||||
this.controller.subscriptions.broadcast(new messages.FeatureUpdatedEvent(updates));
|
||||
}
|
||||
|
||||
@@ -276,10 +276,38 @@ function checkFieldValue(field: FeatureField, value: FeatureValue, label: string
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if a value equals the default of its field, lists are compared by content. */
|
||||
export function isDefaultValue(field: FeatureField, value: FeatureValue) {
|
||||
if (Array.isArray(value) && Array.isArray(field.default)) {
|
||||
return value.length === field.default.length && value.every((item, index) => item === (field.default as string[])[index]);
|
||||
/** Check if two values are equal, lists are compared by content. */
|
||||
export function sameValue(a: FeatureValue | undefined, b: FeatureValue | undefined) {
|
||||
if (Array.isArray(a) && Array.isArray(b)) {
|
||||
return a.length === b.length && a.every((item, index) => item === b[index]);
|
||||
}
|
||||
return value === field.default;
|
||||
return a === b;
|
||||
}
|
||||
|
||||
export function isDefaultValue(field: FeatureField, value: FeatureValue) {
|
||||
return sameValue(value, field.default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop stored values which no longer match the fields of a feature, after a
|
||||
* setting was renamed, removed, or changed type.
|
||||
*
|
||||
* @returns the values which are still valid, and the names of those dropped
|
||||
*/
|
||||
export function pruneFeatureValues(feature: Feature, values: Record<string, FeatureValue>) {
|
||||
const kept: Record<string, FeatureValue> = {};
|
||||
const dropped: string[] = [];
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
const field = feature.fields.find(f => f.name === key);
|
||||
try {
|
||||
if (!field) {
|
||||
throw new Error("removed");
|
||||
}
|
||||
checkFieldValue(field, value, key);
|
||||
kept[key] = value;
|
||||
} catch {
|
||||
dropped.push(key);
|
||||
}
|
||||
}
|
||||
return { kept, dropped };
|
||||
}
|
||||
@@ -98,7 +98,7 @@ return feature:guard{
|
||||
[e.on_player_joined_game] = on_player_joined_game,
|
||||
},
|
||||
on_nth_tick = {
|
||||
[60 * 60 * 30] = check_afk_players,
|
||||
[60 * 60] = check_afk_players,
|
||||
},
|
||||
has_active_player = has_active_player,
|
||||
}
|
||||
@@ -30,7 +30,8 @@ local function check_items(player, type)
|
||||
|
||||
local banned_items = config.banned_items
|
||||
local items = {} --- @type LuaItemStack[]
|
||||
local inventory = assert(player.get_inventory(type))
|
||||
local inventory = player.get_inventory(type)
|
||||
if not inventory then return end
|
||||
-- Check what items the player has
|
||||
for i = 1, #inventory do
|
||||
local item = inventory[i --[[@as uint]]]
|
||||
|
||||
@@ -263,8 +263,9 @@ function Feature:update_config(enabled, values)
|
||||
for path, value in pairs(values) do
|
||||
if self.fields[path] == nil then
|
||||
log("[WARNING] Unknown override for " .. self.name .. "." .. path)
|
||||
else
|
||||
overrides[path] = value
|
||||
end
|
||||
overrides[path] = value
|
||||
end
|
||||
|
||||
local old_values = {}
|
||||
|
||||
@@ -143,6 +143,20 @@ t.test("class ControllerPlugin", t2 => {
|
||||
t3.ok(records.every(record => record.enabled && !Object.keys(record.values).length), "enabled with no overrides");
|
||||
});
|
||||
|
||||
t2.test(".reconcileFeatures() drops stored values and features which no longer exist", async t3 => {
|
||||
const databaseDirectory = t3.testdir();
|
||||
const { plugin } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
|
||||
plugin.features.set(new messages.FeatureRecord("afk_kick", false, { afk_minutes: 5, trust_time: 600 }));
|
||||
plugin.features.set(new messages.FeatureRecord("gone", true, {}));
|
||||
await plugin.onShutdown();
|
||||
|
||||
const { plugin: restarted } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
|
||||
const record = restarted.features.get("afk_kick");
|
||||
t3.strictSame([record.enabled, record.values], [false, { afk_minutes: 5 }], "the stale value is dropped, the rest kept");
|
||||
t3.notOk(restarted.features.has("gone"), "the removed feature is deleted");
|
||||
t3.ok(features.every(feature => restarted.features.has(feature.name)), "every declared feature still has a record");
|
||||
});
|
||||
|
||||
t2.test(".handleFeatureUpdateRequest() stores the values which differ from the default", async t3 => {
|
||||
const { plugin } = await startPlugin(t3, { withPlugins: false });
|
||||
const broadcasts = [];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import t from "tap";
|
||||
import { features, validateFeatureValues } from "../dist/node/features.js";
|
||||
import { features, pruneFeatureValues, validateFeatureValues } from "../dist/node/features.js";
|
||||
|
||||
/** Every lua file in the module, by path relative to it. */
|
||||
function luaFiles(dir, prefix = "") {
|
||||
@@ -105,3 +105,13 @@ t.test("validateFeatureValues()", t2 => {
|
||||
t2.same(validateFeatureValues("spawn_area", { "turrets.enabled": false }), { "turrets.enabled": false }, "nested settings");
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("pruneFeatureValues()", t2 => {
|
||||
const afkKick = features.find(feature => feature.name === "afk_kick");
|
||||
t2.same(
|
||||
pruneFeatureValues(afkKick, { afk_minutes: 5, trust_time: 600, kick_minutes: "soon", active_role_id: null }),
|
||||
{ kept: { afk_minutes: 5, active_role_id: null }, dropped: ["trust_time", "kick_minutes"] },
|
||||
"removed settings and wrong types are dropped, valid values and optional nulls stay",
|
||||
);
|
||||
t2.end();
|
||||
});
|
||||
@@ -53,6 +53,7 @@ Suite.test("update_config() ignores and logs values which can not be overridden"
|
||||
feature:update_config(true, { flag = "yes", check = false, icon = "x" })
|
||||
Suite.eq(feature.config, { enabled = true, flag = true, check = check }, "wrong types, functions, and unknown keys are skipped")
|
||||
Suite.eq(#env.logged, 3, "each one is logged")
|
||||
Suite.eq(env.storage.test, { enabled = true, flag = "yes", check = false }, "unknown keys are not stored")
|
||||
end)
|
||||
|
||||
Suite.test("receive_update() updates known features", function(env)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { Button, Checkbox, Col, ConfigProvider, Divider, Input, InputNumber, Row, Select, Space, Switch } from "antd";
|
||||
import { Button, Checkbox, Col, ConfigProvider, Divider, Input, InputNumber, Row, Select, Space, Spin, Switch } from "antd";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { ControlContext, PageHeader, PageLayout, notifyErrorHandler, useAccount } from "@clusterio/web_ui";
|
||||
|
||||
import { Feature, FeatureField, FeatureValue, features, isDefaultValue } from "../../features.js";
|
||||
import { Feature, FeatureField, FeatureValue, features, isDefaultValue, sameValue } from "../../features.js";
|
||||
import { FeatureRecord, FeatureUpdateRequest } from "../../messages.js";
|
||||
import { useFeatures } from "../index";
|
||||
|
||||
@@ -15,13 +15,6 @@ type PendingChanges = Record<string, { enabled?: boolean, values: Record<string,
|
||||
const borderColor = "#424242";
|
||||
const modifiedColor = "#2a1912";
|
||||
|
||||
function sameValue(a: FeatureValue | undefined, b: FeatureValue | undefined) {
|
||||
if (Array.isArray(a) && Array.isArray(b)) {
|
||||
return a.length === b.length && a.every((item, index) => item === b[index]);
|
||||
}
|
||||
return a === b;
|
||||
}
|
||||
|
||||
/** The stored state of a feature, with defaults for values which were not set. */
|
||||
function storedState(feature: Feature, record: FeatureRecord | undefined): FeatureState {
|
||||
return {
|
||||
@@ -78,23 +71,23 @@ function searchFields(feature: Feature, query: string) {
|
||||
function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void }) {
|
||||
const { field, value, disabled, onChange } = props;
|
||||
const control = useContext(ControlContext);
|
||||
const CustomInput = field.type !== "string_list" && field.inputComponent
|
||||
? control.inputComponents.get(field.inputComponent)
|
||||
: undefined;
|
||||
if (CustomInput && field.type !== "string_list") {
|
||||
const fieldDefinition: lib.FieldDefinition = {
|
||||
type: field.type,
|
||||
title: field.title,
|
||||
description: field.description,
|
||||
optional: field.optional,
|
||||
inputComponent: field.inputComponent,
|
||||
};
|
||||
return <CustomInput
|
||||
fieldDefinition={fieldDefinition}
|
||||
value={value as Exclude<FeatureValue, string[]>}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
/>;
|
||||
if (field.type !== "string_list" && field.inputComponent) {
|
||||
const CustomInput = control.inputComponents.get(field.inputComponent);
|
||||
if (CustomInput) {
|
||||
const fieldDefinition: lib.FieldDefinition = {
|
||||
type: field.type,
|
||||
title: field.title,
|
||||
description: field.description,
|
||||
optional: field.optional,
|
||||
inputComponent: field.inputComponent,
|
||||
};
|
||||
return <CustomInput
|
||||
fieldDefinition={fieldDefinition}
|
||||
value={value as Exclude<FeatureValue, string[]>}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
/>;
|
||||
}
|
||||
}
|
||||
|
||||
switch (field.type) {
|
||||
@@ -228,11 +221,19 @@ function FeatureNav(props: { feature: Feature, enabled: boolean }) {
|
||||
export default function FeaturesPage() {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const [records] = useFeatures();
|
||||
const [records, synced] = useFeatures();
|
||||
const [pending, setPending] = useState<PendingChanges>({});
|
||||
const [search, setSearch] = useState("");
|
||||
const canEdit = Boolean(account.hasPermission("exp_scenario.config.edit"));
|
||||
|
||||
// Until the subscription delivers the records every feature would look enabled with its defaults
|
||||
if (!synced) {
|
||||
return <PageLayout nav={[{ name: "Scenario Features" }]}>
|
||||
<PageHeader title="Scenario Features" />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
const stored = Object.fromEntries(features.map(feature => [feature.name, storedState(feature, records.get(feature.name))]));
|
||||
const current = (name: string): FeatureState => ({
|
||||
enabled: pending[name]?.enabled ?? stored[name].enabled,
|
||||
|
||||
Reference in new issue
Block a user