mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-23 08:23:12 +09:00
Merge remote-tracking branch 'upstream/master' into feature/wait-for-plugin
This commit is contained in:
commit
7f688d2ed0
77 files changed
+2006
-693
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@clusterio/lib",
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.1",
|
||||
"description": "Shared library for Clusterio",
|
||||
"homepage": "https://github.com/clusterio/clusterio#readme",
|
||||
"author": "Hornwitser <github@hornwitser.no>",
|
||||
@@ -31,6 +31,13 @@
|
||||
},
|
||||
"import": "./src/link/WebSocket.browser.ts"
|
||||
},
|
||||
"#zlib_sync": {
|
||||
"node": {
|
||||
"types": "./src/zlib_sync.node.ts",
|
||||
"default": "./dist/node/src/zlib_sync.node.js"
|
||||
},
|
||||
"import": "./src/zlib_sync.browser.ts"
|
||||
},
|
||||
"#is_deep_strict_equal": {
|
||||
"node": {
|
||||
"types": "./src/is_deep_strict_equal.node.ts",
|
||||
@@ -51,11 +58,9 @@
|
||||
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "catalog:",
|
||||
"@types/yauzl": "catalog:",
|
||||
"@types/yazl": "catalog:",
|
||||
"ajv": "^8.20.0",
|
||||
"chalk": "catalog:",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fflate": "catalog:",
|
||||
"set-blocking": "catalog:",
|
||||
"triple-beam": "^1.4.1",
|
||||
"winston": "catalog:",
|
||||
@@ -71,6 +76,8 @@
|
||||
"@types/triple-beam": "^1.3.5",
|
||||
"@types/ws": "catalog:",
|
||||
"@types/yargs": "catalog:",
|
||||
"@types/yauzl": "catalog:",
|
||||
"@types/yazl": "catalog:",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import events from "events";
|
||||
import { Static } from "@sinclair/typebox";
|
||||
import { logger } from "./logging.js";
|
||||
import { downloadFile, atomicOverwriteFile } from "./file_ops.js";
|
||||
import { hashFile } from "./hash.js";
|
||||
import { ZipArchive, findRoot } from "./zip_ops.js";
|
||||
import { ModPortalReleaseSchema, ModPortalDetailsSchema, ModNameVersionPair } from "./data/messages_mod.js";
|
||||
import { ModInfo, ModPack, MajorMinorVersion, ModVersionEquality, SourceVersion } from "./data/index.js";
|
||||
|
||||
@@ -54,8 +56,44 @@ export default class ModStore extends events.EventEmitter<ModStoreEvents> {
|
||||
|
||||
mods() { return this.files.values(); }
|
||||
|
||||
/**
|
||||
* Read the info.json of a mod zip file along with its size, mtime and hash
|
||||
*
|
||||
* @param modPath - Path to the mod zip file.
|
||||
* @returns Mod info for the file.
|
||||
*/
|
||||
static async readModInfo(modPath: string) {
|
||||
let modInfo: Static<typeof ModInfo.jsonSchema>;
|
||||
let zip = await ZipArchive.fromFile(modPath);
|
||||
try {
|
||||
let content = await zip.readFile(path.posix.join(findRoot(zip), "info.json"));
|
||||
if (content === null) {
|
||||
throw new Error("Mod contains no info.json file");
|
||||
}
|
||||
modInfo = JSON.parse(content.toString("utf8"));
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
|
||||
let valid = ModInfo.validateInfo(modInfo);
|
||||
if (!valid) {
|
||||
throw new Error("Mod's info.json is not valid");
|
||||
}
|
||||
|
||||
const stat = await fs.stat(modPath);
|
||||
return ModInfo.fromJSON({
|
||||
...modInfo,
|
||||
|
||||
size: stat.size,
|
||||
sha1: await hashFile(modPath),
|
||||
mtime_ms: stat.mtimeMs,
|
||||
updated_at_ms: stat.mtimeMs,
|
||||
is_deleted: false,
|
||||
});
|
||||
}
|
||||
|
||||
static async loadFile(modsDirectory: string, file: string) {
|
||||
let modInfo = await ModInfo.fromModFile(path.join(modsDirectory, file));
|
||||
let modInfo = await ModStore.readModInfo(path.join(modsDirectory, file));
|
||||
if (modInfo.filename !== file) {
|
||||
throw new Error(`filename does not match the expected name ${modInfo.filename}.`);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "path";
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
import * as libHash from "../hash.js";
|
||||
import * as libSchema from "../schema.js";
|
||||
import { ZipArchive, findRoot } from "../zip_ops.js";
|
||||
import { ModRecord } from "./ModPack.js";
|
||||
|
||||
import {
|
||||
@@ -349,34 +345,4 @@ export default class ModInfo {
|
||||
if (this.isDeleted) { json.is_deleted = this.isDeleted; }
|
||||
return json;
|
||||
}
|
||||
|
||||
static async fromModFile(modPath: string) {
|
||||
let modInfo: Static<typeof ModInfo.jsonSchema>;
|
||||
let zip = await ZipArchive.fromFile(modPath);
|
||||
try {
|
||||
let content = await zip.readFile(path.posix.join(findRoot(zip), "info.json"));
|
||||
if (content === null) {
|
||||
throw new Error("Mod contains no info.json file");
|
||||
}
|
||||
modInfo = JSON.parse(content.toString("utf8"));
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
|
||||
let valid = this.validateInfo(modInfo);
|
||||
if (!valid) {
|
||||
throw new Error("Mod's info.json is not valid");
|
||||
}
|
||||
|
||||
const stat = await fs.stat(modPath);
|
||||
return this.fromJSON({
|
||||
...modInfo,
|
||||
|
||||
size: stat.size,
|
||||
sha1: await libHash.hashFile(modPath),
|
||||
mtime_ms: stat.mtimeMs,
|
||||
updated_at_ms: stat.mtimeMs,
|
||||
is_deleted: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import zlib from "zlib";
|
||||
import * as zlib from "#zlib_sync";
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
import * as libSchema from "../schema.js";
|
||||
@@ -306,7 +306,7 @@ export default class ModPack {
|
||||
|
||||
// eslint-disable-next-line node/no-sync
|
||||
let buf = zlib.deflateSync(JSON.stringify(json));
|
||||
return buf.toString("base64");
|
||||
return Buffer.from(buf).toString("base64");
|
||||
}
|
||||
|
||||
static fromModPackString(modPackString: string) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import zlib from "zlib";
|
||||
import * as zlib from "#zlib_sync";
|
||||
|
||||
class MapReaderState {
|
||||
pos = 0;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Throws if condition is falsy, node:assert is not available in the browser. */
|
||||
export function assert(condition: unknown): asserts condition {
|
||||
if (!condition) {
|
||||
throw new Error("Assertion failed");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
// Connection adapters for Links
|
||||
import { strict as assert } from "assert";
|
||||
import events from "events";
|
||||
|
||||
import { WebSocket } from "#WebSocket";
|
||||
@@ -7,6 +6,7 @@ import * as libData from "../data/index.js";
|
||||
import * as libErrors from "../errors.js";
|
||||
import { logger } from "../logging.js";
|
||||
import ExponentialBackoff from "../ExponentialBackoff.js";
|
||||
import { assert } from "./assert.js";
|
||||
import type { Request, Event } from "./link.js";
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,7 +5,7 @@ import { logger } from "../logging.js";
|
||||
import * as libSchema from "../schema.js";
|
||||
import { dataClasses, errorClasses } from "./messages.js";
|
||||
import { BaseConnector, WebSocketBaseConnector } from "./connectors.js";
|
||||
import { strict as assert } from "assert";
|
||||
import { assert } from "./assert.js";
|
||||
import type { PluginNodeEnvInfo, PluginWebEnvInfo } from "../plugin.js";
|
||||
import type {
|
||||
AddressType, JSONDeserialisable, MessageRoutable, MessageRequest, MessageEvent, IUser,
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
* @module lib/logging_utils
|
||||
*/
|
||||
import fs from "node:fs/promises";
|
||||
import type { ReadStream } from "node:fs";
|
||||
import { type ReadStream, type WriteStream, createWriteStream, mkdirSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "path";
|
||||
import stream from "stream";
|
||||
import util from "util";
|
||||
import util, { styleText } from "util";
|
||||
import winston from "winston";
|
||||
import Transport from "winston-transport";
|
||||
import { LEVEL, MESSAGE } from "triple-beam";
|
||||
import chalk from "chalk";
|
||||
|
||||
import * as libData from "./data/index.js";
|
||||
import * as libErrors from "./errors.js";
|
||||
@@ -108,30 +108,30 @@ export type ParsedFactorioOutput =
|
||||
function formatServerOutput(parsed: ParsedFactorioOutput) {
|
||||
let time = "";
|
||||
if (parsed.format === "seconds") {
|
||||
time = `${chalk.yellow(parsed.time.padStart(8))} `;
|
||||
time = `${styleText("yellow", parsed.time.padStart(8))} `;
|
||||
} else if (parsed.format === "date") {
|
||||
time = `${chalk.yellow(parsed.time)} `;
|
||||
time = `${styleText("yellow", parsed.time)} `;
|
||||
}
|
||||
|
||||
let info = "";
|
||||
if (parsed.type === "log") {
|
||||
let level = parsed.level;
|
||||
if (level === "Script") {
|
||||
level = chalk.bold.greenBright(level);
|
||||
level = styleText(["bold", "greenBright"], level);
|
||||
} else if (level === "Verbose") {
|
||||
level = chalk.bold.gray(level);
|
||||
level = styleText(["bold", "gray"], level);
|
||||
} else if (level === "Info") {
|
||||
level = chalk.bold.blueBright(level);
|
||||
level = styleText(["bold", "blueBright"], level);
|
||||
} else if (parsed.level === "Warning") {
|
||||
level = chalk.bold.yellowBright(level);
|
||||
level = styleText(["bold", "yellowBright"], level);
|
||||
} else if (parsed.level === "Error") {
|
||||
level = chalk.bold.redBright(level);
|
||||
level = styleText(["bold", "redBright"], level);
|
||||
}
|
||||
|
||||
info = `${level} ${chalk.gray(parsed.file)}: `;
|
||||
info = `${level} ${styleText("gray", parsed.file)}: `;
|
||||
|
||||
} else if (parsed.type === "action") {
|
||||
info = `[${chalk.yellow(parsed.action)}] `;
|
||||
info = `[${styleText("yellow", parsed.action)}] `;
|
||||
}
|
||||
|
||||
return time + info + parsed.message;
|
||||
@@ -226,6 +226,55 @@ export class LinkTransport extends Transport {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes log entries as lines to dirname/prefix-YYYY-MM-DD.log, opening
|
||||
* a new file when the UTC date changes.
|
||||
*/
|
||||
export class DailyFileTransport extends Transport {
|
||||
dirname: string;
|
||||
prefix: string;
|
||||
now: () => number;
|
||||
date?: string;
|
||||
stream?: WriteStream;
|
||||
|
||||
constructor(
|
||||
options: Transport.TransportStreamOptions & {
|
||||
dirname: string,
|
||||
prefix: string,
|
||||
now?: () => number,
|
||||
}
|
||||
) {
|
||||
super(options);
|
||||
this.dirname = options.dirname;
|
||||
this.prefix = options.prefix;
|
||||
this.now = options.now ?? Date.now;
|
||||
// eslint-disable-next-line node/no-sync
|
||||
mkdirSync(this.dirname, { recursive: true });
|
||||
}
|
||||
|
||||
log(info: any, callback: () => void) {
|
||||
const date = new Date(this.now()).toISOString().slice(0, 10);
|
||||
if (!this.stream || date !== this.date) {
|
||||
this.stream?.end();
|
||||
this.date = date;
|
||||
this.stream = createWriteStream(path.join(this.dirname, `${this.prefix}-${date}.log`), { flags: "a" });
|
||||
this.stream.on("error", err => this.emit("error", err));
|
||||
}
|
||||
this.stream.write(info[MESSAGE] + os.EOL);
|
||||
return callback();
|
||||
}
|
||||
|
||||
close(callback?: () => void) {
|
||||
const fileStream = this.stream;
|
||||
this.stream = undefined;
|
||||
if (fileStream) {
|
||||
fileStream.end(callback);
|
||||
} else {
|
||||
callback?.();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const logFileGlob = /^[a-z]+-(\d{4}-\d{2}-\d{2})\.log$/;
|
||||
const logIndexVersion = 2;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { PermissionDefinition } from "./permissions.js";
|
||||
import type { PlayerStats, Role } from "./data/index.js";
|
||||
import type { SyncHook } from "./SyncHook.js";
|
||||
import type { ErrorClass } from "./link/index.js";
|
||||
import { ModDependency } from "./data/ModInfo.js";
|
||||
|
||||
export const PluginFeatureFlags = [
|
||||
/** The plugin requires module code to be patched into the save */
|
||||
@@ -41,6 +42,11 @@ export type PluginDeclaration = {
|
||||
migrationEntrypoint?: string;
|
||||
|
||||
features?: (typeof PluginFeatureFlags)[number][];
|
||||
/**
|
||||
* Factorio mods the plugin needs in the instance's mod pack, as Factorio
|
||||
* dependency strings like `"subspace_storage >= 2.3.0"`.
|
||||
*/
|
||||
requiredMods?: string[];
|
||||
|
||||
messages?: any[];
|
||||
errors?: ErrorClass[];
|
||||
@@ -65,6 +71,23 @@ export function pluginNeedsWebBuild(info: PluginDeclaration) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the requiredMods of a plugin
|
||||
*
|
||||
* A mod listed more than once must satisfy every entry, which gives a range.
|
||||
*
|
||||
* @throws Error if an entry is invalid or has a dependency prefix.
|
||||
*/
|
||||
export function pluginRequiredMods(pluginInfo: PluginDeclaration) {
|
||||
return (pluginInfo.requiredMods ?? []).map(spec => {
|
||||
const dependency = new ModDependency(spec);
|
||||
if (dependency.type !== "required") {
|
||||
throw new Error(`requiredMods entry "${spec}" can not have a dependency prefix`);
|
||||
}
|
||||
return dependency;
|
||||
});
|
||||
}
|
||||
|
||||
export type PluginNodeEnvInfo = PluginDeclaration & {
|
||||
/**
|
||||
* Path to the folder with the static files that should be hosted on the web
|
||||
|
||||
@@ -84,6 +84,12 @@ export async function loadPluginInfos(pluginList: Map<string, string>, skippedNp
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
libPlugin.pluginRequiredMods(pluginInfo);
|
||||
} catch (err: any) {
|
||||
throw new libErrors.PluginError(pluginName, err);
|
||||
}
|
||||
|
||||
// migrate: ignore incompatible old plugins
|
||||
if (pluginInfo.messages && !(pluginInfo.messages instanceof Array)) {
|
||||
logger.warn(`Ignoring incompatible pre alpha.14 plugin ${pluginName}`);
|
||||
|
||||
+42
-10
@@ -7,10 +7,31 @@ import { PassThrough, type Readable } from "stream";
|
||||
import util from "util";
|
||||
import zlib from "zlib";
|
||||
import yauzl from "yauzl";
|
||||
import type yazl from "yazl";
|
||||
|
||||
const deflateRaw = util.promisify(zlib.deflateRaw);
|
||||
|
||||
/**
|
||||
* Entry in a ZipArchive
|
||||
*
|
||||
* Local subset of yauzl.Entry so the published declarations do not import
|
||||
* yauzl, which would make @types/yauzl a runtime dependency of lib.
|
||||
*/
|
||||
export interface ZipEntry {
|
||||
fileName: string;
|
||||
fileComment: string;
|
||||
versionMadeBy: number;
|
||||
versionNeededToExtract: number;
|
||||
generalPurposeBitFlag: number;
|
||||
compressionMethod: number;
|
||||
lastModFileTime: number;
|
||||
lastModFileDate: number;
|
||||
crc32: number;
|
||||
compressedSize: number;
|
||||
uncompressedSize: number;
|
||||
externalFileAttributes: number;
|
||||
getLastModDate(options?: { timezone?: "local" | "UTC" | null, forceDosFormat?: boolean }): Date;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Zip archive opened for random access reading
|
||||
@@ -21,10 +42,9 @@ const deflateRaw = util.promisify(zlib.deflateRaw);
|
||||
*/
|
||||
export class ZipArchive {
|
||||
private constructor(
|
||||
/** Underlying yauzl zip file. */
|
||||
public zipfile: yauzl.ZipFile,
|
||||
private zipfile: yauzl.ZipFile,
|
||||
/** Entries by file name in the order they appear in the central directory. */
|
||||
public entries: Map<string, yauzl.Entry>,
|
||||
public entries: Map<string, ZipEntry>,
|
||||
) { }
|
||||
|
||||
/**
|
||||
@@ -77,8 +97,17 @@ export class ZipArchive {
|
||||
*
|
||||
* @param entry - Entry to read, must belong to this archive.
|
||||
*/
|
||||
openStream(entry: yauzl.Entry): Promise<Readable> {
|
||||
return this.zipfile.openReadStreamPromise(entry);
|
||||
openStream(entry: ZipEntry): Promise<Readable> {
|
||||
return this.zipfile.openReadStreamPromise(entry as yauzl.Entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a stream of the content of an entry as stored in the archive
|
||||
*
|
||||
* @param entry - Entry to read, must belong to this archive.
|
||||
*/
|
||||
openRawStream(entry: ZipEntry): Promise<Readable> {
|
||||
return this.zipfile.openReadStreamPromise(entry as yauzl.Entry, { decodeFileData: false });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,7 +115,7 @@ export class ZipArchive {
|
||||
*
|
||||
* @param entry - Entry to read, must belong to this archive.
|
||||
*/
|
||||
async readEntry(entry: yauzl.Entry) {
|
||||
async readEntry(entry: ZipEntry) {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of await this.openStream(entry)) {
|
||||
chunks.push(chunk);
|
||||
@@ -153,7 +182,10 @@ export function findRoot(zip: ZipArchive) {
|
||||
*
|
||||
* @param zipFile - zip file being written.
|
||||
*/
|
||||
export function zipOutputStream(zipFile: yazl.ZipFile) {
|
||||
export function zipOutputStream(zipFile: {
|
||||
outputStream: NodeJS.ReadableStream,
|
||||
on(event: "error", listener: (err: Error) => void): unknown,
|
||||
}) {
|
||||
const output = zipFile.outputStream as Readable;
|
||||
zipFile.on("error", err => output.destroy(err));
|
||||
return output;
|
||||
@@ -224,7 +256,7 @@ export class ZipWriter {
|
||||
* @param zip - Archive to copy from.
|
||||
* @param entry - Entry to copy, must belong to zip.
|
||||
*/
|
||||
async addEntry(zip: ZipArchive, entry: yauzl.Entry) {
|
||||
async addEntry(zip: ZipArchive, entry: ZipEntry) {
|
||||
const writerEntry: WriterEntry = {
|
||||
fileName: Buffer.from(entry.fileName, "utf8"),
|
||||
fileComment: Buffer.from(entry.fileComment, "utf8"),
|
||||
@@ -242,7 +274,7 @@ export class ZipWriter {
|
||||
offset: this.offset,
|
||||
};
|
||||
await this.write(this.localFileHeader(writerEntry));
|
||||
const stream = await zip.zipfile.openReadStreamPromise(entry, { decodeFileData: false });
|
||||
const stream = await zip.openRawStream(entry);
|
||||
for await (const chunk of stream) {
|
||||
await this.write(chunk);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/* eslint-disable node/no-sync */
|
||||
import { strToU8, unzlibSync, zlibSync } from "fflate";
|
||||
|
||||
export function inflateSync(data: Uint8Array): Uint8Array {
|
||||
try {
|
||||
return unzlibSync(data);
|
||||
} catch (err: any) {
|
||||
// Match the error code node:zlib gives for invalid data.
|
||||
throw Object.assign(new Error(err.message), { code: "Z_DATA_ERROR" });
|
||||
}
|
||||
}
|
||||
|
||||
export function deflateSync(data: Uint8Array | string): Uint8Array {
|
||||
return zlibSync(typeof data === "string" ? strToU8(data) : data);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import zlib from "zlib";
|
||||
|
||||
export function inflateSync(data: Uint8Array): Uint8Array {
|
||||
// eslint-disable-next-line node/no-sync
|
||||
return zlib.inflateSync(data);
|
||||
}
|
||||
|
||||
export function deflateSync(data: Uint8Array | string): Uint8Array {
|
||||
// eslint-disable-next-line node/no-sync
|
||||
return zlib.deflateSync(data);
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
"./src/hash.ts",
|
||||
"./src/ini.ts",
|
||||
"./src/is_deep_strict_equal.browser.ts",
|
||||
"./src/zlib_sync.browser.ts",
|
||||
"./src/link/*.ts",
|
||||
"./src/lua_tools.ts",
|
||||
"./src/logging.ts",
|
||||
|
||||
Reference in new issue
Block a user