Implement config notification event

Add fieldChanged event to config objects that is triggered when the
value of a field in a group belonging to it is changed.
This commit is contained in:
Hornwitser committed 2020-05-30 14:27:59 +02:00
1 parent fc3686b865
commit 67ca8dcc4d
4 files changed
+101 -21

No files matched your search

+39 -10
View File
@@ -1,6 +1,9 @@
// Configuration classes // Configuration classes
"use strict"; "use strict";
const events = require("events");
const util = require("util");
const { basicType } = require("lib/helpers"); const { basicType } = require("lib/helpers");
@@ -55,10 +58,20 @@ function splitOn(separator, string) {
* Represents a collection of ConfigGroup instances that can be * Represents a collection of ConfigGroup instances that can be
* managed as one. * managed as one.
* *
* This is an EventEmitter with the following events:
* - fieldChanged -
* invoked after a field has been updated in one of the config groups
* belonging to this config. Takes three parameters: group, field,
* prev.
*
* @extends events.EventEmitter
*
* @memberof module:lib/config * @memberof module:lib/config
*/ */
class Config { class Config extends events.EventEmitter {
constructor() { constructor() {
super();
if (!this.constructor._finalized) { if (!this.constructor._finalized) {
throw new Error(`Cannot instantiate incomplete Config class ${this.constructor.name}`) throw new Error(`Cannot instantiate incomplete Config class ${this.constructor.name}`)
} }
@@ -71,7 +84,7 @@ class Config {
for (let [name, GroupClass] of this.constructor._groups) { for (let [name, GroupClass] of this.constructor._groups) {
if (!this._groups.has(name)) { if (!this._groups.has(name)) {
let group = new GroupClass(); let group = new GroupClass();
await group.init(); await group.init(this);
this._groups.set(name, group); this._groups.set(name, group);
} }
} }
@@ -98,7 +111,7 @@ class Config {
} }
let group = new GroupClass(); let group = new GroupClass();
await group.load(serializedGroup); await group.load(this, serializedGroup);
this._groups.set(GroupClass.groupName, group); this._groups.set(GroupClass.groupName, group);
} }
@@ -123,12 +136,12 @@ class Config {
* Updates all groups in the config with groups in the serialized * Updates all groups in the config with groups in the serialized
* config passed. * config passed.
*/ */
update(serializedConfig) { update(serializedConfig, notify) {
this._validate(serializedConfig); this._validate(serializedConfig);
for (let serializedGroup of serializedConfig.groups) { for (let serializedGroup of serializedConfig.groups) {
let group = this._groups.get(serializedGroup.name); let group = this._groups.get(serializedGroup.name);
if (group) { if (group) {
group.update(serializedGroup); group.update(serializedGroup, notify);
} else { } else {
this._unknownGroups.set(serializedGroup.name, serializedGroup); this._unknownGroups.set(serializedGroup.name, serializedGroup);
} }
@@ -226,6 +239,11 @@ class Config {
/** /**
* Collection of related config entries * Collection of related config entries
* *
* Type checks and stores a collection of related config entries. Attempt
* to set invalid values for fields will result in an error thrown while
* loading a config with invalid values will result in those being replaced
* by the innitial value for those fields.
*
* @memberof module:lib/config * @memberof module:lib/config
*/ */
class ConfigGroup { class ConfigGroup {
@@ -242,6 +260,7 @@ class ConfigGroup {
this._fields = new Map(); this._fields = new Map();
this._unknownFields = new Map(); this._unknownFields = new Map();
this._config = null;
} }
/** /**
@@ -250,7 +269,9 @@ class ConfigGroup {
* Computes and assigns the initial values for all fields of the * Computes and assigns the initial values for all fields of the
* config group. * config group.
*/ */
async init() { async init(config) {
this._config = config;
for (let [name, def] of this.constructor._definitions) { for (let [name, def] of this.constructor._definitions) {
if (this._fields.has(name)) { if (this._fields.has(name)) {
continue; continue;
@@ -275,9 +296,9 @@ class ConfigGroup {
* group and then initializes any possible missing fields from it to * group and then initializes any possible missing fields from it to
* their default values. * their default values.
*/ */
async load(serializedGroup) { async load(config, serializedGroup) {
this.update(serializedGroup); this.update(serializedGroup, false);
await this.init(); await this.init(config);
} }
/** /**
@@ -345,7 +366,11 @@ class ConfigGroup {
} }
} }
let prev = this._fields.get(name);
this._fields.set(name, value); this._fields.set(name, value);
if (this._config && !util.isDeepStrictEqual(value, prev)) {
this._config.emit("fieldChanged", this, name, prev);
}
} }
/** /**
@@ -354,7 +379,7 @@ class ConfigGroup {
* Overwrites the values of all the fields in this config group that * Overwrites the values of all the fields in this config group that
* has a valid value in the passed serialized group with that value. * has a valid value in the passed serialized group with that value.
*/ */
update(serializedGroup) { update(serializedGroup, notify) {
if (basicType(serializedGroup) !== "object") { if (basicType(serializedGroup) !== "object") {
throw new Error(`Expected object, not ${basicType(serializedGroup)} for ConfigGroup`); throw new Error(`Expected object, not ${basicType(serializedGroup)} for ConfigGroup`);
} }
@@ -388,7 +413,11 @@ class ConfigGroup {
continue; continue;
} }
let prev = this._fields.get(name);
this._fields.set(name, value); this._fields.set(name, value);
if (notify && this._config && !util.isDeepStrictEqual(value, prev)) {
this._config.emit("fieldChanged", this, name, prev);
}
} }
} }
+13
View File
@@ -42,6 +42,19 @@ class BaseInstancePlugin {
*/ */
async init() { } async init() { }
/**
* Called when the value of a config field changed.
*
* Invoked after the value of the config field given by `field` has
* changed.
*
* @param {module:lib/config.ConfigGroup} group -
* The group who's field got changed on.
* @param {string} field - Name of the field that changed.
* @param prev - The previous value of the field.
*/
async onInstanceConfigFieldChanged(group, field, prev) { }
/** /**
* Called before collecting Prometheus metrics * Called before collecting Prometheus metrics
* *
+8 -1
View File
@@ -68,6 +68,11 @@ class Instance extends link.Link{
this.plugins = new Map(); this.plugins = new Map();
this.config = instanceConfig; this.config = instanceConfig;
this._configFieldChanged = (group, field, prev) => {
plugin.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev);
};
this.config.on("fieldChanged", this._configFieldChanged);
let serverOptions = { let serverOptions = {
version: this.config.get("factorio.version"), version: this.config.get("factorio.version"),
gamePort: this.config.get('factorio.game_port'), gamePort: this.config.get('factorio.game_port'),
@@ -112,6 +117,8 @@ class Instance extends link.Link{
this._running = false; this._running = false;
link.messages.instanceStopped.send(this, { instance_id: this.config.get("instance.id") }); link.messages.instanceStopped.send(this, { instance_id: this.config.get("instance.id") });
this.config.off("fieldChanged", this._configFieldChanged);
// Clear metrics this instance is exporting // Clear metrics this instance is exporting
for (let collector of prometheus.defaultRegistry.collectors) { for (let collector of prometheus.defaultRegistry.collectors) {
if ( if (
@@ -756,7 +763,7 @@ class Slave extends link.Link {
let { instance_id, serialized_config } = message.data; let { instance_id, serialized_config } = message.data;
let instanceInfo = this.instanceInfos.get(instance_id); let instanceInfo = this.instanceInfos.get(instance_id);
if (instanceInfo) { if (instanceInfo) {
instanceInfo.config.update(serialized_config); instanceInfo.config.update(serialized_config, true);
console.log(`Clusterio | Updated config for ${instanceInfo.path}`); console.log(`Clusterio | Updated config for ${instanceInfo.path}`);
// TODO: Notify of update if instance is running // TODO: Notify of update if instance is running
+41 -10
View File
@@ -177,7 +177,7 @@ describe("lib/config/classes", function() {
describe(".load()", function() { describe(".load()", function() {
it("should load a basic group", async function() { it("should load a basic group", async function() {
let testInstance = new TestGroup(); let testInstance = new TestGroup();
await testInstance.load({ name: "test_group", fields: { await testInstance.load(null, { name: "test_group", fields: {
enum: "c", enum: "c",
test: "blah", test: "blah",
func: 22, func: 22,
@@ -193,7 +193,7 @@ describe("lib/config/classes", function() {
}); });
it("should load defaults for missing serialized fields", async function() { it("should load defaults for missing serialized fields", async function() {
let testInstance = new TestGroup(); let testInstance = new TestGroup();
await testInstance.load({ name: "test_group", fields: { enum: "a" } }); await testInstance.load(null, { name: "test_group", fields: { enum: "a" } });
assert.equal(testInstance.get("enum"), "a"); assert.equal(testInstance.get("enum"), "a");
assert.equal(testInstance.get("test"), null); assert.equal(testInstance.get("test"), null);
@@ -213,7 +213,7 @@ describe("lib/config/classes", function() {
} }
let testInstance = new TestGroup(); let testInstance = new TestGroup();
await testInstance.load({ name: "test_group", fields: testFields }); await testInstance.load(null, { name: "test_group", fields: testFields });
assert.deepEqual(testInstance.serialize().fields, testFields); assert.deepEqual(testInstance.serialize().fields, testFields);
}); });
@@ -223,7 +223,7 @@ describe("lib/config/classes", function() {
it("should skip updating invalid values", async function() { it("should skip updating invalid values", async function() {
let testInstance = new TestGroup(); let testInstance = new TestGroup();
await testInstance.init(); await testInstance.init();
testInstance.update({ name: "test_group", fields: { enum: "wrong", test: 3, func: null }}); testInstance.update({ name: "test_group", fields: { enum: "wrong", test: 3, func: null }}, false);
assert.equal(testInstance.get("enum"), "b"); assert.equal(testInstance.get("enum"), "b");
assert.equal(testInstance.get("test"), null); assert.equal(testInstance.get("test"), null);
@@ -237,19 +237,19 @@ describe("lib/config/classes", function() {
new Error("Expected object, not undefined for ConfigGroup") new Error("Expected object, not undefined for ConfigGroup")
); );
assert.throws( assert.throws(
() => testInstance.update({}), () => testInstance.update({}, false),
new Error("Expected group name test_group, not undefined") new Error("Expected group name test_group, not undefined")
); );
assert.throws( assert.throws(
() => testInstance.update({ name: "test_group" }), () => testInstance.update({ name: "test_group" }, false),
new Error("Expected fields to be an object, not undefined") new Error("Expected fields to be an object, not undefined")
); );
assert.throws( assert.throws(
() => testInstance.update({ name: "test_group", fields: []}), () => testInstance.update({ name: "test_group", fields: []}, false),
new Error("Expected fields to be an object, not array") new Error("Expected fields to be an object, not array")
); );
assert.throws( assert.throws(
() => testInstance.update({ name: "test_group", fields: null}), () => testInstance.update({ name: "test_group", fields: null}, false),
new Error("Expected fields to be an object, not null") new Error("Expected fields to be an object, not null")
); );
}); });
@@ -261,7 +261,7 @@ describe("lib/config/classes", function() {
testInstance = new TestGroup(); testInstance = new TestGroup();
testInstance.update({ name: "test_group", fields: { testInstance.update({ name: "test_group", fields: {
enum: "a", test: "blah", func: 27, enum: "a", test: "blah", func: 27,
}}); }}, false);
}); });
it("should throw if field does not exist", function() { it("should throw if field does not exist", function() {
@@ -500,7 +500,7 @@ describe("lib/config/classes", function() {
name: "beta", name: "beta",
fields: { bar: 30 }, fields: { bar: 30 },
} }
]}); ]}, false);
assert.deepEqual(testInstance.serialize(), { assert.deepEqual(testInstance.serialize(), {
groups: [ groups: [
@@ -563,5 +563,36 @@ describe("lib/config/classes", function() {
}); });
}); });
describe("fieldChanged event", function() {
it("should be called when setting a field", async function() {
let testInstance = new TestConfig();
await testInstance.init();
let called = false;
testInstance.once("fieldChanged", (group, field, prev) => {
if (group.constructor.groupName === "alpha" && field === "foo") {
called = true;
}
});
testInstance.set("alpha.foo", "new value");
assert(called, "fieldChanged was not called");
});
it("should be called when updating a config", async function() {
let testInstance = new TestConfig();
await testInstance.init();
let called = false;
testInstance.once("fieldChanged", (group, field, prev) => {
if (group.constructor.groupName === "alpha" && field === "foo") {
called = true;
}
});
testInstance.update({ groups: [{ name: "alpha", fields: { foo: "new value" }}]}, true);
assert(called, "fieldChanged was not called");
});
});
}); });
}); });