Refactor user and instance manager (#837)

* Refactor UserManager to use Datastore

* Rename lib.User to UserDetails also adds to/fromUserDetails

* Fix existing tests

* Add user class tests

* Add tests for finaliseUsers

* Move HostDetails to own file with tests

* Move InstanceDetails to its own file with tests

* Rename HostInfo and add tests

* Rename InstanceInfo and add tests

- Also changes the names of the host properties related to instances
- Also removes the need to specify the location of InstanceInfo

* Make json round trip test validate schema

* Add InstanceManager

* Fix lint errors

* Extra tests

* Add final test coverage

* Add one last test to InstanceManager

* Response to comments

* Use generator rather than return anonumous generator

Co-authored-by: Hornwitser <github@hornwitser.no>

* Fix lint issue with generator

---------

Co-authored-by: Hornwitser <github@hornwitser.no>
This commit is contained in:
Cooldude2606andHornwitser authored and GitHub committed 2026-03-01 23:04:37 +00:00
1 parent 5bea930d05
commit 2235294c59
60 files changed
+3371 -1227

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
import { Type, Static } from "@sinclair/typebox";
export default class HostDetails {
constructor(
/** Version of the host software. The controller may warn if there is a mismatch. */
public version: string,
/** Human-readable display name of the host. */
public name: string,
/** Unique numeric identifier for this host. */
public id: number,
/** Whether the host is currently connected to the controller. */
public connected: boolean,
/** Address from which the host has connected to the controller. */
public remoteAddress = "",
/** Public-facing IP address of the host, if available. */
public publicAddress: string = "",
/** Unix timestamp (sec) after which issued tokens are considered valid. */
public tokenValidAfter: number = 0,
/** Unix timestamp (ms) indicating when this record was last updated. */
public updatedAtMs = 0,
/** Flag indicating the host record has been removed on the controller. */
public isDeleted = false
) {}
static jsonSchema = Type.Object({
"version": Type.String(),
"name": Type.String(),
"id": Type.Integer(),
"connected": Type.Boolean(),
"remoteAddress": Type.Optional(Type.String()),
"publicAddress": Type.Optional(Type.String()),
"tokenValidAfter": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"isDeleted": Type.Optional(Type.Boolean()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(
json.version,
json.name,
json.id,
json.connected,
json.remoteAddress,
json.publicAddress,
json.tokenValidAfter,
json.updatedAtMs,
json.isDeleted
);
}
toJSON() {
const json = {
version: this.version,
name: this.name,
id: this.id,
connected: this.connected,
} as Static<typeof HostDetails.jsonSchema>;
if (this.remoteAddress !== "") {
json.remoteAddress = this.remoteAddress;
}
if (this.publicAddress !== "") {
json.publicAddress = this.publicAddress;
}
if (this.tokenValidAfter !== 0) {
json.tokenValidAfter = this.tokenValidAfter;
}
if (this.updatedAtMs !== 0) {
json.updatedAtMs = this.updatedAtMs;
}
if (this.isDeleted !== false) {
json.isDeleted = this.isDeleted;
}
return json;
}
}
+108
View File
@@ -0,0 +1,108 @@
import { Static, Type } from "@sinclair/typebox";
import { StringEnum } from "./composites";
import { TargetVersion, TargetVersionSchema } from "./version";
export const InstanceStatus = StringEnum([
"unknown",
"unassigned",
"stopped",
"starting",
"running",
"stopping",
"creating_save",
"exporting_data",
"deleted",
]);
/**
* Current status of the instance. One of:
* - `unknown`: Instance is assigned to a host but this host is currently
* not connected to the contreller.
* - `unassigned`: Instance is not assigned to a a host and exists only on
* the controller.
* - `stopped`: Instance is stopped.
* - `starting`: Instance is in the process of starting up.
* - `running`: Instance is running normally.
* - `stopping`: Instance is in the process of stopping.
* - `creating_save`: Instance is in the process of creating a save.
* - `exporting_data`: Instance is in the process of exporting game data.
* - `deleted`: Instance has been deleted.
*/
export type InstanceStatus = Static<typeof InstanceStatus>;
export default class InstanceDetails {
constructor(
public name: string,
public id: number,
public assignedHost: number | undefined,
public gamePort: number | undefined,
public status: InstanceStatus,
public factorioVersion: TargetVersion | undefined,
public startedAtMs = 0,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAtMs = 0,
public excludeFromStartAll = false
) {}
get isDeleted() {
return this.status === "deleted";
}
static jsonSchema = Type.Object({
"name": Type.String(),
"id": Type.Integer(),
"assignedHost": Type.Optional(Type.Integer()),
"gamePort": Type.Optional(Type.Integer()),
"status": StringEnum([
"unknown", "unassigned", "stopped", "starting", "running", "stopping",
"creating_save", "exporting_data", "deleted",
]),
"factorioVersion": Type.Optional(TargetVersionSchema),
"startedAtMs": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"excludeFromStartAll": Type.Optional(Type.Boolean()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(
json.name,
json.id,
json.assignedHost,
json.gamePort,
json.status,
json.factorioVersion,
json.startedAtMs,
json.updatedAtMs,
json.excludeFromStartAll
);
}
toJSON() {
const json = {
name: this.name,
id: this.id,
status: this.status,
} as Static<typeof InstanceDetails.jsonSchema>;
if (this.assignedHost !== undefined) {
json.assignedHost = this.assignedHost;
}
if (this.gamePort !== undefined) {
json.gamePort = this.gamePort;
}
if (this.factorioVersion !== undefined) {
json.factorioVersion = this.factorioVersion;
}
if (this.startedAtMs !== 0) {
json.startedAtMs = this.startedAtMs;
}
if (this.updatedAtMs !== 0) {
json.updatedAtMs = this.updatedAtMs;
}
if (this.excludeFromStartAll !== false) {
json.excludeFromStartAll = this.excludeFromStartAll;
}
return json;
}
}
@@ -2,12 +2,10 @@ import { Static, Type } from "@sinclair/typebox";
import PlayerStats from "./PlayerStats";
/**
* Represeents a user in the cluster
*
* Holds data about a Factorio user in the cluster.
*/
export default class User {
/** Represents a user in the cluster */
export default class UserDetails {
public playerStats: PlayerStats;
constructor(
/** Factorio user name. */
public name: string,
@@ -27,11 +25,15 @@ export default class User {
public updatedAtMs = 0,
/** True if this user object has been removed from the cluster. */
public isDeleted = false,
/** Combined statistics for the player this user account is tied to. */
public playerStats = new PlayerStats(),
/** Per instance statistics for the player this user account is tied to. */
public instanceStats = new Map<number, PlayerStats>(),
) {
this.playerStats = UserDetails._calculatePlayerStats(this.instanceStats);
}
/** Name of the user, used by event subscriptions and to ensure case insensitivity */
get id() {
return this.name.toLowerCase();
}
static jsonSchema = Type.Object({
@@ -51,17 +53,13 @@ export default class User {
),
});
static fromJSON(json: Static<typeof this.jsonSchema>, _hack?: any) {
const roleIds = new Set<number>(json.roles ?? []);
static fromJSON(json: Static<typeof this.jsonSchema>) {
const instanceStats = new Map(
(json.instance_stats ?? []).map(
([id, stats]) => [id, PlayerStats.fromJSON(stats)]
)
(json.instance_stats ?? []).map(([id, stats]) => [id, PlayerStats.fromJSON(stats)])
);
const playerStats = User._calculatePlayerStats(instanceStats);
return new this(
json.name,
roleIds,
new Set<number>(json.roles),
new Set(json.instances),
json.is_admin,
json.is_banned,
@@ -69,13 +67,12 @@ export default class User {
json.ban_reason,
json.updated_at_ms,
json.is_deleted,
playerStats,
instanceStats,
);
}
toJSON() {
let json: Static<typeof User.jsonSchema> = {
let json: Static<typeof UserDetails.jsonSchema> = {
name: this.name,
};
@@ -119,7 +116,7 @@ export default class User {
}
recalculatePlayerStats() {
this.playerStats = User._calculatePlayerStats(this.instanceStats);
this.playerStats = UserDetails._calculatePlayerStats(this.instanceStats);
}
static _calculatePlayerStats(instanceStatsMap: Map<number, PlayerStats>) {
@@ -149,44 +146,13 @@ export default class User {
}
return playerStats;
}
/**
* Merge another user into this one, must have matching ids, user is not deleted
* @param otherUser - User who's details are merged from
*/
merge(otherUser: User) {
if (this.id !== otherUser.id) {
throw new Error("Cannot merge users with different ids");
}
// Merge properties
this.roleIds = new Set([...this.roleIds, ...otherUser.roleIds]);
this.instances = new Set([...this.instances, ...otherUser.instances]);
this.isAdmin = this.isAdmin && otherUser.isAdmin; // More secure to use && rather ||
this.isBanned = this.isBanned || otherUser.isBanned;
this.isBanned = this.isWhitelisted || otherUser.isWhitelisted;
this.banReason = this.updatedAtMs > otherUser.updatedAtMs ? this.banReason : otherUser.banReason;
this.updatedAtMs = Date.now();
// Merge instance stats
const thisInstanceStats = this.instanceStats;
for (const [instanceId, instanceStats] of otherUser.instanceStats.entries()) {
if (thisInstanceStats.has(instanceId)) {
thisInstanceStats.get(instanceId)!.merge(instanceStats);
} else {
thisInstanceStats.set(instanceId, instanceStats);
}
}
this.recalculatePlayerStats();
}
/** Name of the user, used by event subscriptions and to ensure case insensitivity */
get id() {
return this.name.toLowerCase();
}
}
export interface IControllerUser extends User {
/**
* This interface is implemented by User on the controller.
* It is exposed here to allow message definitions to create permission methods.
*/
export interface IUser extends UserDetails {
/**
* Check if a given permission is granted
*
+4 -2
View File
@@ -12,8 +12,10 @@ export { default as ModuleInfo } from "./ModuleInfo";
export { default as Permission } from "./Permission";
export { default as PlayerStats } from "./PlayerStats";
export { default as Role } from "./Role";
export { default as User } from "./User";
export type { IControllerUser } from "./User";
export { default as InstanceDetails, InstanceStatus } from "./InstanceDetails";
export { default as HostDetails } from "./HostDetails";
export { default as UserDetails } from "./UserDetails";
export type { IUser } from "./UserDetails";
export * from "./composites";
export * from "./messages_core";
export * from "./messages_controller";
+1 -41
View File
@@ -2,6 +2,7 @@ import { Type, Static } from "@sinclair/typebox";
import { jsonArray, plainJson, StringEnum } from "./composites";
import { CollectorResultSerialized } from "../prometheus";
import { HostConfig } from "../config/definitions";
import HostDetails from "./HostDetails";
export class HostStopRequest {
declare ["constructor"]: typeof HostStopRequest;
@@ -82,47 +83,6 @@ export class HostConfigSetPropRequest {
}
}
export class HostDetails {
constructor(
public version: string,
public name: string,
public id: number,
public connected: boolean,
public remoteAddress = "",
public publicAddress: string = "",
public tokenValidAfter: number = 0,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAtMs = 0,
public isDeleted = false,
) { }
static jsonSchema = Type.Object({
"version": Type.String(),
"name": Type.String(),
"id": Type.Integer(),
"connected": Type.Boolean(),
"remoteAddress": Type.Optional(Type.String()),
"publicAddress": Type.Optional(Type.String()),
"tokenValidAfter": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"isDeleted": Type.Optional(Type.Boolean()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(
json.version,
json.name,
json.id,
json.connected,
json.remoteAddress,
json.publicAddress,
json.tokenValidAfter,
json.updatedAtMs,
json.isDeleted,
);
}
}
export class HostListRequest {
declare ["constructor"]: typeof HostListRequest;
static type = "request" as const;
+3 -79
View File
@@ -2,87 +2,11 @@ import { Type, Static } from "@sinclair/typebox";
import PlayerStats from "./PlayerStats";
import { JsonString, StringEnum, jsonArray, plainJson } from "./composites";
import { InstanceConfig } from "../config";
import type { IControllerUser } from "./User";
import type { IUser } from "./UserDetails";
import type { MessageRequest } from "./messages_core";
import { CollectorResultSerialized } from "../prometheus";
import { TargetVersion, TargetVersionSchema, PartialVersion, PartialVersionSchema } from "./version";
export const InstanceStatus = StringEnum([
"unknown",
"unassigned",
"stopped",
"starting",
"running",
"stopping",
"creating_save",
"exporting_data",
"deleted",
]);
/**
* Current status of the instance. One of:
* - `unknown`: Instance is assigned to a host but this host is currently
* not connected to the contreller.
* - `unassigned`: Instance is not assigned to a a host and exists only on
* the controller.
* - `stopped`: Instance is stopped.
* - `starting`: Instance is in the process of starting up.
* - `running`: Instance is running normally.
* - `stopping`: Instance is in the process of stopping.
* - `creating_save`: Instance is in the process of creating a save.
* - `exporting_data`: Instance is in the process of exporting game data.
* - `deleted`: Instance has been deleted.
*/
export type InstanceStatus = Static<typeof InstanceStatus>;
export class InstanceDetails {
constructor(
public name: string,
public id: number,
public assignedHost: number | undefined,
public gamePort: number | undefined,
public status: InstanceStatus,
public factorioVersion: TargetVersion | undefined,
public startedAtMs = 0,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAtMs = 0,
public excludeFromStartAll = false,
) { }
static jsonSchema = Type.Object({
"name": Type.String(),
"id": Type.Integer(),
"assignedHost": Type.Optional(Type.Integer()),
"gamePort": Type.Optional(Type.Integer()),
"status": StringEnum([
"unknown", "unassigned", "stopped", "starting", "running", "stopping",
"creating_save", "exporting_data", "deleted",
]),
"factorioVersion": Type.Optional(TargetVersionSchema),
"startedAtMs": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"excludeFromStartAll": Type.Optional(Type.Boolean()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(
json.name,
json.id,
json.assignedHost,
json.gamePort,
json.status,
json.factorioVersion,
json.startedAtMs,
json.updatedAtMs,
json.excludeFromStartAll,
);
}
get isDeleted() {
return this.status === "deleted";
}
}
import InstanceDetails, { InstanceStatus } from "./InstanceDetails";
export class InstanceDetailsGetRequest {
declare ["constructor"]: typeof InstanceDetailsGetRequest;
@@ -539,7 +463,7 @@ export class InstanceTransferSaveRequest {
static type = "request" as const;
static src = ["control", "controller"] as const;
static dst = ["controller", "host"] as const;
static permission(user: IControllerUser, message: MessageRequest) {
static permission(user: IUser, message: MessageRequest) {
user.checkPermission("core.instance.save.transfer");
if (typeof message.data === "object" && message.data !== null) {
const data = message.data as { copy: boolean, sourceName: string, targetName: string };
+7 -7
View File
@@ -1,5 +1,5 @@
import { Type, Static } from "@sinclair/typebox";
import User, { IControllerUser } from "./User";
import UserDetails, { IUser } from "./UserDetails";
import { StringEnum, jsonArray, plainJson } from "./composites";
import { MessageRequest } from "./messages_core";
@@ -22,7 +22,7 @@ export class UserGetRequest {
return new this(json.name);
}
static Response = User;
static Response = UserDetails;
}
export class UserListRequest {
@@ -31,7 +31,7 @@ export class UserListRequest {
static src = "control" as const;
static dst = "controller" as const;
static permission = "core.user.list" as const;
static Response = jsonArray(User);
static Response = jsonArray(UserDetails);
}
export class UserCreateRequest {
@@ -198,15 +198,15 @@ export class UserUpdatesEvent {
static permission = "core.user.subscribe" as const;
constructor(
public updates: User[],
public updates: UserDetails[],
) { }
static jsonSchema = Type.Object({
"updates": Type.Array(User.jsonSchema),
"updates": Type.Array(UserDetails.jsonSchema),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.updates.map(update => User.fromJSON(update)));
return new this(json.updates.map(update => UserDetails.fromJSON(update)));
}
}
@@ -250,7 +250,7 @@ export class UserBulkImportRequest {
static type = "request" as const;
static src = "control" as const;
static dst = "controller" as const;
static permission(user: IControllerUser, message: MessageRequest) {
static permission(user: IUser, message: MessageRequest) {
if (typeof message.data === "object" && message.data !== null) {
const data = message.data as Static<typeof UserBulkImportRequest.jsonSchema>;
// Check if this is a restore or import request