Add time unit suffixes to variables (#561)

Add suffixes like Ms and Ns to variables whos time unit is not in
seconds.  This is aligning with a new code style of putting units
on variables that are not in SI base units.
This commit is contained in:
Hornwitser authored and GitHub committed 2024-01-20 13:26:55 +01:00
1 parent 9842705eb9
commit c53781d16c
38 files changed
+221 -201

No files matched your search

+4 -4
View File
@@ -30,7 +30,7 @@ export default class ExponentialBackoff {
reset: number;
private _exp = 0;
private _lastInvocationTime = Date.now();
private _lastInvocationTimeMs = Date.now();
/**
* Construct ExponentialBackoff helper
@@ -65,9 +65,9 @@ export default class ExponentialBackoff {
* @returns time in milliseconds to wait.
*/
delay() {
let invocationTime = Date.now();
let interval = (invocationTime - this._lastInvocationTime) / 1000;
this._lastInvocationTime = invocationTime;
let invocationTimeMs = Date.now();
let interval = (invocationTimeMs - this._lastInvocationTimeMs) / 1000;
this._lastInvocationTimeMs = invocationTimeMs;
if (interval > this.reset) {
this._exp = 0;
+1 -1
View File
@@ -56,7 +56,7 @@ export default class ModStore extends TypedEventEmitter<keyof ModStoreEvents, Mo
await fs.unlink(path.join(this.modsDirectory, file));
this.files.delete(file);
modInfo.isDeleted = true;
modInfo.updatedAt = Date.now();
modInfo.updatedAtMs = Date.now();
this.emit("change", modInfo);
}
+5 -5
View File
@@ -29,7 +29,7 @@ export default class RateLimiter {
*/
action?: () => void;
private _lastRun = 0;
private _lastRunMs = 0;
private _runTimeout?: ReturnType<typeof setTimeout>;
/**
@@ -60,15 +60,15 @@ export default class RateLimiter {
*/
activate() {
let now = Date.now();
if (now < this._lastRun + 1000 / this.maxRate) {
if (now < this._lastRunMs + 1000 / this.maxRate) {
if (!this._runTimeout && this.action) {
this._runTimeout = setTimeout(() => {
this._runTimeout = undefined;
this._lastRun = Date.now();
this._lastRunMs = Date.now();
if (this.action) {
this.action();
}
}, this._lastRun + 1000 / this.maxRate - now);
}, this._lastRunMs + 1000 / this.maxRate - now);
}
return false;
}
@@ -79,7 +79,7 @@ export default class RateLimiter {
this._runTimeout = undefined;
}
this._lastRun = now;
this._lastRunMs = now;
if (this.action) {
this.action();
}
+5 -5
View File
@@ -122,7 +122,7 @@ export default class ModInfo {
sha1?: string;
/** Millisecond Unix timestamp this entry was last updated at */
updatedAt = 0;
updatedAtMs = 0;
/**
* True if this mod has been deleted
@@ -148,7 +148,7 @@ export default class ModInfo {
...this.infoJsonSchema.properties,
"size": Type.Optional(Type.Integer()),
"sha1": Type.Optional(Type.String()),
"updated_at": Type.Optional(Type.Number()),
"updated_at_ms": Type.Optional(Type.Number()),
"is_deleted": Type.Optional(Type.Boolean()),
});
@@ -171,7 +171,7 @@ export default class ModInfo {
// Additional data
if (json.size) { modInfo.size = json.size; }
if (json.sha1) { modInfo.sha1 = json.sha1; }
if (json.updated_at) { modInfo.updatedAt = json.updated_at; }
if (json.updated_at_ms) { modInfo.updatedAtMs = json.updated_at_ms; }
if (json.is_deleted) { modInfo.isDeleted = json.is_deleted; }
return modInfo;
@@ -193,7 +193,7 @@ export default class ModInfo {
}
if (this.size) { json.size = this.size; }
if (this.sha1) { json.sha1 = this.sha1; }
if (this.updatedAt) { json.updated_at = this.updatedAt; }
if (this.updatedAtMs) { json.updated_at_ms = this.updatedAtMs; }
if (this.isDeleted) { json.is_deleted = this.isDeleted; }
return json;
}
@@ -229,7 +229,7 @@ export default class ModInfo {
size: stat.size,
sha1: await libHash.hashFile(modPath),
updated_at: stat.mtimeMs,
updated_at_ms: stat.mtimeMs,
is_deleted: false,
});
}
+6 -6
View File
@@ -102,7 +102,7 @@ export default class ModPack {
exportManifest?: ExportManifest;
/** Millisecond Unix timestamp this entry was last updated at */
updatedAt = 0;
updatedAtMs = 0;
/**
* True if this mod pack has been deleted from the list of mod packs.
@@ -118,7 +118,7 @@ export default class ModPack {
clone.mods = this.mods;
clone.settings = this.settings;
clone.exportManifest = this.exportManifest;
clone.updatedAt = this.updatedAt;
clone.updatedAtMs = this.updatedAtMs;
clone.isDeleted = this.isDeleted;
return clone;
}
@@ -135,7 +135,7 @@ export default class ModPack {
"runtime-per-user": ModSettingsJsonSchema,
}),
"export_manifest": Type.Optional(ExportManifest.jsonSchema),
"updated_at": Type.Optional(Type.Number()),
"updated_at_ms": Type.Optional(Type.Number()),
"is_deleted": Type.Optional(Type.Boolean()),
});
@@ -161,7 +161,7 @@ export default class ModPack {
};
}
if (json.export_manifest) { modPack.exportManifest = ExportManifest.fromJSON(json.export_manifest); }
if (json.updated_at) { modPack.updatedAt = json.updated_at; }
if (json.updated_at_ms) { modPack.updatedAtMs = json.updated_at_ms; }
if (json.is_deleted) { modPack.isDeleted = json.is_deleted; }
if (!modPack.mods.has("base")) {
@@ -185,7 +185,7 @@ export default class ModPack {
},
};
if (this.exportManifest) { json.export_manifest = this.exportManifest; }
if (this.updatedAt) { json.updated_at = this.updatedAt; }
if (this.updatedAtMs) { json.updated_at_ms = this.updatedAtMs; }
if (this.isDeleted) { json.is_deleted = this.isDeleted; }
return json;
}
@@ -194,7 +194,7 @@ export default class ModPack {
const json = this.toJSON();
delete json.id;
delete json.export_manifest;
delete json.updated_at;
delete json.updated_at_ms;
delete json.is_deleted;
// eslint-disable-next-line node/no-sync
+14 -11
View File
@@ -37,30 +37,33 @@ export default class PlayerStats {
static jsonSchema = Type.Object({
"join_count": Type.Optional(Type.Integer()),
"online_time_ms": Type.Optional(Type.Number()),
"first_join_at": Type.Optional(Type.Number()),
"first_join_at_ms": Type.Optional(Type.Number()),
"last_join_at_ms": Type.Optional(Type.Number()),
"last_leave_at_ms": Type.Optional(Type.Number()),
"last_leave_reason": Type.Optional(Type.String()),
// migrate: renamed fields from alpha 13
"last_join_at": Type.Optional(Type.Number()),
"last_leave_at": Type.Optional(Type.Number()),
"last_leave_reason": Type.Optional(Type.String()),
});
constructor(json: Static<typeof PlayerStats.jsonSchema> = {}) {
if (json["join_count"]) {
this.joinCount = json["join_count"];
}
if (json["first_join_at"]) {
this.firstJoinAt = new Date(json["first_join_at"]);
if (json["first_join_at_ms"]) {
this.firstJoinAt = new Date(json["first_join_at_ms"]);
}
if (json["online_time_ms"]) {
this.onlineTimeMs = json["online_time_ms"];
}
if (json["last_join_at"]) {
this.lastJoinAt = new Date(json["last_join_at"]);
if (json["last_join_at_ms"] ?? json["last_join_at"]) {
this.lastJoinAt = new Date(json["last_join_at_ms"] ?? json["last_join_at"]!);
if (!this.firstJoinAt) { // migrate: pre-alpha 14 did not have this field.
this.firstJoinAt = this.lastJoinAt;
}
}
if (json["last_leave_at"]) {
this.lastLeaveAt = new Date(json["last_leave_at"]);
if (json["last_leave_at_ms"] ?? json["last_leave_at"]) {
this.lastLeaveAt = new Date(json["last_leave_at_ms"] ?? json["last_leave_at"]!);
this.lastLeaveReason = json["last_leave_reason"] || "quit";
}
}
@@ -78,13 +81,13 @@ export default class PlayerStats {
json["online_time_ms"] = this.onlineTimeMs;
}
if (this.firstJoinAt) {
json["first_join_at"] = this.firstJoinAt.getTime();
json["first_join_at_ms"] = this.firstJoinAt.getTime();
}
if (this.lastJoinAt) {
json["last_join_at"] = this.lastJoinAt.getTime();
json["last_join_at_ms"] = this.lastJoinAt.getTime();
}
if (this.lastLeaveAt) {
json["last_leave_at"] = this.lastLeaveAt.getTime();
json["last_leave_at_ms"] = this.lastLeaveAt.getTime();
json["last_leave_reason"] = this.lastLeaveReason;
}
return json;
+5 -5
View File
@@ -24,7 +24,7 @@ export default class User {
/** Reason for being banned. Ignored if isBanned is false. */
public banReason = "",
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAt = 0,
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. */
@@ -42,7 +42,7 @@ export default class User {
is_banned: Type.Optional(Type.Boolean()),
is_whitelisted: Type.Optional(Type.Boolean()),
ban_reason: Type.Optional(Type.String()),
updated_at: Type.Optional(Type.Number()),
updated_at_ms: Type.Optional(Type.Number()),
is_deleted: Type.Optional(Type.Boolean()),
instance_stats: Type.Optional(
Type.Array(
@@ -67,7 +67,7 @@ export default class User {
json.is_banned,
json.is_whitelisted,
json.ban_reason,
json.updated_at,
json.updated_at_ms,
json.is_deleted,
playerStats,
instanceStats,
@@ -103,8 +103,8 @@ export default class User {
json.ban_reason = this.banReason;
}
if (this.updatedAt) {
json.updated_at = this.updatedAt;
if (this.updatedAtMs) {
json.updated_at_ms = this.updatedAtMs;
}
if (this.isDeleted) {
+3 -3
View File
@@ -239,7 +239,7 @@ export class SystemInfo {
public diskAvailable: number,
public canRestart: boolean,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAt: number,
public updatedAtMs: number,
public isDeleted: boolean,
) { }
@@ -256,7 +256,7 @@ export class SystemInfo {
"diskCapacity": Type.Number(),
"diskAvailable": Type.Number(),
"canRestart": Type.Boolean(),
"updatedAt": Type.Number(),
"updatedAtMs": Type.Number(),
"isDeleted": Type.Boolean(),
});
@@ -274,7 +274,7 @@ export class SystemInfo {
json.diskCapacity,
json.diskAvailable,
json.canRestart,
json.updatedAt,
json.updatedAtMs,
json.isDeleted,
);
}
+3 -3
View File
@@ -84,7 +84,7 @@ export class HostDetails {
public publicAddress: string = "",
public tokenValidAfter: number = 0,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAt = 0,
public updatedAtMs = 0,
public isDeleted = false,
) { }
@@ -96,7 +96,7 @@ export class HostDetails {
"remoteAddress": Type.Optional(Type.String()),
"publicAddress": Type.Optional(Type.String()),
"tokenValidAfter": Type.Optional(Type.Number()),
"updatedAt": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
"isDeleted": Type.Optional(Type.Boolean()),
});
@@ -109,7 +109,7 @@ export class HostDetails {
json.remoteAddress,
json.publicAddress,
json.tokenValidAfter,
json.updatedAt,
json.updatedAtMs,
json.isDeleted,
);
}
+8 -8
View File
@@ -43,7 +43,7 @@ export class InstanceDetails {
public gamePort: number | undefined,
public status: InstanceStatus,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAt = 0,
public updatedAtMs = 0,
) { }
static jsonSchema = Type.Object({
@@ -55,7 +55,7 @@ export class InstanceDetails {
"unknown", "unassigned", "stopped", "starting", "running", "stopping",
"creating_save", "exporting_data", "deleted",
]),
"updatedAt": Type.Optional(Type.Number()),
"updatedAtMs": Type.Optional(Type.Number()),
});
static fromJSON(json: Static<typeof this.jsonSchema>) {
@@ -65,7 +65,7 @@ export class InstanceDetails {
json.assignedHost,
json.gamePort,
json.status,
json.updatedAt,
json.updatedAtMs,
);
}
@@ -289,7 +289,7 @@ export class SaveDetails {
public loaded: boolean,
public loadByDefault: boolean,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAt: number,
public updatedAtMs: number,
public isDeleted: boolean,
) { }
@@ -301,7 +301,7 @@ export class SaveDetails {
"mtimeMs": Type.Number(),
"loaded": Type.Boolean(),
"loadByDefault": Type.Boolean(),
"updatedAt": Type.Number(),
"updatedAtMs": Type.Number(),
"isDeleted": Type.Boolean(),
});
@@ -314,7 +314,7 @@ export class SaveDetails {
json.mtimeMs,
json.loaded,
json.loadByDefault,
json.updatedAt,
json.updatedAtMs,
json.isDeleted,
);
}
@@ -330,8 +330,8 @@ export class SaveDetails {
* @returns true if this save is identical to the provided save
*/
equals(other: SaveDetails) {
// Note that updatedAt is not included in the equality check because
// instances send the whole list of saves with updatedAt set to zero
// Note that updatedAtMs is not included in the equality check because
// instances send the whole list of saves with updatedAtMs set to zero
// to the controller whenever any save changes and this equals check
// is used to filter whether a save was updated.
return (
+6 -6
View File
@@ -22,10 +22,10 @@ export function basicType(value: unknown) {
/**
* Asynchronously wait for the given duration
*
* @param duration - Time to wait for in milliseconds.
* @param durationMs - Time to wait for in milliseconds.
*/
export async function wait(duration: number) {
await new Promise(resolve => { setTimeout(resolve, duration); });
export async function wait(durationMs: number) {
await new Promise(resolve => { setTimeout(resolve, durationMs); });
}
@@ -33,16 +33,16 @@ export async function wait(duration: number) {
* Resolve a promise with a timeout.
*
* @param {Promise} promise - Promise to wait for.
* @param {number} time - Maximum time im milliseconds to wait for.
* @param {number} limitMs - Maximum time im milliseconds to wait for.
* @param {*=} timeoutResult - Value to return if the operation timed out.
*/
export async function timeout<T>(promise: Promise<T>, time: number, timeoutResult: T) {
export async function timeout<T>(promise: Promise<T>, limitMs: number, timeoutResult: T) {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<T>(resolve => {
timer = setTimeout(() => resolve(timeoutResult), time);
timer = setTimeout(() => resolve(timeoutResult), limitMs);
}),
]);
+15 -15
View File
@@ -95,7 +95,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
_state: ConnectorState = "closed";
_closing = false;
_socket: WebSocketClusterio | null = null;
_lastHeartbeat: number | null = null;
_lastHeartbeatMs: number | null = null;
_heartbeatId: ReturnType<typeof setInterval> | null = null;
_heartbeatInterval: number | null = null;
_lastReceivedSeq = undefined;
@@ -105,7 +105,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
this._state = "closed";
this._closing = false;
assert(this._socket === null);
this._lastHeartbeat = null;
this._lastHeartbeatMs = null;
assert(this._heartbeatId === null);
this._heartbeatInterval = null;
this._lastReceivedSeq = undefined;
@@ -117,7 +117,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
this._state = "connecting";
assert(this._closing === false);
assert(this._socket);
this._lastHeartbeat = null;
this._lastHeartbeatMs = null;
assert(this._heartbeatId === null);
this._heartbeatInterval = null;
this._lastReceivedSeq = undefined;
@@ -192,7 +192,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
_doHeartbeat() {
this._check("connected");
if (Date.now() - this._lastHeartbeat! > 2000 * this._heartbeatInterval!) {
if (Date.now() - this._lastHeartbeatMs! > 2000 * this._heartbeatInterval!) {
logger.verbose("Connector | closing after heartbeat timed out");
// eslint-disable-next-line node/no-process-env
if (process.env.APP_ENV === "browser") {
@@ -207,7 +207,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
}
_processHeartbeat(message: libData.MessageHeartbeat) {
this._lastHeartbeat = Date.now();
this._lastHeartbeatMs = Date.now();
this._dropSendBufferSeq(message.seq);
}
@@ -218,7 +218,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
if (this._heartbeatId) {
throw new Error("heartbeat is already running");
}
this._lastHeartbeat = Date.now();
this._lastHeartbeatMs = Date.now();
this._heartbeatId = setInterval(() => {
this._doHeartbeat();
}, this._heartbeatInterval! * 1000);
@@ -327,7 +327,7 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
_reconnectId?: ReturnType<typeof setTimeout>;
_sessionToken: string | null = null;
_sessionTimeout: number | null = null;
_startedResuming: number | null = null;
_startedResumingMs: number | null = null;
_backoff: ExponentialBackoff;
constructor(
@@ -350,7 +350,7 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
this._reconnectId = undefined;
this._sessionToken = null;
this._sessionTimeout = null;
this._startedResuming = null;
this._startedResumingMs = null;
super._reset();
this.src = undefined as any;
}
@@ -359,7 +359,7 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
assert(this._reconnectId === undefined);
this._sessionToken = null;
this._sessionTimeout = null;
this._startedResuming = null;
this._startedResumingMs = null;
super._invalidate();
this.src = undefined as any;
}
@@ -473,10 +473,10 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
logger.error("Unexpected double call to reconnect");
}
let delay = this._backoff.delay();
let delayMs = this._backoff.delay();
if (
this._state === "resuming"
&& this._startedResuming! + this._sessionTimeout! * 1000 < Date.now() + delay
&& this._startedResumingMs! + this._sessionTimeout! * 1000 < Date.now() + delayMs
) {
logger.error("Connector | Session timed out trying to resume");
this._reset();
@@ -489,12 +489,12 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
}
}
logger.verbose(
`Connector | waiting ${(Math.round(delay / 10) / 100)} seconds for reconnect`
`Connector | waiting ${(Math.round(delayMs / 10) / 100)} seconds for reconnect`
);
this._reconnectId = setTimeout(() => {
this._reconnectId = undefined;
this._doConnect();
}, delay);
}, delayMs);
}
_attachSocketHandlers() {
@@ -516,7 +516,7 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
} else {
this._state = "resuming";
this._startedResuming = Date.now();
this._startedResumingMs = Date.now();
this.reconnect();
this.emit("drop");
}
@@ -625,7 +625,7 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
for (let bufferedMessage of this._sendBuffer) {
this._sendInternal(bufferedMessage);
}
this._startedResuming = null;
this._startedResumingMs = null;
this.emit("resume");
} else if (type === "invalidate") {
+9 -9
View File
@@ -740,10 +740,10 @@ class GaugeChild extends ValueCollectorChild {
* seconds from when the timer was started
*/
startTimer() {
let start = process.hrtime.bigint();
let startNs = process.hrtime.bigint();
return () => {
let end = process.hrtime.bigint();
this.set(Number(end - start) / 1e9);
let endNs = process.hrtime.bigint();
this.set(Number(endNs - startNs) / 1e9);
};
}
}
@@ -979,10 +979,10 @@ class SummaryChild {
* when the timer was started into the metric.
*/
startTimer() {
let start = process.hrtime.bigint();
let startNs = process.hrtime.bigint();
return () => {
let end = process.hrtime.bigint();
this.observe(Number(end - start) / 1e9);
let endNs = process.hrtime.bigint();
this.observe(Number(endNs - startNs) / 1e9);
};
}
}
@@ -1260,10 +1260,10 @@ class HistogramChild {
* when the timer was started into the metric.
*/
startTimer() {
let start = process.hrtime.bigint();
let startNs = process.hrtime.bigint();
return () => {
let end = process.hrtime.bigint();
this.observe(Number(end - start) / 1e9);
let endNs = process.hrtime.bigint();
this.observe(Number(endNs - startNs) / 1e9);
};
}
}
+10 -10
View File
@@ -33,7 +33,7 @@ export class SubscriptionRequest {
constructor(
public eventName: string,
public subscribe: boolean,
public lastRequestTime: number = 0,
public lastRequestTimeMs: number = 0,
) {
if (!Link._eventsByName.has(eventName)) {
throw new Error(`Unregistered Event class ${eventName}`);
@@ -47,7 +47,7 @@ export class SubscriptionRequest {
]);
toJSON() {
return [this.eventName, this.subscribe, this.lastRequestTime];
return [this.eventName, this.subscribe, this.lastRequestTimeMs];
}
static fromJSON(json: Static<typeof SubscriptionRequest.jsonSchema>): SubscriptionRequest {
@@ -152,7 +152,7 @@ export class SubscriptionController {
export interface SubscribableValue {
id: number | string,
updatedAt: number,
updatedAtMs: number,
isDeleted: boolean,
}
@@ -175,8 +175,8 @@ export class EventSubscriber<
/** True if this subscriber is currently synced with the source */
synced = false;
_snapshot?: readonly [ReadonlyMap<K, Readonly<V>>, boolean];
_snapshotLastUpdated = 0;
lastResponseTime = -1;
_snapshotLastUpdatedMs = 0;
lastResponseTimeMs = -1;
constructor(
private Event: EventClass<T>,
@@ -203,7 +203,7 @@ export class EventSubscriber<
*/
async _handle(event: EventSubscribable<T, V>) {
for (const value of event.updates) {
this.lastResponseTime = Math.max(this.lastResponseTime, value.updatedAt);
this.lastResponseTimeMs = Math.max(this.lastResponseTimeMs, value.updatedAtMs);
if (value.isDeleted) {
this.values.delete(value.id as K);
} else {
@@ -257,8 +257,8 @@ export class EventSubscriber<
* @returns tuple of values map snapshot and synced property.
*/
getSnapshot() {
if (this._snapshotLastUpdated !== this.lastResponseTime) {
this._snapshotLastUpdated = this.lastResponseTime;
if (this._snapshotLastUpdatedMs !== this.lastResponseTimeMs) {
this._snapshotLastUpdatedMs = this.lastResponseTimeMs;
this._snapshot = [new Map(this.values), this.synced];
}
return this._snapshot!;
@@ -277,10 +277,10 @@ export class EventSubscriber<
await this.control.send(new SubscriptionRequest(
entry.name,
this._callbacks.length > 0,
this.lastResponseTime
this.lastResponseTimeMs
));
this.synced = this._callbacks.length > 0;
this._snapshotLastUpdated = 0;
this._snapshotLastUpdatedMs = 0;
for (let callback of this._callbacks) {
callback([], this.synced);
}