Merge pull request #29 from Hoekstraa/main

Add manual push/pull feature
This commit is contained in:
Alt 2022-10-10 00:38:57 +02:00 committed by GitHub
commit 3298542143
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 192 additions and 58 deletions

View file

@ -1,4 +1,5 @@
{ {
"extends": "@istanbuljs/nyc-config-typescript", "extends": "@istanbuljs/nyc-config-typescript",
"all": true "all": true,
"include": ["src/**"]
} }

View file

@ -1,4 +1,9 @@
#!/usr/bin/env -S node --experimental-specifier-resolution=node #!/usr/bin/env -S node --experimental-specifier-resolution=node
import { start } from "../src/index"; import { start, push, pull } from "../src/index";
import parser from "yargs-parser";
await start(); const argv = parser(process.argv.slice(2));
if (argv.push == true) await push();
else if (argv.pull == true) await pull();
else await start();

81
package-lock.json generated
View file

@ -13,7 +13,8 @@
"convict": "^6.2.3", "convict": "^6.2.3",
"signal-js": "^3.0.1", "signal-js": "^3.0.1",
"typescript": "^4.8.4", "typescript": "^4.8.4",
"ws": "^8.8.1" "ws": "^8.8.1",
"yargs-parser": "^21.1.1"
}, },
"bin": { "bin": {
"bitburner-filesync": "dist/npx/bitburner-filesync.js" "bitburner-filesync": "dist/npx/bitburner-filesync.js"
@ -1245,6 +1246,14 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/convict/node_modules/yargs-parser": {
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
"engines": {
"node": ">=10"
}
},
"node_modules/create-require": { "node_modules/create-require": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
@ -1863,6 +1872,15 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/istanbul-lib-processinfo/node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true,
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/istanbul-lib-report": { "node_modules/istanbul-lib-report": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz",
@ -3194,15 +3212,6 @@
"browserslist": ">= 4.21.0" "browserslist": ">= 4.21.0"
} }
}, },
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true,
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/v8-compile-cache-lib": { "node_modules/v8-compile-cache-lib": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
@ -3319,11 +3328,11 @@
} }
}, },
"node_modules/yargs-parser": { "node_modules/yargs-parser": {
"version": "20.2.9", "version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"engines": { "engines": {
"node": ">=10" "node": ">=12"
} }
}, },
"node_modules/yargs-unparser": { "node_modules/yargs-unparser": {
@ -3341,6 +3350,15 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/yargs/node_modules/yargs-parser": {
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
"dev": true,
"engines": {
"node": ">=10"
}
},
"node_modules/yn": { "node_modules/yn": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
@ -4318,6 +4336,13 @@
"requires": { "requires": {
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"yargs-parser": "^20.2.7" "yargs-parser": "^20.2.7"
},
"dependencies": {
"yargs-parser": {
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="
}
} }
}, },
"create-require": { "create-require": {
@ -4757,6 +4782,14 @@
"p-map": "^3.0.0", "p-map": "^3.0.0",
"rimraf": "^3.0.0", "rimraf": "^3.0.0",
"uuid": "^8.3.2" "uuid": "^8.3.2"
},
"dependencies": {
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true
}
} }
}, },
"istanbul-lib-report": { "istanbul-lib-report": {
@ -5744,12 +5777,6 @@
"picocolors": "^1.0.0" "picocolors": "^1.0.0"
} }
}, },
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"dev": true
},
"v8-compile-cache-lib": { "v8-compile-cache-lib": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
@ -5831,12 +5858,20 @@
"string-width": "^4.2.0", "string-width": "^4.2.0",
"y18n": "^5.0.5", "y18n": "^5.0.5",
"yargs-parser": "^20.2.2" "yargs-parser": "^20.2.2"
},
"dependencies": {
"yargs-parser": {
"version": "20.2.9",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==",
"dev": true
}
} }
}, },
"yargs-parser": { "yargs-parser": {
"version": "20.2.9", "version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==" "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="
}, },
"yargs-unparser": { "yargs-unparser": {
"version": "2.0.0", "version": "2.0.0",

View file

@ -34,7 +34,8 @@
"convict": "^6.2.3", "convict": "^6.2.3",
"signal-js": "^3.0.1", "signal-js": "^3.0.1",
"typescript": "^4.8.4", "typescript": "^4.8.4",
"ws": "^8.8.1" "ws": "^8.8.1",
"yargs-parser": "^21.1.1"
}, },
"devDependencies": { "devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.2", "@istanbuljs/nyc-config-typescript": "^1.0.2",

View file

@ -63,6 +63,13 @@ export let config = convict({
default: false, default: false,
arg: "pushAllOnConnection", arg: "pushAllOnConnection",
}, },
disableWatch: {
doc: "Disable everything besides push/pulling through the external calls.",
format: "Boolean",
env: "BB_MANUAL",
default: false,
arg: "manual",
},
}); });
export function loadConfig() { export function loadConfig() {

View file

@ -1,7 +1,7 @@
export class EventType { export enum EventType {
static ConnectionMade = "ConnectionMade"; ConnectionMade,
static FileChanged = "FileChanged"; FileChanged,
static FileDeleted = "FileDeleted"; FileDeleted,
static MessageReceived = "MessageReceived"; MessageReceived,
static MessageSend = "MessageSend"; MessageSend,
} }

View file

@ -1,6 +1,7 @@
import { setupWatch } from "./fileWatch"; import { setupWatch } from "./fileWatch";
import { config, loadConfig } from "./config"; import { config, loadConfig } from "./config";
import { setupSocket } from "./networking/webSocket"; import { setupSocket } from "./networking/webSocket";
import { WebSocket } from "ws";
import signal from "signal-js"; import signal from "signal-js";
import { RawData } from "ws"; import { RawData } from "ws";
import { import {
@ -12,6 +13,8 @@ import {
import { EventType } from "./eventTypes"; import { EventType } from "./eventTypes";
import { messageHandler } from "./networking/messageHandler"; import { messageHandler } from "./networking/messageHandler";
import { FileEvent } from "./interfaces"; import { FileEvent } from "./interfaces";
import { exit } from "process";
import CheapWatch from "cheap-watch";
export async function start() { export async function start() {
loadConfig(); loadConfig();
@ -21,6 +24,18 @@ export async function start() {
// Add a handler for received messages. // Add a handler for received messages.
signal.on(EventType.MessageReceived, (msg: RawData) => messageHandler(signal, msg, watch.paths)); signal.on(EventType.MessageReceived, (msg: RawData) => messageHandler(signal, msg, watch.paths));
console.log(`Server is ready, running on ${config.get("port")}!`);
process.on("SIGINT", function () {
console.log("Shutting down!");
watch.close();
socket.close();
process.exit();
});
}
async function watchMode(watch: CheapWatch) {
// Add a handler for when a connection to a game is made. // Add a handler for when a connection to a game is made.
signal.on(EventType.ConnectionMade, () => { signal.on(EventType.ConnectionMade, () => {
console.log("Connection made!"); console.log("Connection made!");
@ -52,14 +67,26 @@ export async function start() {
signal.on(EventType.FileDeleted, (fileEvent: FileEvent) => signal.on(EventType.FileDeleted, (fileEvent: FileEvent) =>
signal.emit(EventType.MessageSend, fileRemovalEventToMsg(fileEvent)), signal.emit(EventType.MessageSend, fileRemovalEventToMsg(fileEvent)),
); );
}
console.log(`Server is ready, running on ${config.get("port")}!`);
export async function pull() {
process.on("SIGINT", function () { loadConfig();
console.log("Shutting down!"); const ws = new WebSocket(`ws://localhost:${config.get("port")}`);
watch.close(); ws.onopen = () => {
socket.close(); ws.send(JSON.stringify({ jsonrpc: "2.0", method: "manualPullFromGame", id: Number.MAX_SAFE_INTEGER }));
process.exit(); ws.close();
}); exit(0);
};
}
export async function push() {
loadConfig();
const ws = new WebSocket(`ws://localhost:${config.get("port")}`);
ws.onopen = () => {
ws.send(JSON.stringify({ jsonrpc: "2.0", method: "manualPushToGame", id: Number.MAX_SAFE_INTEGER }));
ws.close();
exit(0);
};
} }

View file

@ -49,6 +49,17 @@ export function requestFilenames(): Message {
}; };
} }
export function requestAllFiles(): Message {
return {
jsonrpc: "2.0",
method: "getAllFiles",
params: {
server: "home",
},
id: messageCounter++,
};
}
function addLeadingSlash(path: string): string { function addLeadingSlash(path: string): string {
const slashes = path.match("/"); const slashes = path.match("/");
if (slashes) return `/${path}`; if (slashes) return `/${path}`;

View file

@ -3,9 +3,30 @@ import { Stats, writeFile } from "fs";
import { RawData } from "ws"; import { RawData } from "ws";
import { config } from "../config"; import { config } from "../config";
import { EventType } from "../eventTypes"; import { EventType } from "../eventTypes";
import { fileChangeEventToMsg } from "./messageGenerators"; import { fileChangeEventToMsg, requestAllFiles } from "./messageGenerators";
import type { Signal } from "signal-js"; import type { Signal } from "signal-js";
import { Message } from "../interfaces"; import { FileContent, Message } from "../interfaces";
/*function deserialize(data: RawData): Message {
const msg = JSON.parse(data.toString());
if (typeof msg.jsonrpc !== "string" || msg.jsonrpc !== "2.0" || typeof msg.id !== "number") {
throw Error("Malformed data received.");
}
const id: number = msg.id;
let request = messageTracker.get(id);
console.log(msg);
if (msg.error != null) {
throw Error(msg.error);
} else if (msg.result == null) {
throw Error("Malformed JSON received.");
}
return { jsonrpc: "2.0", method: !request? msg.method : request.method, result: msg.result, id };
}*/
function deserialize(data: RawData): Message { function deserialize(data: RawData): Message {
const msg = JSON.parse(data.toString()); const msg = JSON.parse(data.toString());
@ -15,23 +36,26 @@ function deserialize(data: RawData): Message {
} }
const id: number = msg.id; const id: number = msg.id;
const request = messageTracker.get(id); const request = id === Number.MAX_SAFE_INTEGER ? { method: msg.method } : messageTracker.get(id);
if (typeof request?.method !== "string") { console.log("M:", msg);
throw Error("Malformed JSON received."); console.log("R:", request);
} else if (msg.error != null) {
if (msg.error != null) {
throw Error(msg.error); throw Error(msg.error);
} else if (msg.result == null) {
throw Error("Malformed JSON received.");
} }
return { jsonrpc: "2.0", method: request.method, result: msg.result, id }; return { jsonrpc: "2.0", method: request?.method, result: msg.result, id };
} }
export function isStringArray(s: Array<unknown>): s is string[] { export function isStringArray(s: Array<unknown>): s is string[] {
return s.every((s) => typeof s === "string"); return s.every((s) => typeof s === "string");
} }
export function isFileContentArray(a: Array<unknown>): a is FileContent[] {
return a.every((f) => !!f && Object.hasOwn(f, "filename") && Object.hasOwn(f, "content"));
}
export function messageHandler(signaller: Signal, data: RawData, paths: Map<string, Stats>) { export function messageHandler(signaller: Signal, data: RawData, paths: Map<string, Stats>) {
let incoming; let incoming;
@ -49,9 +73,9 @@ export function messageHandler(signaller: Signal, data: RawData, paths: Map<stri
writeFile(config.get("definitionFile").location, incoming.result, (err) => { writeFile(config.get("definitionFile").location, incoming.result, (err) => {
if (err) return console.log(err); if (err) return console.log(err);
}); });
break; break;
case "getFileNames": {
case "getFileNames":
if (!Array.isArray(incoming.result) || !isStringArray(incoming.result)) if (!Array.isArray(incoming.result) || !isStringArray(incoming.result))
return console.log("Malformed data received."); return console.log("Malformed data received.");
@ -61,7 +85,30 @@ export function messageHandler(signaller: Signal, data: RawData, paths: Map<stri
if (!stats.isDirectory() && !gameFiles.includes(fileName)) if (!stats.isDirectory() && !gameFiles.includes(fileName))
signaller.emit(EventType.MessageSend, fileChangeEventToMsg({ path: fileName })); signaller.emit(EventType.MessageSend, fileChangeEventToMsg({ path: fileName }));
}); });
} break;
case "getAllFiles":
if (!Array.isArray(incoming.result) || !isFileContentArray(incoming.result))
return console.log("Malformed data received.");
const gameFiles2 = incoming.result.map((f: FileContent) => {
return { filename: removeLeadingSlash(f.filename), content: f.content };
});
gameFiles2.forEach((f) => console.log(f));
break;
case "manualPullFromGame":
console.log("PULL");
signaller.emit(EventType.MessageSend, requestAllFiles());
break;
case "manualPushToGame":
console.log("PUSH");
paths.forEach((stats, fileName) => {
if (!stats.isDirectory()) signaller.emit(EventType.MessageSend, fileChangeEventToMsg({ path: fileName }));
});
break;
} }
} }

6
src/signals.d.ts vendored
View file

@ -1,8 +1,8 @@
declare module "signal-js" { declare module "signal-js" {
export type Signal = typeof signal; export type Signal = typeof signal;
export default class signal { export default class signal {
static on<T>(event: string, callback: (data: T) => void): void; static on<T>(event: number, callback: (data: T) => void): void;
static emit<T>(event: string, data: T): void; static emit<T>(event: number, data: T): void;
static trigger(event: string): void; static trigger(event: number): void;
} }
} }