mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-23 00:13:13 +09:00
Fix missing semicolons
Ensure all statements end with a semicolon.
This commit is contained in:
1 parent
34aaeee354
commit
29f066a191
56 files changed
+242
-242
No files matched your search
+2
-2
@@ -45,7 +45,7 @@ async function build(args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (args.clean) {
|
if (args.clean) {
|
||||||
let splitter = /^(.*)_(\d+\.\d+\.\d+)(\.zip)?$/
|
let splitter = /^(.*)_(\d+\.\d+\.\d+)(\.zip)?$/;
|
||||||
for (let entry of await fs.readdir(args.outputDir)) {
|
for (let entry of await fs.readdir(args.outputDir)) {
|
||||||
let match = splitter.exec(entry);
|
let match = splitter.exec(entry);
|
||||||
if (match) {
|
if (match) {
|
||||||
@@ -111,7 +111,7 @@ async function build(args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (module === require.main) {
|
if (module === require.main) {
|
||||||
main().catch(err => { console.log(err) });
|
main().catch(err => { console.log(err); });
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
+5
-5
@@ -431,7 +431,7 @@ commands.push(new Command({
|
|||||||
let response = await link.messages.sendRcon.send(control, {
|
let response = await link.messages.sendRcon.send(control, {
|
||||||
instance_id: await resolveInstance(control, args.instance),
|
instance_id: await resolveInstance(control, args.instance),
|
||||||
command: args.command
|
command: args.command
|
||||||
})
|
});
|
||||||
|
|
||||||
// Factorio includes a newline in it's response output.
|
// Factorio includes a newline in it's response output.
|
||||||
process.stdout.write(response.result);
|
process.stdout.write(response.result);
|
||||||
@@ -509,7 +509,7 @@ commands.push(new Command({
|
|||||||
});
|
});
|
||||||
}],
|
}],
|
||||||
handler: async function(args, control) {
|
handler: async function(args, control) {
|
||||||
let role = await resolveRole(control, args.role)
|
let role = await resolveRole(control, args.role);
|
||||||
await link.messages.deleteRole.send(control, { id: role.id });
|
await link.messages.deleteRole.send(control, { id: role.id });
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
@@ -647,7 +647,7 @@ class Control extends link.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.connector.close(1001, "Control Quit")
|
await this.connector.close(1001, "Control Quit");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -733,7 +733,7 @@ async function startControl() {
|
|||||||
command = commands.get(commandName);
|
command = commands.get(commandName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await command.run(args, control)
|
await command.run(args, control);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof errors.CommandError) {
|
if (err instanceof errors.CommandError) {
|
||||||
@@ -761,7 +761,7 @@ module.exports = {
|
|||||||
_Control: Control,
|
_Control: Control,
|
||||||
|
|
||||||
_commands: commands,
|
_commands: commands,
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
if (module === require.main) {
|
if (module === require.main) {
|
||||||
|
|||||||
+12
-12
@@ -73,7 +73,7 @@ class Config extends events.EventEmitter {
|
|||||||
super();
|
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}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._groups = new Map();
|
this._groups = new Map();
|
||||||
@@ -177,7 +177,7 @@ class Config extends events.EventEmitter {
|
|||||||
*/
|
*/
|
||||||
group(name) {
|
group(name) {
|
||||||
if (!this._initialized) {
|
if (!this._initialized) {
|
||||||
throw new Error(`${this.constructor.name} instance is uninitialized`)
|
throw new Error(`${this.constructor.name} instance is uninitialized`);
|
||||||
}
|
}
|
||||||
let group = this._groups.get(name);
|
let group = this._groups.get(name);
|
||||||
if (!group) {
|
if (!group) {
|
||||||
@@ -263,7 +263,7 @@ class ConfigGroup {
|
|||||||
*/
|
*/
|
||||||
constructor(serializedGroup) {
|
constructor(serializedGroup) {
|
||||||
if (!this.constructor._finalized) {
|
if (!this.constructor._finalized) {
|
||||||
throw new Error(`Cannot instantiate incomplete ConfigGroup class ${this.constructor.name}`)
|
throw new Error(`Cannot instantiate incomplete ConfigGroup class ${this.constructor.name}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._fields = new Map();
|
this._fields = new Map();
|
||||||
@@ -287,7 +287,7 @@ class ConfigGroup {
|
|||||||
|
|
||||||
let value = null;
|
let value = null;
|
||||||
if (typeof def.initial_value === "function") {
|
if (typeof def.initial_value === "function") {
|
||||||
value = await def.initial_value()
|
value = await def.initial_value();
|
||||||
|
|
||||||
} else if (def.initial_value !== undefined) {
|
} else if (def.initial_value !== undefined) {
|
||||||
value = def.initial_value;
|
value = def.initial_value;
|
||||||
@@ -368,14 +368,14 @@ class ConfigGroup {
|
|||||||
try {
|
try {
|
||||||
value = JSON.parse(value);
|
value = JSON.parse(value);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new InvalidValue(`Error parsing value for ${name}: ${err.message}`)
|
throw new InvalidValue(`Error parsing value for ${name}: ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (value === null) {
|
if (value === null) {
|
||||||
if (!def.optional) {
|
if (!def.optional) {
|
||||||
throw new InvalidValue(`Field ${name} cannot be null`)
|
throw new InvalidValue(`Field ${name} cannot be null`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
@@ -540,11 +540,11 @@ class ConfigGroup {
|
|||||||
*/
|
*/
|
||||||
static define(item) {
|
static define(item) {
|
||||||
if (this._finalized) {
|
if (this._finalized) {
|
||||||
throw new Error(`Cannot define field for ConfigGroup class ${this.name} after it has been finalized`)
|
throw new Error(`Cannot define field for ConfigGroup class ${this.name} after it has been finalized`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (basicType(this.groupName) !== "string") {
|
if (basicType(this.groupName) !== "string") {
|
||||||
throw new Error(`Expected ConfigGroup class ${this.name} to have the groupName property set to a string`)
|
throw new Error(`Expected ConfigGroup class ${this.name} to have the groupName property set to a string`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._initSubclass();
|
this._initSubclass();
|
||||||
@@ -556,7 +556,7 @@ class ConfigGroup {
|
|||||||
if (!itemKeys.includes(prop)) {
|
if (!itemKeys.includes(prop)) {
|
||||||
throw new Error(`${prop} is required when defining an field`);
|
throw new Error(`${prop} is required when defining an field`);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
// Validate properties
|
// Validate properties
|
||||||
let validTypes = ["boolean", "string", "number", "object"];
|
let validTypes = ["boolean", "string", "number", "object"];
|
||||||
@@ -618,7 +618,7 @@ class ConfigGroup {
|
|||||||
let computed = Object.assign({
|
let computed = Object.assign({
|
||||||
optional: false,
|
optional: false,
|
||||||
fullName: `${this.groupName}.${item.name}`,
|
fullName: `${this.groupName}.${item.name}`,
|
||||||
}, item)
|
}, item);
|
||||||
|
|
||||||
if (!computed.optional && computed.initial_value === undefined) {
|
if (!computed.optional && computed.initial_value === undefined) {
|
||||||
throw new Error(`Non-optional field ${item.name} needs an initial_value`);
|
throw new Error(`Non-optional field ${item.name} needs an initial_value`);
|
||||||
@@ -632,7 +632,7 @@ class ConfigGroup {
|
|||||||
*/
|
*/
|
||||||
static finalize() {
|
static finalize() {
|
||||||
if (basicType(this.groupName) !== "string") {
|
if (basicType(this.groupName) !== "string") {
|
||||||
throw new Error(`Expected ConfigGroup class ${this.name} to have the groupName property set to a string`)
|
throw new Error(`Expected ConfigGroup class ${this.name} to have the groupName property set to a string`);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._initSubclass();
|
this._initSubclass();
|
||||||
@@ -672,4 +672,4 @@ module.exports = {
|
|||||||
Config,
|
Config,
|
||||||
ConfigGroup,
|
ConfigGroup,
|
||||||
PluginConfigGroup,
|
PluginConfigGroup,
|
||||||
}
|
};
|
||||||
@@ -15,7 +15,7 @@ const classes = require("./classes");
|
|||||||
* @memberof module:lib/config
|
* @memberof module:lib/config
|
||||||
*/
|
*/
|
||||||
class MasterGroup extends classes.ConfigGroup { }
|
class MasterGroup extends classes.ConfigGroup { }
|
||||||
MasterGroup.groupName = "master"
|
MasterGroup.groupName = "master";
|
||||||
MasterGroup.define({
|
MasterGroup.define({
|
||||||
name: "database_directory",
|
name: "database_directory",
|
||||||
title: "Database directory",
|
title: "Database directory",
|
||||||
@@ -189,7 +189,7 @@ SlaveConfig.registerGroup(SlaveGroup);
|
|||||||
* @memberof module:lib/config
|
* @memberof module:lib/config
|
||||||
*/
|
*/
|
||||||
class InstanceGroup extends classes.ConfigGroup { }
|
class InstanceGroup extends classes.ConfigGroup { }
|
||||||
InstanceGroup.groupName = "instance"
|
InstanceGroup.groupName = "instance";
|
||||||
InstanceGroup.define({
|
InstanceGroup.define({
|
||||||
name: "name",
|
name: "name",
|
||||||
type: "string",
|
type: "string",
|
||||||
@@ -438,4 +438,4 @@ module.exports = {
|
|||||||
finalizeConfigs,
|
finalizeConfigs,
|
||||||
configCommand,
|
configCommand,
|
||||||
handleConfigCommand,
|
handleConfigCommand,
|
||||||
}
|
};
|
||||||
+1
-1
@@ -6,4 +6,4 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
...require("./classes"),
|
...require("./classes"),
|
||||||
...require("./definitions"),
|
...require("./definitions"),
|
||||||
}
|
};
|
||||||
+2
-2
@@ -232,7 +232,7 @@ class ItemDatabase {
|
|||||||
checkName(name);
|
checkName(name);
|
||||||
|
|
||||||
if (!this._items.has(name)) {
|
if (!this._items.has(name)) {
|
||||||
return 0
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return this._items.get(name);
|
return this._items.get(name);
|
||||||
@@ -287,4 +287,4 @@ module.exports = {
|
|||||||
loadJsonArrayAsMap,
|
loadJsonArrayAsMap,
|
||||||
saveMapAsJsonArray,
|
saveMapAsJsonArray,
|
||||||
ItemDatabase,
|
ItemDatabase,
|
||||||
}
|
};
|
||||||
+1
-1
@@ -71,4 +71,4 @@ module.exports = {
|
|||||||
StartupError,
|
StartupError,
|
||||||
EnvironmentError,
|
EnvironmentError,
|
||||||
PluginError,
|
PluginError,
|
||||||
}
|
};
|
||||||
@@ -21,7 +21,7 @@ const buildMod = require("../../build-mod");
|
|||||||
*/
|
*/
|
||||||
async function generateExportMod(server) {
|
async function generateExportMod(server) {
|
||||||
let dependencies = [];
|
let dependencies = [];
|
||||||
let splitter = /^(.*)_(\d+\.\d+\.\d+)(\.zip)?$/
|
let splitter = /^(.*)_(\d+\.\d+\.\d+)(\.zip)?$/;
|
||||||
for (let entry of await fs.readdir(server.writePath("mods"))) {
|
for (let entry of await fs.readdir(server.writePath("mods"))) {
|
||||||
let match = splitter.exec(entry);
|
let match = splitter.exec(entry);
|
||||||
if (match && match[1] !== "export") {
|
if (match && match[1] !== "export") {
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ function reorderDependencies(modules) {
|
|||||||
|
|
||||||
if (cycle.includes(module.name)) {
|
if (cycle.includes(module.name)) {
|
||||||
cycle.push(module.name);
|
cycle.push(module.name);
|
||||||
cycle.splice(0, cycle.indexOf(module.name))
|
cycle.splice(0, cycle.indexOf(module.name));
|
||||||
throw new Error(`Module dependency loop detected: ${cycle.join(" -> ")}`);
|
throw new Error(`Module dependency loop detected: ${cycle.join(" -> ")}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,7 +251,7 @@ async function patch(savePath, modules) {
|
|||||||
let moduleInfo = {
|
let moduleInfo = {
|
||||||
"name": module.name,
|
"name": module.name,
|
||||||
"files": [],
|
"files": [],
|
||||||
}
|
};
|
||||||
|
|
||||||
let dirs = [[module.path, ""]];
|
let dirs = [[module.path, ""]];
|
||||||
while (dirs.length) {
|
while (dirs.length) {
|
||||||
@@ -294,4 +294,4 @@ module.exports = {
|
|||||||
_findRoot: findRoot,
|
_findRoot: findRoot,
|
||||||
_generateLoader: generateLoader,
|
_generateLoader: generateLoader,
|
||||||
_reorderDependencies: reorderDependencies,
|
_reorderDependencies: reorderDependencies,
|
||||||
}
|
};
|
||||||
+13
-13
@@ -140,7 +140,7 @@ function randomDynamicPort() {
|
|||||||
const start = 49152;
|
const start = 49152;
|
||||||
const end = 65535 + 1;
|
const end = 65535 + 1;
|
||||||
|
|
||||||
return Math.floor(Math.random() * (end - start) + start)
|
return Math.floor(Math.random() * (end - start) + start);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -206,7 +206,7 @@ class LineSplitter {
|
|||||||
*/
|
*/
|
||||||
constructor(callback) {
|
constructor(callback) {
|
||||||
this._callback = callback;
|
this._callback = callback;
|
||||||
this._partial = null
|
this._partial = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -278,12 +278,12 @@ function parseOutput(line, source) {
|
|||||||
let output = {
|
let output = {
|
||||||
source,
|
source,
|
||||||
received: Date.now(),
|
received: Date.now(),
|
||||||
}
|
};
|
||||||
|
|
||||||
// There are three broad categories of output from Factorio, the first kind
|
// There are three broad categories of output from Factorio, the first kind
|
||||||
// starts with the seconds since the server started and has a format of
|
// starts with the seconds since the server started and has a format of
|
||||||
// " 0.704 message"
|
// " 0.704 message"
|
||||||
const secRegex = /^ {0,3}(\d+\.\d+) (.*)$/
|
const secRegex = /^ {0,3}(\d+\.\d+) (.*)$/;
|
||||||
let secMatch = secRegex.exec(line);
|
let secMatch = secRegex.exec(line);
|
||||||
if (secMatch) {
|
if (secMatch) {
|
||||||
output.format = "seconds";
|
output.format = "seconds";
|
||||||
@@ -293,7 +293,7 @@ function parseOutput(line, source) {
|
|||||||
// A seconds output has two different kinds of formats: The first is a
|
// A seconds output has two different kinds of formats: The first is a
|
||||||
// log level and source location and has a format of
|
// log level and source location and has a format of
|
||||||
// "Level File.cpp:123: message"
|
// "Level File.cpp:123: message"
|
||||||
const secLogRegex = /^(\w+) (\w+\.cpp:\d+): (.*)$/
|
const secLogRegex = /^(\w+) (\w+\.cpp:\d+): (.*)$/;
|
||||||
let secLogMatch = secLogRegex.exec(secContent);
|
let secLogMatch = secLogRegex.exec(secContent);
|
||||||
if (secLogMatch) {
|
if (secLogMatch) {
|
||||||
output.type = "log";
|
output.type = "log";
|
||||||
@@ -310,7 +310,7 @@ function parseOutput(line, source) {
|
|||||||
// The second category of output starts with a date stamp of the format
|
// The second category of output starts with a date stamp of the format
|
||||||
// "yyyy-mm-dd hh:mm:ss message"
|
// "yyyy-mm-dd hh:mm:ss message"
|
||||||
} else {
|
} else {
|
||||||
const dateRegex = /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d) (.*)$/
|
const dateRegex = /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d) (.*)$/;
|
||||||
let dateMatch = dateRegex.exec(line);
|
let dateMatch = dateRegex.exec(line);
|
||||||
if (dateMatch) {
|
if (dateMatch) {
|
||||||
output.format = "date";
|
output.format = "date";
|
||||||
@@ -319,7 +319,7 @@ function parseOutput(line, source) {
|
|||||||
|
|
||||||
// A date output has two general formats. The first is an action
|
// A date output has two general formats. The first is an action
|
||||||
// followed by a message and has a format of "[ACTION] message"
|
// followed by a message and has a format of "[ACTION] message"
|
||||||
const dateActionRegex = /^\[(\w+)\] (.*)$/
|
const dateActionRegex = /^\[(\w+)\] (.*)$/;
|
||||||
let dateActionMatch = dateActionRegex.exec(dateContent);
|
let dateActionMatch = dateActionRegex.exec(dateContent);
|
||||||
if (dateActionMatch) {
|
if (dateActionMatch) {
|
||||||
output.type = "action";
|
output.type = "action";
|
||||||
@@ -523,14 +523,14 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
this.on("_autosave", function(name) {
|
this.on("_autosave", function(name) {
|
||||||
this.emit("autosave-start", name);
|
this.emit("autosave-start", name);
|
||||||
this._runningAutosave = name;
|
this._runningAutosave = name;
|
||||||
})
|
});
|
||||||
|
|
||||||
this.on("_saved", function() {
|
this.on("_saved", function() {
|
||||||
if (this._runningAutosave) {
|
if (this._runningAutosave) {
|
||||||
this.emit("autosave-finished", this._runningAutosave);
|
this.emit("autosave-finished", this._runningAutosave);
|
||||||
this._runningAutosave = null;
|
this._runningAutosave = null;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_check(expectedStates) {
|
_check(expectedStates) {
|
||||||
@@ -566,7 +566,7 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
|
|
||||||
// Prevent malicious names
|
// Prevent malicious names
|
||||||
if (/[\\/\0]/.test(fileName)) {
|
if (/[\\/\0]/.test(fileName)) {
|
||||||
throw new Error(`Invalid IPC file name '${fileName}'`)
|
throw new Error(`Invalid IPC file name '${fileName}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fileName.endsWith(".json")) {
|
if (fileName.endsWith(".json")) {
|
||||||
@@ -575,7 +575,7 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
|
|
||||||
} else {
|
} else {
|
||||||
let format = fileName.slice(fileName.lastIndexOf(".") + 1);
|
let format = fileName.slice(fileName.lastIndexOf(".") + 1);
|
||||||
throw new Error(`Unknown IPC file format '${format}'`)
|
throw new Error(`Unknown IPC file format '${format}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
@@ -703,7 +703,7 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
} else {
|
} else {
|
||||||
let msg;
|
let msg;
|
||||||
if (code !== null) {
|
if (code !== null) {
|
||||||
msg = `Factorio server unexpectedly shut down with code ${code}`
|
msg = `Factorio server unexpectedly shut down with code ${code}`;
|
||||||
} else {
|
} else {
|
||||||
msg = `Factorio server was unexpectedly shut by down by signal ${signal}`;
|
msg = `Factorio server was unexpectedly shut by down by signal ${signal}`;
|
||||||
}
|
}
|
||||||
@@ -865,7 +865,7 @@ class FactorioServer extends events.EventEmitter {
|
|||||||
* @returns {string} response from server.
|
* @returns {string} response from server.
|
||||||
*/
|
*/
|
||||||
async sendRcon(message, expectEmpty) {
|
async sendRcon(message, expectEmpty) {
|
||||||
this._check(["running", "stopping"])
|
this._check(["running", "stopping"]);
|
||||||
if (!this._rconReady) {
|
if (!this._rconReady) {
|
||||||
await events.once(this, "rcon-ready");
|
await events.once(this, "rcon-ready");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,4 +33,4 @@ async function getNewestFile(directory, filter = (name) => true) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getNewestFile,
|
getNewestFile,
|
||||||
}
|
};
|
||||||
@@ -41,4 +41,4 @@ module.exports = async function({
|
|||||||
await fs.outputFile(sslCertPath, forge.pki.certificateToPem(cert));
|
await fs.outputFile(sslCertPath, forge.pki.certificateToPem(cert));
|
||||||
|
|
||||||
log("Generated certificate in: "+(Number(hrtime()-startNs) / 1e6)+" ms");
|
log("Generated certificate in: "+(Number(hrtime()-startNs) / 1e6)+" ms");
|
||||||
}
|
};
|
||||||
+3
-3
@@ -14,8 +14,8 @@ const fs = require("fs");
|
|||||||
*/
|
*/
|
||||||
function hashStream(stream) {
|
function hashStream(stream) {
|
||||||
return new Promise(function(resolve, reject) {
|
return new Promise(function(resolve, reject) {
|
||||||
let hasher = crypto.createHash("sha1")
|
let hasher = crypto.createHash("sha1");
|
||||||
hasher.setEncoding("hex")
|
hasher.setEncoding("hex");
|
||||||
hasher.on("finish", function() {
|
hasher.on("finish", function() {
|
||||||
resolve(hasher.read());
|
resolve(hasher.read());
|
||||||
});
|
});
|
||||||
@@ -42,4 +42,4 @@ function hashFile(path) {
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
hashStream,
|
hashStream,
|
||||||
hashFile,
|
hashFile,
|
||||||
}
|
};
|
||||||
+1
-1
@@ -20,4 +20,4 @@ function basicType(value) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
basicType,
|
basicType,
|
||||||
}
|
};
|
||||||
@@ -226,7 +226,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
url.pathname += "api/socket";
|
url.pathname += "api/socket";
|
||||||
|
|
||||||
// Open WebSocket to master
|
// Open WebSocket to master
|
||||||
console.log(`SOCKET | connecting to ${url}`)
|
console.log(`SOCKET | connecting to ${url}`);
|
||||||
|
|
||||||
this._socket = new WebSocket(url, {
|
this._socket = new WebSocket(url, {
|
||||||
// For now we do not verify TLS certificates since the default setup is
|
// For now we do not verify TLS certificates since the default setup is
|
||||||
@@ -261,7 +261,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let delay = Math.random() * this._reconnectDelay;
|
let delay = Math.random() * this._reconnectDelay;
|
||||||
console.log(`SOCKET | waiting ${delay.toLocaleString("en", { maximumFractionDigits: 2 })} seconds for reconnect`)
|
console.log(`SOCKET | waiting ${delay.toLocaleString("en", { maximumFractionDigits: 2 })} seconds for reconnect`);
|
||||||
this._reconnectId = setTimeout(() => {
|
this._reconnectId = setTimeout(() => {
|
||||||
this._reconnectId = null;
|
this._reconnectId = null;
|
||||||
this._doConnect();
|
this._doConnect();
|
||||||
|
|||||||
+2
-2
@@ -35,7 +35,7 @@ class Link {
|
|||||||
this.processMessage(payload);
|
this.processMessage(payload);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof errors.InvalidMessage) {
|
if (err instanceof errors.InvalidMessage) {
|
||||||
console.error(`Invalid message on ${this.source}-${this.target} link: ${err.message}`)
|
console.error(`Invalid message on ${this.source}-${this.target} link: ${err.message}`);
|
||||||
if (err.errors) {
|
if (err.errors) {
|
||||||
console.error(err.errors);
|
console.error(err.errors);
|
||||||
}
|
}
|
||||||
@@ -243,4 +243,4 @@ class Link {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
Link,
|
Link,
|
||||||
}
|
};
|
||||||
@@ -226,7 +226,7 @@ class Request extends Message {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
let messages = {}
|
let messages = {};
|
||||||
|
|
||||||
// Connection requests
|
// Connection requests
|
||||||
let wsLinks = ["master-control", "control-master", "master-slave", "slave-master"];
|
let wsLinks = ["master-control", "control-master", "master-slave", "slave-master"];
|
||||||
@@ -396,7 +396,7 @@ messages.assignInstance = new Request({
|
|||||||
"serialized_config": { type: "object" },
|
"serialized_config": { type: "object" },
|
||||||
},
|
},
|
||||||
forwardTo: "instance",
|
forwardTo: "instance",
|
||||||
})
|
});
|
||||||
|
|
||||||
messages.startInstance = new Request({
|
messages.startInstance = new Request({
|
||||||
type: "start_instance",
|
type: "start_instance",
|
||||||
@@ -705,7 +705,7 @@ class Event extends Message {
|
|||||||
handler = async (message, event) => {
|
handler = async (message, event) => {
|
||||||
await link.broadcastEventToInstance(message, event);
|
await link.broadcastEventToInstance(message, event);
|
||||||
await originalHandler.call(link, message, event);
|
await originalHandler.call(link, message, event);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -860,4 +860,4 @@ module.exports = {
|
|||||||
attachAllMessages,
|
attachAllMessages,
|
||||||
|
|
||||||
messages,
|
messages,
|
||||||
}
|
};
|
||||||
+1
-1
@@ -19,4 +19,4 @@ function escapeString(content) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
escapeString,
|
escapeString,
|
||||||
}
|
};
|
||||||
@@ -63,14 +63,14 @@ async function listMods(config, instance) {
|
|||||||
date:mod.date,
|
date:mod.date,
|
||||||
factorio_ver:mod.factorio_version,
|
factorio_ver:mod.factorio_version,
|
||||||
author:mod.author,
|
author:mod.author,
|
||||||
}
|
};
|
||||||
})));
|
})));
|
||||||
});
|
});
|
||||||
// Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2
|
// Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2
|
||||||
// bug is resolved, thanks to @Danacus and @brotherpot
|
// bug is resolved, thanks to @Danacus and @brotherpot
|
||||||
factorioAPI.getModsFromSaves().then(list => {
|
factorioAPI.getModsFromSaves().then(list => {
|
||||||
console.log("* Mods used in save:");
|
console.log("* Mods used in save:");
|
||||||
console.log(asTable(list[0].mods))
|
console.log(asTable(list[0].mods));
|
||||||
});
|
});
|
||||||
}).catch(reason => {
|
}).catch(reason => {
|
||||||
console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json");
|
console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json");
|
||||||
@@ -84,8 +84,8 @@ async function listMods(config, instance) {
|
|||||||
token: config.token,
|
token: config.token,
|
||||||
require_ownership: false
|
require_ownership: false
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
console.log("\r\n")
|
console.log("\r\n");
|
||||||
console.log("* Mods shared by all instances:")
|
console.log("* Mods shared by all instances:");
|
||||||
factorioAPI.getInstalledMods().then(mods => {
|
factorioAPI.getInstalledMods().then(mods => {
|
||||||
console.log(asTable(mods));
|
console.log(asTable(mods));
|
||||||
resolve();
|
resolve();
|
||||||
@@ -128,7 +128,7 @@ async function findMods(config, searchTerm) {
|
|||||||
latest_version: mod.latest_release.version,
|
latest_version: mod.latest_release.version,
|
||||||
owner:mod.owner,
|
owner:mod.owner,
|
||||||
//license: mod.license_name,
|
//license: mod.license_name,
|
||||||
}
|
};
|
||||||
}));
|
}));
|
||||||
resolve(result);
|
resolve(result);
|
||||||
// console.log(result);
|
// console.log(result);
|
||||||
@@ -202,7 +202,7 @@ async function addMod(config, term, instance) {
|
|||||||
require_ownership: false
|
require_ownership: false
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
factorioAPI.searchMods(term).then(body => {
|
factorioAPI.searchMods(term).then(body => {
|
||||||
console.log(body)
|
console.log(body);
|
||||||
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
||||||
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
||||||
console.log("Mod downloaded");
|
console.log("Mod downloaded");
|
||||||
@@ -242,7 +242,7 @@ async function removeMod(config, term, instance, force = false) {
|
|||||||
fs.unlinkSync(path.join(modDirectory, modsMatchingFilter[i]));
|
fs.unlinkSync(path.join(modDirectory, modsMatchingFilter[i]));
|
||||||
console.log("Deleted "+modsMatchingFilter[i]);
|
console.log("Deleted "+modsMatchingFilter[i]);
|
||||||
}
|
}
|
||||||
} else console.log("Did not delete mods.")
|
} else console.log("Did not delete mods.");
|
||||||
}
|
}
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
@@ -264,7 +264,7 @@ function downloadFromGitURL(url) {
|
|||||||
let res = syncRequest("GET", url, {"headers":{"User-Agent":"factorioClusterio"}});
|
let res = syncRequest("GET", url, {"headers":{"User-Agent":"factorioClusterio"}});
|
||||||
let downloadUrl = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
let downloadUrl = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
||||||
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
||||||
console.log(JSON.parse(res.getBody()))
|
console.log(JSON.parse(res.getBody()));
|
||||||
if (downloadUrl) {
|
if (downloadUrl) {
|
||||||
console.log(downloadUrl);
|
console.log(downloadUrl);
|
||||||
let file = fs.createWriteStream("sharedMods/"+name);
|
let file = fs.createWriteStream("sharedMods/"+name);
|
||||||
@@ -291,4 +291,4 @@ module.exports = {
|
|||||||
addMod,
|
addMod,
|
||||||
removeMod,
|
removeMod,
|
||||||
downloadFromGitURL,
|
downloadFromGitURL,
|
||||||
}
|
};
|
||||||
@@ -76,7 +76,7 @@ let downloadList = [
|
|||||||
url: "https://fonts.googleapis.com/css?family=Roboto",
|
url: "https://fonts.googleapis.com/css?family=Roboto",
|
||||||
file: "static/external/css/Roboto.css",
|
file: "static/external/css/Roboto.css",
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
|
||||||
// initiate folder creations and downloads
|
// initiate folder creations and downloads
|
||||||
function processMkdirRecursive(callback){
|
function processMkdirRecursive(callback){
|
||||||
|
|||||||
+3
-3
@@ -17,7 +17,7 @@ a == c; // false
|
|||||||
*/
|
*/
|
||||||
module.exports.deepclone = function(obj){
|
module.exports.deepclone = function(obj){
|
||||||
return JSON.parse(JSON.stringify(obj));
|
return JSON.parse(JSON.stringify(obj));
|
||||||
}
|
};
|
||||||
/**
|
/**
|
||||||
Checks if a string is valid JSON using try/catch. If passed an object it will always return true.
|
Checks if a string is valid JSON using try/catch. If passed an object it will always return true.
|
||||||
@param {string} string to verify
|
@param {string} string to verify
|
||||||
@@ -31,7 +31,7 @@ objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true
|
|||||||
*/
|
*/
|
||||||
module.exports.isJSON = function(string){
|
module.exports.isJSON = function(string){
|
||||||
let stringIsJson = false;
|
let stringIsJson = false;
|
||||||
let x
|
let x;
|
||||||
try {
|
try {
|
||||||
x = JSON.parse(string);
|
x = JSON.parse(string);
|
||||||
} catch (e){
|
} catch (e){
|
||||||
@@ -41,4 +41,4 @@ module.exports.isJSON = function(string){
|
|||||||
stringIsJson = true;
|
stringIsJson = true;
|
||||||
}
|
}
|
||||||
return stringIsJson;
|
return stringIsJson;
|
||||||
}
|
};
|
||||||
+9
-9
@@ -46,7 +46,7 @@ function escapeLabelValue(value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function labelsToKey(labels, metricLabels) {
|
function labelsToKey(labels, metricLabels) {
|
||||||
let items = []
|
let items = [];
|
||||||
if (labels.length === 1 && typeof labels[0] === "object") {
|
if (labels.length === 1 && typeof labels[0] === "object") {
|
||||||
labels = labels[0];
|
labels = labels[0];
|
||||||
for (let name of metricLabels) {
|
for (let name of metricLabels) {
|
||||||
@@ -170,7 +170,7 @@ class ValueCollector extends Collector {
|
|||||||
return candidate.get(name) === value;
|
return candidate.get(name) === value;
|
||||||
});
|
});
|
||||||
if (hasLabels) {
|
if (hasLabels) {
|
||||||
mapping.delete(key)
|
mapping.delete(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,7 +208,7 @@ class CounterChild extends ValueCollectorChild {
|
|||||||
throw new Error("Expected value to be a positive number");
|
throw new Error("Expected value to be a positive number");
|
||||||
}
|
}
|
||||||
|
|
||||||
this._values.set(this._key, this._values.get(this._key) + value)
|
this._values.set(this._key, this._values.get(this._key) + value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -224,19 +224,19 @@ class Counter extends ValueCollector {
|
|||||||
|
|
||||||
class GaugeChild extends ValueCollectorChild {
|
class GaugeChild extends ValueCollectorChild {
|
||||||
inc(value = 1) {
|
inc(value = 1) {
|
||||||
this._values.set(this._key, this._values.get(this._key) + value)
|
this._values.set(this._key, this._values.get(this._key) + value);
|
||||||
}
|
}
|
||||||
|
|
||||||
dec(value = 1) {
|
dec(value = 1) {
|
||||||
this._values.set(this._key, this._values.get(this._key) - value)
|
this._values.set(this._key, this._values.get(this._key) - value);
|
||||||
}
|
}
|
||||||
|
|
||||||
set(value) {
|
set(value) {
|
||||||
this._values.set(this._key, value)
|
this._values.set(this._key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
setToCurrentTime() {
|
setToCurrentTime() {
|
||||||
this._values.set(this._key, Date.now() / 1000)
|
this._values.set(this._key, Date.now() / 1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,7 +323,7 @@ async function* expositionLines(resultsIterator) {
|
|||||||
if (first) {
|
if (first) {
|
||||||
first = false;
|
first = false;
|
||||||
} else {
|
} else {
|
||||||
yield "\n"
|
yield "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
yield `# HELP ${result.metric.name} ${escapeHelp(result.metric.help)}\n`;
|
yield `# HELP ${result.metric.name} ${escapeHelp(result.metric.help)}\n`;
|
||||||
@@ -395,7 +395,7 @@ function deserializeResult(serializedResult) {
|
|||||||
serializedResult.metric.labels,
|
serializedResult.metric.labels,
|
||||||
),
|
),
|
||||||
samples: new Map(serializedResult.samples),
|
samples: new Map(serializedResult.samples),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let defaultCollectors = {};
|
let defaultCollectors = {};
|
||||||
|
|||||||
+1
-1
@@ -53,7 +53,7 @@ function definePermission({ name, title, description, grantByDefault=false }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (permissions.has(name)) {
|
if (permissions.has(name)) {
|
||||||
throw new Error(`Permission '${name}' is already defined`)
|
throw new Error(`Permission '${name}' is already defined`);
|
||||||
}
|
}
|
||||||
|
|
||||||
permissions.set(name, new Permission(name, title, description, grantByDefault));
|
permissions.set(name, new Permission(name, title, description, grantByDefault));
|
||||||
|
|||||||
@@ -126,11 +126,11 @@ const wsActiveSlavesGauge = new prometheus.Gauge(
|
|||||||
async function getMetrics(req, res, next) {
|
async function getMetrics(req, res, next) {
|
||||||
endpointHitCounter.labels(req.route.path).inc();
|
endpointHitCounter.labels(req.route.path).inc();
|
||||||
|
|
||||||
let results = []
|
let results = [];
|
||||||
let pluginResults = await plugin.invokeHook(masterPlugins, "onMetrics");
|
let pluginResults = await plugin.invokeHook(masterPlugins, "onMetrics");
|
||||||
for (let metricIterator of pluginResults) {
|
for (let metricIterator of pluginResults) {
|
||||||
for await (let metric of metricIterator) {
|
for await (let metric of metricIterator) {
|
||||||
results.push(metric)
|
results.push(metric);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -314,7 +314,7 @@ async function loadUsers(databaseDirectory, file) {
|
|||||||
*/
|
*/
|
||||||
function createUser(name) {
|
function createUser(name) {
|
||||||
if (db.users.has(name)) {
|
if (db.users.has(name)) {
|
||||||
throw new Error(`User '${name}' already exists`)
|
throw new Error(`User '${name}' already exists`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let defaultRoleId = masterConfig.get("master.default_role_id");
|
let defaultRoleId = masterConfig.get("master.default_role_id");
|
||||||
@@ -475,7 +475,7 @@ class BaseConnection extends link.Link {
|
|||||||
throw new errors.RequestError("Slave containing instance is not connected");
|
throw new errors.RequestError("Slave containing instance is not connected");
|
||||||
}
|
}
|
||||||
if (request.plugin && !connection.plugins.has(request.plugin)) {
|
if (request.plugin && !connection.plugins.has(request.plugin)) {
|
||||||
throw new errors.RequestError(`Slave containing instance does not have ${request.plugin} plugin`)
|
throw new errors.RequestError(`Slave containing instance does not have ${request.plugin} plugin`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await request.send(connection, message.data);
|
return await request.send(connection, message.data);
|
||||||
@@ -529,7 +529,7 @@ class BaseConnection extends link.Link {
|
|||||||
let controlConnections = new Array();
|
let controlConnections = new Array();
|
||||||
class ControlConnection extends BaseConnection {
|
class ControlConnection extends BaseConnection {
|
||||||
constructor(registerData, connector, user) {
|
constructor(registerData, connector, user) {
|
||||||
super("control", connector)
|
super("control", connector);
|
||||||
|
|
||||||
this._agent = registerData.agent;
|
this._agent = registerData.agent;
|
||||||
this._version = registerData.version;
|
this._version = registerData.version;
|
||||||
@@ -617,7 +617,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
let instanceConfig = new config.InstanceConfig();
|
let instanceConfig = new config.InstanceConfig();
|
||||||
await instanceConfig.load(message.data.serialized_config);
|
await instanceConfig.load(message.data.serialized_config);
|
||||||
|
|
||||||
let instanceId = instanceConfig.get("instance.id")
|
let instanceId = instanceConfig.get("instance.id");
|
||||||
if (db.instances.has(instanceId)) {
|
if (db.instances.has(instanceId)) {
|
||||||
throw new errors.RequestError(`Instance with ID ${instanceId} already exists`);
|
throw new errors.RequestError(`Instance with ID ${instanceId} already exists`);
|
||||||
}
|
}
|
||||||
@@ -644,7 +644,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
serialized_config: instance.config.serialize(),
|
serialized_config: instance.config.serialize(),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateInstanceConfig(instance) {
|
async updateInstanceConfig(instance) {
|
||||||
@@ -708,7 +708,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
throw new errors.RequestError("Target slave is not connected to the master server");
|
throw new errors.RequestError("Target slave is not connected to the master server");
|
||||||
}
|
}
|
||||||
|
|
||||||
instance.config.set("instance.assigned_slave", message.data.slave_id)
|
instance.config.set("instance.assigned_slave", message.data.slave_id);
|
||||||
|
|
||||||
return await link.messages.assignInstance.send(connection, {
|
return await link.messages.assignInstance.send(connection, {
|
||||||
instance_id: instance.config.get("instance.id"),
|
instance_id: instance.config.get("instance.id"),
|
||||||
@@ -836,7 +836,7 @@ class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
this.connector._socket.clusterio_ignore_dump = true;
|
this.connector._socket.clusterio_ignore_dump = true;
|
||||||
debugEvents.on("message", this.ws_dumper)
|
debugEvents.on("message", this.ws_dumper);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -883,7 +883,7 @@ class SlaveConnection extends BaseConnection {
|
|||||||
let instance = db.instances.get(message.data.instance_id);
|
let instance = db.instances.get(message.data.instance_id);
|
||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "initialized";
|
instance.status = "initialized";
|
||||||
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Initialized`)
|
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Initialized`);
|
||||||
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -891,7 +891,7 @@ class SlaveConnection extends BaseConnection {
|
|||||||
let instance = db.instances.get(message.data.instance_id);
|
let instance = db.instances.get(message.data.instance_id);
|
||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "running";
|
instance.status = "running";
|
||||||
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Started`)
|
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Started`);
|
||||||
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -899,7 +899,7 @@ class SlaveConnection extends BaseConnection {
|
|||||||
let instance = db.instances.get(message.data.instance_id);
|
let instance = db.instances.get(message.data.instance_id);
|
||||||
let prev = instance.status;
|
let prev = instance.status;
|
||||||
instance.status = "stopped";
|
instance.status = "stopped";
|
||||||
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Stopped`)
|
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} Stopped`);
|
||||||
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -919,7 +919,7 @@ class SlaveConnection extends BaseConnection {
|
|||||||
let instanceConfig = new config.InstanceConfig();
|
let instanceConfig = new config.InstanceConfig();
|
||||||
await instanceConfig.load(instance.serialized_config);
|
await instanceConfig.load(instance.serialized_config);
|
||||||
|
|
||||||
let masterInstance = db.instances.get(instanceConfig.get("instance.id"))
|
let masterInstance = db.instances.get(instanceConfig.get("instance.id"));
|
||||||
if (masterInstance) {
|
if (masterInstance) {
|
||||||
// Already have this instance, update state instead
|
// Already have this instance, update state instead
|
||||||
if (masterInstance.status !== instance.status) {
|
if (masterInstance.status !== instance.status) {
|
||||||
@@ -1022,7 +1022,7 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
|
|||||||
* Sends the ready message over the socket to initiate the session.
|
* Sends the ready message over the socket to initiate the session.
|
||||||
*/
|
*/
|
||||||
ready(sessionToken) {
|
ready(sessionToken) {
|
||||||
this._heartbeatInterval = masterConfig.get("master.heartbeat_interval")
|
this._heartbeatInterval = masterConfig.get("master.heartbeat_interval");
|
||||||
this._socket.send(JSON.stringify({
|
this._socket.send(JSON.stringify({
|
||||||
seq: null,
|
seq: null,
|
||||||
type: "ready",
|
type: "ready",
|
||||||
@@ -1053,7 +1053,7 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
|
|||||||
this._timeoutId = null;
|
this._timeoutId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._heartbeatInterval = masterConfig.get("master.heartbeat_interval")
|
this._heartbeatInterval = masterConfig.get("master.heartbeat_interval");
|
||||||
this._socket.send(JSON.stringify({
|
this._socket.send(JSON.stringify({
|
||||||
seq: null,
|
seq: null,
|
||||||
type: "continue",
|
type: "continue",
|
||||||
@@ -1078,7 +1078,7 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
|
|||||||
clearTimeout(this._timeoutId);
|
clearTimeout(this._timeoutId);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._timeoutId = setTimeout(() => { this._timedOut() }, timeout * 1000);
|
this._timeoutId = setTimeout(() => { this._timedOut(); }, timeout * 1000);
|
||||||
this._timeout = timeout;
|
this._timeout = timeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1117,7 +1117,7 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
|
|||||||
} else {
|
} else {
|
||||||
this._state = "handshake";
|
this._state = "handshake";
|
||||||
this.emit("drop");
|
this.emit("drop");
|
||||||
this._timeoutId = setTimeout(() => { this._timedOut() }, this._timeout * 1000);
|
this._timeoutId = setTimeout(() => { this._timedOut(); }, this._timeout * 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.stopHeartbeat();
|
this.stopHeartbeat();
|
||||||
@@ -1172,7 +1172,7 @@ class WebSocketServerConnector extends link.WebSocketBaseConnector {
|
|||||||
this.stopHeartbeat();
|
this.stopHeartbeat();
|
||||||
this._state = "closing";
|
this._state = "closing";
|
||||||
this._socket.close(code, reason);
|
this._socket.close(code, reason);
|
||||||
await events.once(this, "close")
|
await events.once(this, "close");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1283,7 +1283,7 @@ async function handleHandshake(message, socket, req, attachHandler) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
connector.continue(socket, data.last_seq);
|
connector.continue(socket, data.last_seq);
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (stopAcceptingNewSessions) {
|
if (stopAcceptingNewSessions) {
|
||||||
@@ -1386,7 +1386,7 @@ async function loadPlugins(pluginInfos) {
|
|||||||
plugins.set(pluginInfo.name, masterPlugin);
|
plugins.set(pluginInfo.name, masterPlugin);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new errors.PluginError(pluginInfo.name, err)
|
throw new errors.PluginError(pluginInfo.name, err);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Clusterio | Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStarted}ms`);
|
console.log(`Clusterio | Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStarted}ms`);
|
||||||
@@ -1433,7 +1433,7 @@ function _setConfig(config) {
|
|||||||
* Returns the URL needed to connect to the master server.
|
* Returns the URL needed to connect to the master server.
|
||||||
*/
|
*/
|
||||||
function getMasterUrl() {
|
function getMasterUrl() {
|
||||||
let url = masterConfig.get("master.external_address")
|
let url = masterConfig.get("master.external_address");
|
||||||
if (!url) {
|
if (!url) {
|
||||||
if (masterConfig.get("master.https_port")) {
|
if (masterConfig.get("master.https_port")) {
|
||||||
url = `https://localhost:${masterConfig.get("master.https_port")}/`;
|
url = `https://localhost:${masterConfig.get("master.https_port")}/`;
|
||||||
@@ -1472,7 +1472,7 @@ async function startServer() {
|
|||||||
nargs: 1, default: "config-control.json",
|
nargs: 1, default: "config-control.json",
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.demandCommand(1, "You need to specify a command to run")
|
.demandCommand(1, "You need to specify a command to run");
|
||||||
})
|
})
|
||||||
.command("run", "Run master server")
|
.command("run", "Run master server")
|
||||||
.demandCommand(1, "You need to specify a command to run")
|
.demandCommand(1, "You need to specify a command to run")
|
||||||
@@ -1481,7 +1481,7 @@ async function startServer() {
|
|||||||
;
|
;
|
||||||
|
|
||||||
console.log("Loading Plugin info");
|
console.log("Loading Plugin info");
|
||||||
let pluginInfos = await plugin.loadPluginInfos("plugins")
|
let pluginInfos = await plugin.loadPluginInfos("plugins");
|
||||||
config.registerPluginConfigGroups(pluginInfos);
|
config.registerPluginConfigGroups(pluginInfos);
|
||||||
config.finalizeConfigs();
|
config.finalizeConfigs();
|
||||||
|
|
||||||
@@ -1554,7 +1554,7 @@ async function startServer() {
|
|||||||
|
|
||||||
// If we get here the command was run
|
// If we get here the command was run
|
||||||
|
|
||||||
let secondSigint = false
|
let secondSigint = false;
|
||||||
process.on("SIGINT", () => {
|
process.on("SIGINT", () => {
|
||||||
if (secondSigint) {
|
if (secondSigint) {
|
||||||
console.log("Caught second interrupt, terminating immediately");
|
console.log("Caught second interrupt, terminating immediately");
|
||||||
@@ -1624,7 +1624,7 @@ async function startServer() {
|
|||||||
httpsServer = require("https").createServer({
|
httpsServer = require("https").createServer({
|
||||||
key: privateKey,
|
key: privateKey,
|
||||||
cert: certificate
|
cert: certificate
|
||||||
}, app)
|
}, app);
|
||||||
await listen(httpsServer, httpsPort);
|
await listen(httpsServer, httpsPort);
|
||||||
console.log("Listening for HTTPS on port %s...", httpsServer.address().port);
|
console.log("Listening for HTTPS on port %s...", httpsServer.address().port);
|
||||||
}
|
}
|
||||||
@@ -1641,7 +1641,7 @@ module.exports = {
|
|||||||
_ControlConnection: ControlConnection,
|
_ControlConnection: ControlConnection,
|
||||||
_slaveConnections: slaveConnections,
|
_slaveConnections: slaveConnections,
|
||||||
_SlaveConnection: SlaveConnection,
|
_SlaveConnection: SlaveConnection,
|
||||||
}
|
};
|
||||||
|
|
||||||
if (module === require.main) {
|
if (module === require.main) {
|
||||||
console.warn(`
|
console.warn(`
|
||||||
|
|||||||
@@ -20,4 +20,4 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
@@ -57,4 +57,4 @@ module.exports = {
|
|||||||
|
|
||||||
// For testing only
|
// For testing only
|
||||||
_removeTags: removeTags,
|
_removeTags: removeTags,
|
||||||
}
|
};
|
||||||
@@ -62,6 +62,6 @@ describe("global_chat plugin", function() {
|
|||||||
}
|
}
|
||||||
assert(count > 0, "no lines were tested");
|
assert(count > 0, "no lines were tested");
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -77,4 +77,4 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
@@ -5,8 +5,8 @@ const luaTools = require("lib/luaTools");
|
|||||||
|
|
||||||
|
|
||||||
function unexpectedError(err) {
|
function unexpectedError(err) {
|
||||||
console.log("Unexpected error in research_sync")
|
console.log("Unexpected error in research_sync");
|
||||||
console.log("---------------------------------")
|
console.log("---------------------------------");
|
||||||
console.log(err);
|
console.log(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,4 +78,4 @@ class InstancePlugin extends plugin.BaseInstancePlugin {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
InstancePlugin,
|
InstancePlugin,
|
||||||
}
|
};
|
||||||
@@ -38,7 +38,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
broadcastProgress() {
|
broadcastProgress() {
|
||||||
let techs = []
|
let techs = [];
|
||||||
for (let name of this.progressToBroadcast) {
|
for (let name of this.progressToBroadcast) {
|
||||||
let tech = this.technologies.get(name);
|
let tech = this.technologies.get(name);
|
||||||
if (tech.progress) {
|
if (tech.progress) {
|
||||||
@@ -58,7 +58,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
let tech = this.technologies.get(name);
|
let tech = this.technologies.get(name);
|
||||||
if (!tech) {
|
if (!tech) {
|
||||||
tech = { level, progress: 0, researched: false };
|
tech = { level, progress: 0, researched: false };
|
||||||
this.technologies.set(name, tech)
|
this.technologies.set(name, tech);
|
||||||
|
|
||||||
// Ignore contribution to already researched technologies
|
// Ignore contribution to already researched technologies
|
||||||
} else if (tech.level > level || tech.level === level && tech.researched) {
|
} else if (tech.level > level || tech.level === level && tech.researched) {
|
||||||
@@ -96,7 +96,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
let tech = this.technologies.get(name);
|
let tech = this.technologies.get(name);
|
||||||
if (!tech || tech.level <= level) {
|
if (!tech || tech.level <= level) {
|
||||||
this.progressToBroadcast.delete(name);
|
this.progressToBroadcast.delete(name);
|
||||||
this.technologies.set(name, { level, progress: null, researched: true })
|
this.technologies.set(name, { level, progress: null, researched: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,10 +151,10 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
|
|
||||||
let technologies = [];
|
let technologies = [];
|
||||||
for (let [name, tech] of this.technologies) {
|
for (let [name, tech] of this.technologies) {
|
||||||
technologies.push([ name, tech.level, tech.progress, tech.researched ])
|
technologies.push([ name, tech.level, tech.progress, tech.researched ]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { technologies }
|
return { technologies };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,4 +184,4 @@ async function saveTechnologies(masterConfig, technologies) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
MasterPlugin
|
MasterPlugin
|
||||||
}
|
};
|
||||||
@@ -6,4 +6,4 @@ module.exports = {
|
|||||||
description: "Exports statistics to Prometheus",
|
description: "Exports statistics to Prometheus",
|
||||||
version: "2.0.0-alpha",
|
version: "2.0.0-alpha",
|
||||||
instanceEntrypoint: "instance",
|
instanceEntrypoint: "instance",
|
||||||
}
|
};
|
||||||
@@ -64,4 +64,4 @@ module.exports = {
|
|||||||
_instanceGameTicksTotal: instanceGameTicksTotal,
|
_instanceGameTicksTotal: instanceGameTicksTotal,
|
||||||
_instanceForceFlowStatistics: instanceForceFlowStatistics,
|
_instanceForceFlowStatistics: instanceForceFlowStatistics,
|
||||||
_instanceGameFlowStatistics: instanceGameFlowStatistics,
|
_instanceGameFlowStatistics: instanceGameFlowStatistics,
|
||||||
}
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const doleNN = require("./dole_nn_base")
|
const doleNN = require("./dole_nn_base");
|
||||||
|
|
||||||
const prometheus = require("lib/prometheus");
|
const prometheus = require("lib/prometheus");
|
||||||
|
|
||||||
@@ -32,13 +32,13 @@ class neuralDole {
|
|||||||
items
|
items
|
||||||
}){
|
}){
|
||||||
// Set some storage variables for the dole divider
|
// Set some storage variables for the dole divider
|
||||||
this.items = items
|
this.items = items;
|
||||||
this.itemsLastTick = new Map(items._items)
|
this.itemsLastTick = new Map(items._items);
|
||||||
this.dole = {}
|
this.dole = {};
|
||||||
this.carry = {}
|
this.carry = {};
|
||||||
this.lastRequest = {}
|
this.lastRequest = {};
|
||||||
this.stats=[]
|
this.stats=[];
|
||||||
this.debt= {}
|
this.debt= {};
|
||||||
}
|
}
|
||||||
doMagic() {
|
doMagic() {
|
||||||
for (let [name, count] of this.items._items) {
|
for (let [name, count] of this.items._items) {
|
||||||
@@ -47,16 +47,16 @@ class neuralDole {
|
|||||||
this.dole[name],
|
this.dole[name],
|
||||||
this.itemsLastTick.get(name),
|
this.itemsLastTick.get(name),
|
||||||
this.getRequestStats(name,5)
|
this.getRequestStats(name,5)
|
||||||
)
|
);
|
||||||
this.stats[name]=this.stats[name] || []
|
this.stats[name]=this.stats[name] || [];
|
||||||
this.stats[name].unshift({req:0,given:0});//stats[name][0] is the one we currently collect
|
this.stats[name].unshift({req:0,given:0});//stats[name][0] is the one we currently collect
|
||||||
if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats
|
if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats
|
||||||
|
|
||||||
this.dole[name] = magicData[0]
|
this.dole[name] = magicData[0];
|
||||||
// DONE handle magicData[1] for graphing for our users
|
// DONE handle magicData[1] for graphing for our users
|
||||||
prometheusNNDoleGauge.labels(name).set(magicData[1] || 0);
|
prometheusNNDoleGauge.labels(name).set(magicData[1] || 0);
|
||||||
}
|
}
|
||||||
this.itemsLastTick = new Map(this.items._items)
|
this.itemsLastTick = new Map(this.items._items);
|
||||||
}
|
}
|
||||||
divider(object) {
|
divider(object) {
|
||||||
let magicData = doleNN.Dose(
|
let magicData = doleNN.Dose(
|
||||||
@@ -68,19 +68,19 @@ class neuralDole {
|
|||||||
this.lastRequest[object.name+"_"+object.instanceID+"_"+object.instanceName] || 0,
|
this.lastRequest[object.name+"_"+object.instanceID+"_"+object.instanceName] || 0,
|
||||||
this.getRequestStats(object.name,5),
|
this.getRequestStats(object.name,5),
|
||||||
this.debt[object.name+" "+object.instanceID] || 0
|
this.debt[object.name+" "+object.instanceID] || 0
|
||||||
)
|
);
|
||||||
if ((this.stats[object.name] || []).length>0)
|
if ((this.stats[object.name] || []).length>0)
|
||||||
{
|
{
|
||||||
this.stats[object.name][0].req+=Number(object.count);
|
this.stats[object.name][0].req+=Number(object.count);
|
||||||
this.stats[object.name][0].given+=Number(magicData[0]);
|
this.stats[object.name][0].given+=Number(magicData[0]);
|
||||||
}
|
}
|
||||||
this.lastRequest[object.name+"_"+object.instanceID+"_"+object.instanceName] = object.count
|
this.lastRequest[object.name+"_"+object.instanceID+"_"+object.instanceName] = object.count;
|
||||||
//0.Number of items to give in that dose
|
//0.Number of items to give in that dose
|
||||||
//1.New dole for item X
|
//1.New dole for item X
|
||||||
//2.New carry for item X slave Y
|
//2.New carry for item X slave Y
|
||||||
this.dole[object.name] = magicData[1]
|
this.dole[object.name] = magicData[1];
|
||||||
this.carry[object.name+" "+object.instanceID] = magicData[2]
|
this.carry[object.name+" "+object.instanceID] = magicData[2];
|
||||||
this.debt[object.name+" "+object.instanceID] = magicData[3]
|
this.debt[object.name+" "+object.instanceID] = magicData[3];
|
||||||
|
|
||||||
// Remove item from DB and send it
|
// Remove item from DB and send it
|
||||||
this.items.removeItem(object.name, magicData[0]);
|
this.items.removeItem(object.name, magicData[0]);
|
||||||
@@ -111,7 +111,7 @@ function doleDivider({
|
|||||||
if (itemCount > object.count) {
|
if (itemCount > object.count) {
|
||||||
//If successful, increase dole
|
//If successful, increase dole
|
||||||
_doleDivisionFactor[object.name] = Math.max((_doleDivisionFactor[object.name]||0)||1, 1) - 1;
|
_doleDivisionFactor[object.name] = Math.max((_doleDivisionFactor[object.name]||0)||1, 1) - 1;
|
||||||
items.removeItem(object.name, object.count)
|
items.removeItem(object.name, object.count);
|
||||||
|
|
||||||
prometheusDoleFactorGauge.labels(object.name).set(_doleDivisionFactor[object.name] || 0);
|
prometheusDoleFactorGauge.labels(object.name).set(_doleDivisionFactor[object.name] || 0);
|
||||||
return object.count;
|
return object.count;
|
||||||
@@ -127,4 +127,4 @@ function doleDivider({
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
doleDivider,
|
doleDivider,
|
||||||
neuralDole
|
neuralDole
|
||||||
}
|
};
|
||||||
@@ -7,17 +7,17 @@ function sigmoid0(x)
|
|||||||
function sigmoid1(x)
|
function sigmoid1(x)
|
||||||
{
|
{
|
||||||
if (x>=0.0) {
|
if (x>=0.0) {
|
||||||
return 1.0
|
return 1.0;
|
||||||
} else {
|
} else {
|
||||||
return 0.0
|
return 0.0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function sigmoid2(x)
|
function sigmoid2(x)
|
||||||
{
|
{
|
||||||
if (x>=0.0){
|
if (x>=0.0){
|
||||||
return x
|
return x;
|
||||||
} else {
|
} else {
|
||||||
return 0.0
|
return 0.0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function sigmoid3(x)
|
function sigmoid3(x)
|
||||||
@@ -116,4 +116,4 @@ outputs[1]=sigmoid3(outputs[1]);
|
|||||||
return [sigmoid0(outputs[0]),avg];
|
return [sigmoid0(outputs[0]),avg];
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {Dose,Tick}
|
module.exports = {Dose,Tick};
|
||||||
@@ -50,7 +50,7 @@ const items = {
|
|||||||
{ type: "integer" },
|
{ type: "integer" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
name: "subspace_storage",
|
name: "subspace_storage",
|
||||||
@@ -103,4 +103,4 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
@@ -4,8 +4,8 @@ const plugin = require("lib/plugin");
|
|||||||
const luaTools = require("lib/luaTools");
|
const luaTools = require("lib/luaTools");
|
||||||
|
|
||||||
function unexpectedError(err) {
|
function unexpectedError(err) {
|
||||||
console.log("Unexpected error in subspace_storage")
|
console.log("Unexpected error in subspace_storage");
|
||||||
console.log("------------------------------------")
|
console.log("------------------------------------");
|
||||||
console.log(err);
|
console.log(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ class InstancePlugin extends plugin.BaseInstancePlugin {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
||||||
console.log("Exported the following to master:")
|
console.log("Exported the following to master:");
|
||||||
console.log(items);
|
console.log(items);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,7 @@ class InstancePlugin extends plugin.BaseInstancePlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
if (this.instance.config.get("subspace_storage.log_item_transfers")) {
|
||||||
console.log("Imported following from master:")
|
console.log("Imported following from master:");
|
||||||
console.log(response.items);
|
console.log(response.items);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,8 +47,8 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
this.itemsLastUpdate = new Map(this.items._items.entries());
|
this.itemsLastUpdate = new Map(this.items._items.entries());
|
||||||
this.autosaveId = setInterval(() => {
|
this.autosaveId = setInterval(() => {
|
||||||
saveDatabase(this.master.config, this.items).catch(err => {
|
saveDatabase(this.master.config, this.items).catch(err => {
|
||||||
console.log("Unexpected error autosaving items in subspace_storage")
|
console.log("Unexpected error autosaving items in subspace_storage");
|
||||||
console.log("-----------------------------------------------------")
|
console.log("-----------------------------------------------------");
|
||||||
console.log(err);
|
console.log(err);
|
||||||
});
|
});
|
||||||
}, this.master.config.get("subspace_storage.autosave_interval") * 1000);
|
}, this.master.config.get("subspace_storage.autosave_interval") * 1000);
|
||||||
@@ -56,7 +56,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
this.neuralDole = new dole.neuralDole({ items: this.items });
|
this.neuralDole = new dole.neuralDole({ items: this.items });
|
||||||
this.doleMagicId = setInterval(() => {
|
this.doleMagicId = setInterval(() => {
|
||||||
if (this.master.config.get("subspace_storage.division_method") === "neural_dole") {
|
if (this.master.config.get("subspace_storage.division_method") === "neural_dole") {
|
||||||
this.neuralDole.doMagic()
|
this.neuralDole.doMagic();
|
||||||
}
|
}
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
this.updateStorage();
|
this.updateStorage();
|
||||||
|
|
||||||
if (this.master.config.get("subspace_storage.log_item_transfers")) {
|
if (this.master.config.get("subspace_storage.log_item_transfers")) {
|
||||||
console.log(`Imported the following from ${message.data.instance_id}:`)
|
console.log(`Imported the following from ${message.data.instance_id}:`);
|
||||||
console.log(message.data.items);
|
console.log(message.data.items);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,7 +166,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
items: itemsRemoved,
|
items: itemsRemoved,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
onMetrics() {
|
onMetrics() {
|
||||||
|
|||||||
@@ -53,4 +53,4 @@ function addApiRoutes(app, items, endpointHitCounter) {
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
addWebRoutes,
|
addWebRoutes,
|
||||||
addApiRoutes,
|
addApiRoutes,
|
||||||
}
|
};
|
||||||
@@ -11,7 +11,7 @@ function drawcontents(data) {
|
|||||||
const search = new RegExp(searchArgs, "i");
|
const search = new RegExp(searchArgs, "i");
|
||||||
data = data.filter(function(item) {
|
data = data.filter(function(item) {
|
||||||
return search.test(item.name);
|
return search.test(item.name);
|
||||||
})
|
});
|
||||||
|
|
||||||
sortByKey(data, "count");
|
sortByKey(data, "count");
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ function updateInventory() {
|
|||||||
let data = JSON.parse(xmlhttp.responseText);
|
let data = JSON.parse(xmlhttp.responseText);
|
||||||
drawcontents(data);
|
drawcontents(data);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
xmlhttp.open("GET", `${root}api/inventory`, true);
|
xmlhttp.open("GET", `${root}api/inventory`, true);
|
||||||
xmlhttp.send();
|
xmlhttp.send();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ describe("subspace_storage endpoints", function() {
|
|||||||
inventory.forEach(itemStack => {
|
inventory.forEach(itemStack => {
|
||||||
if(itemStack.name == "steel-plate" && itemStack.count >= 20) contains20SteelPlate = true;
|
if(itemStack.name == "steel-plate" && itemStack.count >= 20) contains20SteelPlate = true;
|
||||||
});
|
});
|
||||||
assert(contains20SteelPlate, "Please ensure there are at least 20 steel plate in the inventory")
|
assert(contains20SteelPlate, "Please ensure there are at least 20 steel plate in the inventory");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -69,7 +69,7 @@ function applyAsConfig(name) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`Error applying server setting ${name}`, err);
|
console.error(`Error applying server setting ${name}`, err);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const serverSettingsActions = {
|
const serverSettingsActions = {
|
||||||
@@ -139,10 +139,10 @@ class Instance extends link.Link{
|
|||||||
this.server.sendRcon = (...args) => {
|
this.server.sendRcon = (...args) => {
|
||||||
instanceRconCommandsCounter.labels(String(this.config.get("instance.id"))).inc();
|
instanceRconCommandsCounter.labels(String(this.config.get("instance.id"))).inc();
|
||||||
return originalSendRcon.call(this.server, ...args);
|
return originalSendRcon.call(this.server, ...args);
|
||||||
}
|
};
|
||||||
|
|
||||||
this.server.on("output", (output) => {
|
this.server.on("output", (output) => {
|
||||||
link.messages.instanceOutput.send(this, { instance_id: this.config.get("instance.id"), output })
|
link.messages.instanceOutput.send(this, { instance_id: this.config.get("instance.id"), output });
|
||||||
|
|
||||||
plugin.invokeHook(this.plugins, "onOutput", output);
|
plugin.invokeHook(this.plugins, "onOutput", output);
|
||||||
});
|
});
|
||||||
@@ -225,7 +225,7 @@ class Instance extends link.Link{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let plugins = {}
|
let plugins = {};
|
||||||
for (let [name, plugin] of this.plugins) {
|
for (let [name, plugin] of this.plugins) {
|
||||||
plugins[name] = plugin.info.version;
|
plugins[name] = plugin.info.version;
|
||||||
}
|
}
|
||||||
@@ -326,7 +326,7 @@ class Instance extends link.Link{
|
|||||||
|
|
||||||
// Create save if no save was found.
|
// Create save if no save was found.
|
||||||
if (saveName === null) {
|
if (saveName === null) {
|
||||||
console.log("Clusterio | Creating new save")
|
console.log("Clusterio | Creating new save");
|
||||||
await this.server.create("world.zip");
|
await this.server.create("world.zip");
|
||||||
saveName = "world.zip";
|
saveName = "world.zip";
|
||||||
}
|
}
|
||||||
@@ -408,7 +408,7 @@ class Instance extends link.Link{
|
|||||||
|
|
||||||
this.server.on("exit", () => this.notifyExit());
|
this.server.on("exit", () => this.notifyExit());
|
||||||
await this.server.start(saveName);
|
await this.server.start(saveName);
|
||||||
await this.server.disableAchievements()
|
await this.server.disableAchievements();
|
||||||
await this.updateInstanceData();
|
await this.updateInstanceData();
|
||||||
|
|
||||||
await plugin.invokeHook(this.plugins, "onStart");
|
await plugin.invokeHook(this.plugins, "onStart");
|
||||||
@@ -459,12 +459,12 @@ class Instance extends link.Link{
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getMetricsRequestHandler() {
|
async getMetricsRequestHandler() {
|
||||||
let results = []
|
let results = [];
|
||||||
if (this._running) {
|
if (this._running) {
|
||||||
let pluginResults = await plugin.invokeHook(this.plugins, "onMetrics");
|
let pluginResults = await plugin.invokeHook(this.plugins, "onMetrics");
|
||||||
for (let metricIterator of pluginResults) {
|
for (let metricIterator of pluginResults) {
|
||||||
for await (let metric of metricIterator) {
|
for await (let metric of metricIterator) {
|
||||||
results.push(prometheus.serializeResult(metric))
|
results.push(prometheus.serializeResult(metric));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -482,7 +482,7 @@ class Instance extends link.Link{
|
|||||||
async startInstanceRequestHandler(message) {
|
async startInstanceRequestHandler(message) {
|
||||||
let saveName = message.data.save;
|
let saveName = message.data.save;
|
||||||
try {
|
try {
|
||||||
saveName = await this.prepare(saveName)
|
saveName = await this.prepare(saveName);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.notifyExit();
|
this.notifyExit();
|
||||||
throw err;
|
throw err;
|
||||||
@@ -536,7 +536,7 @@ class Instance extends link.Link{
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (response.statusCode !== 200) {
|
if (response.statusCode !== 200) {
|
||||||
throw Error(`Upload failed: ${response.statusCode} ${response.statusMessage}: ${response.body}`)
|
throw Error(`Upload failed: ${response.statusCode} ${response.statusMessage}: ${response.body}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
@@ -750,7 +750,7 @@ class Slave extends link.Link {
|
|||||||
setBlocking(true);
|
setBlocking(true);
|
||||||
console.error("ERROR: Unexpected error during shutdown");
|
console.error("ERROR: Unexpected error during shutdown");
|
||||||
console.error(err);
|
console.error(err);
|
||||||
process.exit(1)
|
process.exit(1);
|
||||||
});
|
});
|
||||||
});;
|
});;
|
||||||
});
|
});
|
||||||
@@ -769,7 +769,7 @@ class Slave extends link.Link {
|
|||||||
setBlocking(true);
|
setBlocking(true);
|
||||||
console.error("ERROR: Unexpected error during shutdown");
|
console.error("ERROR: Unexpected error during shutdown");
|
||||||
console.error(err);
|
console.error(err);
|
||||||
process.exit(1)
|
process.exit(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -779,7 +779,7 @@ class Slave extends link.Link {
|
|||||||
setBlocking(true);
|
setBlocking(true);
|
||||||
console.error("ERROR: Unexpected error during shutdown");
|
console.error("ERROR: Unexpected error during shutdown");
|
||||||
console.error(err);
|
console.error(err);
|
||||||
process.exit(1)
|
process.exit(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -795,7 +795,7 @@ class Slave extends link.Link {
|
|||||||
|
|
||||||
async _findNewInstanceDir(name) {
|
async _findNewInstanceDir(name) {
|
||||||
try {
|
try {
|
||||||
checkFilename(name)
|
checkFilename(name);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(`Instance name ${err.message}`);
|
throw new Error(`Instance name ${err.message}`);
|
||||||
}
|
}
|
||||||
@@ -821,7 +821,7 @@ class Slave extends link.Link {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (request.plugin && !instanceConnection.plugins.has(request.plugin)) {
|
if (request.plugin && !instanceConnection.plugins.has(request.plugin)) {
|
||||||
throw new errors.RequestError(`Instance ID ${instanceId} does not have ${request.plugin} plugin loaded`)
|
throw new errors.RequestError(`Instance ID ${instanceId} does not have ${request.plugin} plugin loaded`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await request.send(instanceConnection, message.data);
|
return await request.send(instanceConnection, message.data);
|
||||||
@@ -1210,7 +1210,7 @@ async function startSlave() {
|
|||||||
let slave = new Slave(slaveConnector, slaveConfig, pluginInfos);
|
let slave = new Slave(slaveConnector, slaveConfig, pluginInfos);
|
||||||
|
|
||||||
// Handle interrupts
|
// Handle interrupts
|
||||||
let secondSigint = false
|
let secondSigint = false;
|
||||||
process.on("SIGINT", () => {
|
process.on("SIGINT", () => {
|
||||||
if (secondSigint) {
|
if (secondSigint) {
|
||||||
console.log("Caught second interrupt, terminating immediately");
|
console.log("Caught second interrupt, terminating immediately");
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ async function exec(...args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function sendRcon(instanceId, command) {
|
async function sendRcon(instanceId, command) {
|
||||||
let response = await link.messages.sendRcon.send(control, { instance_id: instanceId, command })
|
let response = await link.messages.sendRcon.send(control, { instance_id: instanceId, command });
|
||||||
return response.result;
|
return response.result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,8 +86,8 @@ function spawn(name, cmd, waitFor) {
|
|||||||
resolve(process);
|
resolve(process);
|
||||||
}
|
}
|
||||||
console.log(name, line);
|
console.log(name, line);
|
||||||
})
|
});
|
||||||
let stderr = new server._LineSplitter((line) => { console.log(name, line.toString("utf8")); })
|
let stderr = new server._LineSplitter((line) => { console.log(name, line.toString("utf8")); });
|
||||||
process.stdout.on("data", chunk => { stdout.data(chunk); });
|
process.stdout.on("data", chunk => { stdout.data(chunk); });
|
||||||
process.stdout.on("close", () => { stdout.end(); });
|
process.stdout.on("close", () => { stdout.end(); });
|
||||||
process.stderr.on("data", chunk => { stderr.data(chunk); });
|
process.stderr.on("data", chunk => { stderr.data(chunk); });
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const { slowTest } = require("./index");
|
|||||||
|
|
||||||
|
|
||||||
// The server integration test is required to run before this one
|
// The server integration test is required to run before this one
|
||||||
require("./server")
|
require("./server");
|
||||||
|
|
||||||
describe("Integration of lib/factorio/patch", function() {
|
describe("Integration of lib/factorio/patch", function() {
|
||||||
describe("patch()", function() {
|
describe("patch()", function() {
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ describe("Integration of lib/factorio/server", function() {
|
|||||||
slowTest(this);
|
slowTest(this);
|
||||||
log(".startScenario()");
|
log(".startScenario()");
|
||||||
|
|
||||||
let pass = false
|
let pass = false;
|
||||||
function filter(output) {
|
function filter(output) {
|
||||||
if (output.message === "test_scenario init") {
|
if (output.message === "test_scenario init") {
|
||||||
pass = true;
|
pass = true;
|
||||||
|
|||||||
+19
-19
@@ -97,13 +97,13 @@ describe("lib/config/classes", function() {
|
|||||||
enum: ["a", "b", "c"],
|
enum: ["a", "b", "c"],
|
||||||
optional: true,
|
optional: true,
|
||||||
initial_value: "b",
|
initial_value: "b",
|
||||||
}
|
};
|
||||||
TestGroup.define(field);
|
TestGroup.define(field);
|
||||||
// Generated properties
|
// Generated properties
|
||||||
field.fullName = "test_group.enum";
|
field.fullName = "test_group.enum";
|
||||||
|
|
||||||
assert.deepEqual(TestGroup._definitions.get("enum"), field);
|
assert.deepEqual(TestGroup._definitions.get("enum"), field);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("get definitions", function() {
|
describe("get definitions", function() {
|
||||||
@@ -191,7 +191,7 @@ describe("lib/config/classes", function() {
|
|||||||
func: 22,
|
func: 22,
|
||||||
bool: null,
|
bool: null,
|
||||||
json: { valid: true },
|
json: { valid: true },
|
||||||
}})
|
}});
|
||||||
|
|
||||||
assert.equal(testInstance.get("enum"), "c");
|
assert.equal(testInstance.get("enum"), "c");
|
||||||
assert.equal(testInstance.get("test"), "blah");
|
assert.equal(testInstance.get("test"), "blah");
|
||||||
@@ -218,7 +218,7 @@ describe("lib/config/classes", function() {
|
|||||||
alpha: null,
|
alpha: null,
|
||||||
beta: "decay",
|
beta: "decay",
|
||||||
gamma: 99,
|
gamma: 99,
|
||||||
}
|
};
|
||||||
|
|
||||||
let testInstance = new TestGroup();
|
let testInstance = new TestGroup();
|
||||||
await testInstance.load(null, { name: "test_group", fields: testFields });
|
await testInstance.load(null, { name: "test_group", fields: testFields });
|
||||||
@@ -277,43 +277,43 @@ describe("lib/config/classes", function() {
|
|||||||
() => testInstance.set("bar", 1),
|
() => testInstance.set("bar", 1),
|
||||||
new classes.InvalidField("No field named 'bar'")
|
new classes.InvalidField("No field named 'bar'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw if field is not in enum", function() {
|
it("should throw if field is not in enum", function() {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => testInstance.set("enum", "bar"),
|
() => testInstance.set("enum", "bar"),
|
||||||
new Error("Expected one of [a, b, c], not bar")
|
new Error("Expected one of [a, b, c], not bar")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should work if field is in enum", function() {
|
it("should work if field is in enum", function() {
|
||||||
testInstance.set("enum", "c"),
|
testInstance.set("enum", "c"),
|
||||||
assert.equal(testInstance.get("enum"), "c");
|
assert.equal(testInstance.get("enum"), "c");
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw if field is not optional", function() {
|
it("should throw if field is not optional", function() {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => testInstance.set("func", null),
|
() => testInstance.set("func", null),
|
||||||
new Error("Field func cannot be null")
|
new Error("Field func cannot be null")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should work if field is optional", function() {
|
it("should work if field is optional", function() {
|
||||||
testInstance.set("test", "spam"),
|
testInstance.set("test", "spam"),
|
||||||
assert.equal(testInstance.get("test"), "spam");
|
assert.equal(testInstance.get("test"), "spam");
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw if field is of wrong type", function() {
|
it("should throw if field is of wrong type", function() {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => testInstance.set("test", 1),
|
() => testInstance.set("test", 1),
|
||||||
new Error("Expected type of test to be string, not number")
|
new Error("Expected type of test to be string, not number")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should treat empty string as null", function() {
|
it("should treat empty string as null", function() {
|
||||||
testInstance.set("test", ""),
|
testInstance.set("test", ""),
|
||||||
assert.equal(testInstance.get("test"), null);
|
assert.equal(testInstance.get("test"), null);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should auto convert string to boolean if possible", function() {
|
it("should auto convert string to boolean if possible", function() {
|
||||||
testInstance.set("bool", "true");
|
testInstance.set("bool", "true");
|
||||||
@@ -374,14 +374,14 @@ describe("lib/config/classes", function() {
|
|||||||
() => testInstance.setProp("bar", 1),
|
() => testInstance.setProp("bar", 1),
|
||||||
new classes.InvalidField("No field named 'bar'")
|
new classes.InvalidField("No field named 'bar'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw if field is not an object", function() {
|
it("should throw if field is not an object", function() {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => testInstance.setProp("enum", "a"),
|
() => testInstance.setProp("enum", "a"),
|
||||||
new classes.InvalidField("Cannot set property on non-object field 'enum'")
|
new classes.InvalidField("Cannot set property on non-object field 'enum'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should work if field is an object", function() {
|
it("should work if field is an object", function() {
|
||||||
testInstance.set("json", { prev: 32, test: false });
|
testInstance.set("json", { prev: 32, test: false });
|
||||||
@@ -461,7 +461,7 @@ describe("lib/config/classes", function() {
|
|||||||
await testInstance.init();
|
await testInstance.init();
|
||||||
assert.equal(testInstance.get("alpha.foo"), null);
|
assert.equal(testInstance.get("alpha.foo"), null);
|
||||||
assert.deepEqual(testInstance.get("beta.bar"), {});
|
assert.deepEqual(testInstance.get("beta.bar"), {});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe(".serialize()", function() {
|
describe(".serialize()", function() {
|
||||||
@@ -480,7 +480,7 @@ describe("lib/config/classes", function() {
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe(".load()", function() {
|
describe(".load()", function() {
|
||||||
@@ -522,7 +522,7 @@ describe("lib/config/classes", function() {
|
|||||||
name: "beta",
|
name: "beta",
|
||||||
fields: { bar: { value: 20 }},
|
fields: { bar: { value: 20 }},
|
||||||
}
|
}
|
||||||
]
|
];
|
||||||
|
|
||||||
let testInstance = new TestConfig();
|
let testInstance = new TestConfig();
|
||||||
await testInstance.load({ groups: testGroups });
|
await testInstance.load({ groups: testGroups });
|
||||||
@@ -562,7 +562,7 @@ describe("lib/config/classes", function() {
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe(".group()", function() {
|
describe(".group()", function() {
|
||||||
@@ -580,14 +580,14 @@ describe("lib/config/classes", function() {
|
|||||||
let testInstance = new TestConfig();
|
let testInstance = new TestConfig();
|
||||||
await testInstance.init();
|
await testInstance.init();
|
||||||
|
|
||||||
assert.throws(() => testInstance.get("invalid"), new Error("No config group named 'invalid'"))
|
assert.throws(() => testInstance.get("invalid"), new Error("No config group named 'invalid'"));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw if no field is specified", async function() {
|
it("should throw if no field is specified", async function() {
|
||||||
let testInstance = new TestConfig();
|
let testInstance = new TestConfig();
|
||||||
await testInstance.init();
|
await testInstance.init();
|
||||||
|
|
||||||
assert.throws(() => testInstance.get("alpha"), new Error("No field named ''"))
|
assert.throws(() => testInstance.get("alpha"), new Error("No field named ''"));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -228,13 +228,13 @@ describe("lib/database", function() {
|
|||||||
let items = new database.ItemDatabase();
|
let items = new database.ItemDatabase();
|
||||||
items.addItem("a", 10);
|
items.addItem("a", 10);
|
||||||
assert.deepEqual(items._items, new Map([["a", 10]]));
|
assert.deepEqual(items._items, new Map([["a", 10]]));
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should add an existing item", function() {
|
it("should add an existing item", function() {
|
||||||
let items = new database.ItemDatabase({"a": 10});
|
let items = new database.ItemDatabase({"a": 10});
|
||||||
items.addItem("a", 10);
|
items.addItem("a", 10);
|
||||||
assert.deepEqual(items._items, new Map([["a", 20]]));
|
assert.deepEqual(items._items, new Map([["a", 20]]));
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw on invalid name", function() {
|
it("should throw on invalid name", function() {
|
||||||
let items = new database.ItemDatabase();
|
let items = new database.ItemDatabase();
|
||||||
@@ -262,13 +262,13 @@ describe("lib/database", function() {
|
|||||||
let items = new database.ItemDatabase({"a": 20});
|
let items = new database.ItemDatabase({"a": 20});
|
||||||
items.removeItem("a", 10);
|
items.removeItem("a", 10);
|
||||||
assert.deepEqual(items._items, new Map([["a", 10]]));
|
assert.deepEqual(items._items, new Map([["a", 10]]));
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should turn a non-existing item negative", function() {
|
it("should turn a non-existing item negative", function() {
|
||||||
let items = new database.ItemDatabase();
|
let items = new database.ItemDatabase();
|
||||||
items.removeItem("a", 10);
|
items.removeItem("a", 10);
|
||||||
assert.deepEqual(items._items, new Map([["a", -10]]));
|
assert.deepEqual(items._items, new Map([["a", -10]]));
|
||||||
})
|
});
|
||||||
|
|
||||||
it("should throw on invalid name", function() {
|
it("should throw on invalid name", function() {
|
||||||
let items = new database.ItemDatabase();
|
let items = new database.ItemDatabase();
|
||||||
|
|||||||
@@ -142,8 +142,8 @@ let testLines = new Map([
|
|||||||
message: "Saving finished",
|
message: "Saving finished",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
])
|
]);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
testLines,
|
testLines,
|
||||||
}
|
};
|
||||||
@@ -213,7 +213,7 @@ describe("lib/factorio", function() {
|
|||||||
let zip = new jszip();
|
let zip = new jszip();
|
||||||
zip.file("world/control.lua", "-- unknown\n");
|
zip.file("world/control.lua", "-- unknown\n");
|
||||||
let zipPath = path.join("temp", "test", "patch.zip");
|
let zipPath = path.join("temp", "test", "patch.zip");
|
||||||
await fs.outputFile(zipPath, await zip.generateAsync({type: "nodebuffer"}))
|
await fs.outputFile(zipPath, await zip.generateAsync({type: "nodebuffer"}));
|
||||||
|
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
factorio.patch(zipPath, []),
|
factorio.patch(zipPath, []),
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ describe("lib/factorio/server", function() {
|
|||||||
|
|
||||||
describe("randomDynamicPort()", function() {
|
describe("randomDynamicPort()", function() {
|
||||||
it("should return a port number", function() {
|
it("should return a port number", function() {
|
||||||
let port = factorio._randomDynamicPort()
|
let port = factorio._randomDynamicPort();
|
||||||
assert.equal(typeof port, "number");
|
assert.equal(typeof port, "number");
|
||||||
assert(Number.isInteger(port));
|
assert(Number.isInteger(port));
|
||||||
assert(0 <= port && port < 2**16);
|
assert(0 <= port && port < 2**16);
|
||||||
@@ -203,25 +203,25 @@ describe("lib/factorio/server", function() {
|
|||||||
server._handleIpc(Buffer.from("\f$ipc:blah")),
|
server._handleIpc(Buffer.from("\f$ipc:blah")),
|
||||||
new Error('Malformed IPC line "\f$ipc:blah"')
|
new Error('Malformed IPC line "\f$ipc:blah"')
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
it("should throw on unknown type", async function() {
|
it("should throw on unknown type", async function() {
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
server._handleIpc(Buffer.from("\f$ipc:channel??")),
|
server._handleIpc(Buffer.from("\f$ipc:channel??")),
|
||||||
new Error("Unknown IPC type '?'")
|
new Error("Unknown IPC type '?'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
it("should throw on unknown file type", async function() {
|
it("should throw on unknown file type", async function() {
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
server._handleIpc(Buffer.from("\f$ipc:channel?ffoo.invalid")),
|
server._handleIpc(Buffer.from("\f$ipc:channel?ffoo.invalid")),
|
||||||
new Error("Unknown IPC file format 'invalid'")
|
new Error("Unknown IPC file format 'invalid'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
it("should throw on file name with slash", async function() {
|
it("should throw on file name with slash", async function() {
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
server._handleIpc(Buffer.from("\f$ipc:channel?fa/b")),
|
server._handleIpc(Buffer.from("\f$ipc:channel?fa/b")),
|
||||||
new Error("Invalid IPC file name 'a/b'")
|
new Error("Invalid IPC file name 'a/b'")
|
||||||
);
|
);
|
||||||
})
|
});
|
||||||
it("should load and delete json file", async function() {
|
it("should load and delete json file", async function() {
|
||||||
let filePath = server.writePath("script-output", "data.json");
|
let filePath = server.writePath("script-output", "data.json");
|
||||||
await fs.outputFile(filePath, '{"data":"spam"}');
|
await fs.outputFile(filePath, '{"data":"spam"}');
|
||||||
@@ -230,7 +230,7 @@ describe("lib/factorio/server", function() {
|
|||||||
let result = await waiter;
|
let result = await waiter;
|
||||||
assert.deepEqual(result[0], { "data": "spam" });
|
assert.deepEqual(result[0], { "data": "spam" });
|
||||||
assert(!await fs.pathExists(filePath), "File was not deleted");
|
assert(!await fs.pathExists(filePath), "File was not deleted");
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -2,7 +2,7 @@ const assert = require("assert");
|
|||||||
const fs = require("fs-extra");
|
const fs = require("fs-extra");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const generateSSLcert = require("lib/generateSSLcert")
|
const generateSSLcert = require("lib/generateSSLcert");
|
||||||
|
|
||||||
describe("generateSSLcert.js(options)", ()=>{
|
describe("generateSSLcert.js(options)", ()=>{
|
||||||
let testDir = path.join("temp", "test", "certTest");
|
let testDir = path.join("temp", "test", "certTest");
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ describe("lib/link/link", function() {
|
|||||||
describe("._processHandler()", function() {
|
describe("._processHandler()", function() {
|
||||||
it("should call the handler", function() {
|
it("should call the handler", function() {
|
||||||
let handled = [];
|
let handled = [];
|
||||||
testLink.setHandler("handled", (message) => handled.push(message), (message) => true)
|
testLink.setHandler("handled", (message) => handled.push(message), (message) => true);
|
||||||
testLink._processHandler({ seq: 1, type: "handled", data: { test: "foo" } });
|
testLink._processHandler({ seq: 1, type: "handled", data: { test: "foo" } });
|
||||||
assert.deepEqual(handled, [{ seq: 1, type: "handled", data: { test: "foo" } }]);
|
assert.deepEqual(handled, [{ seq: 1, type: "handled", data: { test: "foo" } }]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -163,6 +163,6 @@ describe("lib/link/messages", function() {
|
|||||||
describe("attachAllMessages()", function() {
|
describe("attachAllMessages()", function() {
|
||||||
it("does not throw", function() {
|
it("does not throw", function() {
|
||||||
link.attachAllMessages(testSourceLink);
|
link.attachAllMessages(testSourceLink);
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+4
-4
@@ -14,7 +14,7 @@ describe("lib/plugin", function() {
|
|||||||
it("should be constructible", async function() {
|
it("should be constructible", async function() {
|
||||||
instancePlugin = new plugin.BaseInstancePlugin();
|
instancePlugin = new plugin.BaseInstancePlugin();
|
||||||
await instancePlugin.init();
|
await instancePlugin.init();
|
||||||
})
|
});
|
||||||
it("should define defaults for hooks", async function() {
|
it("should define defaults for hooks", async function() {
|
||||||
await instancePlugin.onMetrics();
|
await instancePlugin.onMetrics();
|
||||||
await instancePlugin.onStart();
|
await instancePlugin.onStart();
|
||||||
@@ -23,7 +23,7 @@ describe("lib/plugin", function() {
|
|||||||
await instancePlugin.onOutput({});
|
await instancePlugin.onOutput({});
|
||||||
instancePlugin.onMasterConnectionEvent("connect");
|
instancePlugin.onMasterConnectionEvent("connect");
|
||||||
await instancePlugin.onPrepareMasterDisconnect();
|
await instancePlugin.onPrepareMasterDisconnect();
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("class BaseMasterPlugin", function() {
|
describe("class BaseMasterPlugin", function() {
|
||||||
@@ -31,14 +31,14 @@ describe("lib/plugin", function() {
|
|||||||
it("should be constructible", async function() {
|
it("should be constructible", async function() {
|
||||||
masterPlugin = new plugin.BaseMasterPlugin();
|
masterPlugin = new plugin.BaseMasterPlugin();
|
||||||
await masterPlugin.init();
|
await masterPlugin.init();
|
||||||
})
|
});
|
||||||
it("should define defaults for hooks", async function() {
|
it("should define defaults for hooks", async function() {
|
||||||
await masterPlugin.onInstanceStatusChanged({}, "running", "initialized");
|
await masterPlugin.onInstanceStatusChanged({}, "running", "initialized");
|
||||||
await masterPlugin.onMetrics();
|
await masterPlugin.onMetrics();
|
||||||
await masterPlugin.onShutdown();
|
await masterPlugin.onShutdown();
|
||||||
masterPlugin.onSlaveConnectionEvent({}, "connect");
|
masterPlugin.onSlaveConnectionEvent({}, "connect");
|
||||||
await masterPlugin.onPrepareSlaveDisconnect({});
|
await masterPlugin.onPrepareSlaveDisconnect({});
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("loadPluginInfos()", function() {
|
describe("loadPluginInfos()", function() {
|
||||||
|
|||||||
+15
-15
@@ -8,7 +8,7 @@ describe("lib/prometheus", function() {
|
|||||||
let registry;
|
let registry;
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
registry = new prometheus.CollectorRegistry();
|
registry = new prometheus.CollectorRegistry();
|
||||||
})
|
});
|
||||||
|
|
||||||
describe(".register()", function() {
|
describe(".register()", function() {
|
||||||
it("should register a collector", function() {
|
it("should register a collector", function() {
|
||||||
@@ -208,7 +208,7 @@ describe("lib/prometheus", function() {
|
|||||||
name, "Help", { register: false }
|
name, "Help", { register: false }
|
||||||
),
|
),
|
||||||
new Error(`Invalid name '${name}'`)
|
new Error(`Invalid name '${name}'`)
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
it("should throw on invalid label names", function() {
|
it("should throw on invalid label names", function() {
|
||||||
@@ -218,7 +218,7 @@ describe("lib/prometheus", function() {
|
|||||||
"test", "Help", { register: false, labels: [name] }
|
"test", "Help", { register: false, labels: [name] }
|
||||||
),
|
),
|
||||||
new Error(`Invalid label '${name}'`)
|
new Error(`Invalid label '${name}'`)
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
it("should throw on missing name", function() {
|
it("should throw on missing name", function() {
|
||||||
@@ -336,7 +336,7 @@ describe("lib/prometheus", function() {
|
|||||||
gauge.labels("1", "3");
|
gauge.labels("1", "3");
|
||||||
gauge.labels("4", "6");
|
gauge.labels("4", "6");
|
||||||
gauge.removeAll({a: "1"});
|
gauge.removeAll({a: "1"});
|
||||||
assert(gauge._values.size <= 1, "Matching labels remained")
|
assert(gauge._values.size <= 1, "Matching labels remained");
|
||||||
assert(
|
assert(
|
||||||
gauge._values.has('a="4",b="6"'),
|
gauge._values.has('a="4",b="6"'),
|
||||||
"Non-matching label was removed"
|
"Non-matching label was removed"
|
||||||
@@ -351,10 +351,10 @@ describe("lib/prometheus", function() {
|
|||||||
it("should handle special characters", function() {
|
it("should handle special characters", function() {
|
||||||
let gauge = new prometheus.Gauge(
|
let gauge = new prometheus.Gauge(
|
||||||
"test", "Help", { register: false, labels: ["a", "b"] }
|
"test", "Help", { register: false, labels: ["a", "b"] }
|
||||||
)
|
);
|
||||||
gauge.labels('x\\\\\n\"\"\n\\', "2");
|
gauge.labels('x\\\\\n\"\"\n\\', "2");
|
||||||
gauge.removeAll({a: 'x\\\\\n\"\"\n\\'});
|
gauge.removeAll({a: 'x\\\\\n\"\"\n\\'});
|
||||||
assert(gauge._values.size === 0, "Matching labels remained")
|
assert(gauge._values.size === 0, "Matching labels remained");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe(".clear()", function() {
|
describe(".clear()", function() {
|
||||||
@@ -381,7 +381,7 @@ describe("lib/prometheus", function() {
|
|||||||
describe("processStartTimeSeconds", function() {
|
describe("processStartTimeSeconds", function() {
|
||||||
it("should give a close point in time", async function() {
|
it("should give a close point in time", async function() {
|
||||||
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
||||||
let results = []
|
let results = [];
|
||||||
let collector = prometheus.defaultCollectors.processStartTimeSeconds;
|
let collector = prometheus.defaultCollectors.processStartTimeSeconds;
|
||||||
for await (let result of collector.collect()) {
|
for await (let result of collector.collect()) {
|
||||||
results.push(result);
|
results.push(result);
|
||||||
@@ -401,7 +401,7 @@ describe("lib/prometheus", function() {
|
|||||||
describe("processCpuSecondsTotal", function() {
|
describe("processCpuSecondsTotal", function() {
|
||||||
it("should give a low value", async function() {
|
it("should give a low value", async function() {
|
||||||
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
||||||
let results = []
|
let results = [];
|
||||||
let collector = prometheus.defaultCollectors.processCpuSecondsTotal;
|
let collector = prometheus.defaultCollectors.processCpuSecondsTotal;
|
||||||
for await (let result of collector.collect()) {
|
for await (let result of collector.collect()) {
|
||||||
results.push(result);
|
results.push(result);
|
||||||
@@ -412,7 +412,7 @@ describe("lib/prometheus", function() {
|
|||||||
"collector did not give exactly one result"
|
"collector did not give exactly one result"
|
||||||
);
|
);
|
||||||
|
|
||||||
let value = results[0].samples.get("")
|
let value = results[0].samples.get("");
|
||||||
assert(
|
assert(
|
||||||
value < 5 && value > 0,
|
value < 5 && value > 0,
|
||||||
`process time is not between 0 and 5 seconds (${value})`
|
`process time is not between 0 and 5 seconds (${value})`
|
||||||
@@ -422,7 +422,7 @@ describe("lib/prometheus", function() {
|
|||||||
describe("processResidentMemoryBytes", function() {
|
describe("processResidentMemoryBytes", function() {
|
||||||
it("should give a low value", async function() {
|
it("should give a low value", async function() {
|
||||||
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
||||||
let results = []
|
let results = [];
|
||||||
let collector = prometheus.defaultCollectors.processResidentMemoryBytes;
|
let collector = prometheus.defaultCollectors.processResidentMemoryBytes;
|
||||||
for await (let result of collector.collect()) {
|
for await (let result of collector.collect()) {
|
||||||
results.push(result);
|
results.push(result);
|
||||||
@@ -433,7 +433,7 @@ describe("lib/prometheus", function() {
|
|||||||
"collector did not give exactly one result"
|
"collector did not give exactly one result"
|
||||||
);
|
);
|
||||||
|
|
||||||
let value = results[0].samples.get("")
|
let value = results[0].samples.get("");
|
||||||
assert(
|
assert(
|
||||||
value < 200e6 && value > 0,
|
value < 200e6 && value > 0,
|
||||||
`resident memory is not between 0 and 200 MB (${value})`
|
`resident memory is not between 0 and 200 MB (${value})`
|
||||||
@@ -443,7 +443,7 @@ describe("lib/prometheus", function() {
|
|||||||
describe("processHeapBytes", function() {
|
describe("processHeapBytes", function() {
|
||||||
it("should give a low value", async function() {
|
it("should give a low value", async function() {
|
||||||
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
this.skip(); // XXX Doesn't work in Clusterio's shared testing env
|
||||||
let results = []
|
let results = [];
|
||||||
let collector = prometheus.defaultCollectors.processHeapBytes;
|
let collector = prometheus.defaultCollectors.processHeapBytes;
|
||||||
for await (let result of collector.collect()) {
|
for await (let result of collector.collect()) {
|
||||||
results.push(result);
|
results.push(result);
|
||||||
@@ -454,7 +454,7 @@ describe("lib/prometheus", function() {
|
|||||||
"collector did not give exactly one result"
|
"collector did not give exactly one result"
|
||||||
);
|
);
|
||||||
|
|
||||||
let value = results[0].samples.get("")
|
let value = results[0].samples.get("");
|
||||||
assert(
|
assert(
|
||||||
value < 200e6 && value > 0,
|
value < 200e6 && value > 0,
|
||||||
`heap is not between 0 and 200 MB (${value})`
|
`heap is not between 0 and 200 MB (${value})`
|
||||||
@@ -533,7 +533,7 @@ describe("lib/prometheus", function() {
|
|||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
prometheus.serializeResult(deserializedResult),
|
prometheus.serializeResult(deserializedResult),
|
||||||
serializedResult
|
serializedResult
|
||||||
)
|
);
|
||||||
});
|
});
|
||||||
it("should support adding labels", function() {
|
it("should support adding labels", function() {
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
@@ -595,7 +595,7 @@ describe("lib/prometheus", function() {
|
|||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
prometheus.deserializeResult(serializedResult),
|
prometheus.deserializeResult(serializedResult),
|
||||||
deserializedResult
|
deserializedResult
|
||||||
)
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -66,10 +66,10 @@ class MockInstance extends link.Link {
|
|||||||
this.name = "test";
|
this.name = "test";
|
||||||
this.config = {
|
this.config = {
|
||||||
get: (name) => {
|
get: (name) => {
|
||||||
if (name === "instance.id") { return 7357 }
|
if (name === "instance.id") { return 7357; }
|
||||||
throw Error("Not implemented");
|
throw Error("Not implemented");
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -23,16 +23,16 @@ describe("Slave testing", function() {
|
|||||||
describe(".name", function() {
|
describe(".name", function() {
|
||||||
it("should give the name of the instance", function() {
|
it("should give the name of the instance", function() {
|
||||||
assert.equal(instance.name, "foo");
|
assert.equal(instance.name, "foo");
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe(".path()", function() {
|
describe(".path()", function() {
|
||||||
it("should give the path when called without arguments", function() {
|
it("should give the path when called without arguments", function() {
|
||||||
assert.equal(instance.path(), "dir");
|
assert.equal(instance.path(), "dir");
|
||||||
})
|
});
|
||||||
it("should join path with arguments", function() {
|
it("should join path with arguments", function() {
|
||||||
assert.equal(instance.path("bar"), path.join("dir", "bar"));
|
assert.equal(instance.path("bar"), path.join("dir", "bar"));
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -93,7 +93,7 @@ describe("Slave testing", function() {
|
|||||||
let discardingLogger = {
|
let discardingLogger = {
|
||||||
warning: function() { },
|
warning: function() { },
|
||||||
log: function() { },
|
log: function() { },
|
||||||
}
|
};
|
||||||
|
|
||||||
let instance;
|
let instance;
|
||||||
before(async function() {
|
before(async function() {
|
||||||
|
|||||||
Reference in new issue
Block a user