Hello yarn berry

This commit is contained in:
undefined committed 2021-05-26 23:35:36 +08:00
1 parent 04a4306895
commit 782f334a27
62 files changed
+448 -239

No files matched your search

+8 -8
View File
@@ -4,7 +4,7 @@ const os = require('os');
const path = require('path');
const cluster = require('cluster');
const fs = require('fs-extra');
const { argv } = require('yargs');
const argv = require('cac')().parse();
const child = require('child_process');
function buildUrl(opts) {
@@ -29,24 +29,24 @@ if (!cluster.isMaster) {
if (!fs.existsSync(addonPath)) fs.writeFileSync(addonPath, '[]');
let addons = JSON.parse(fs.readFileSync(addonPath).toString());
if (argv._[0] === 'db') {
if (argv.args[0] === 'db') {
const dbConfig = fs.readFileSync(path.resolve(hydroPath, 'config.json'), 'utf-8');
const url = buildUrl(JSON.parse(dbConfig));
return child.spawn('mongo', [url], { stdio: 'inherit' });
}
try {
const ui = argv.ui || '@hydrooj/ui-default';
const ui = argv.options.ui || '@hydrooj/ui-default';
require.resolve(ui);
addons.push(ui);
} catch (e) {
console.error('Please also install @hydrooj/ui-default');
}
if (argv._[0] && argv._[0] !== 'cli') {
const operation = argv._[0];
const arg1 = argv._[1];
const arg2 = argv._[2];
if (argv.args[0] && argv.args[0] !== 'cli') {
const operation = argv.args[0];
const arg1 = argv.args[1];
const arg2 = argv.args[2];
if (operation === 'addon') {
if (arg1 === 'add') addons.push(arg2);
else if (arg1 === 'remove') {
@@ -65,7 +65,7 @@ if (!cluster.isMaster) {
const hydro = require('../dist/loader');
addons = Array.from(new Set(addons));
for (const addon of addons) hydro.addon(addon);
(argv._[0] === 'cli' ? hydro.loadCli : hydro.load)().catch((e) => {
(argv.args[0] === 'cli' ? hydro.loadCli : hydro.load)().catch((e) => {
console.error(e);
process.exit(1);
});
+19 -18
View File
@@ -1,6 +1,6 @@
{
"name": "hydrooj",
"version": "2.27.3",
"version": "2.27.4",
"bin": "bin/hydrooj.js",
"main": "dist/loader.js",
"typings": "dist/loader.d.ts",
@@ -10,50 +10,51 @@
"engines": {
"node": ">=14"
},
"preferUnplugged": true,
"dependencies": {
"@hydrooj/utils": "^1.0.17",
"adm-zip": "^0.5.5",
"ansi_up": "^5.0.1",
"cac": "^6.7.3",
"cookies": "^0.8.0",
"detect-browser": "^5.1.1",
"detect-browser": "^5.2.0",
"fs-extra": "^10.0.0",
"js-yaml": "^4.0.0",
"js-yaml": "^4.1.0",
"koa": "^2.13.1",
"koa-body": "^4.2.0",
"koa-compress": "^5.0.1",
"koa-proxies": "^0.12.1",
"koa-router": "^10.0.0",
"koa-static-cache": "^5.1.3",
"koa-static-cache": "^5.1.4",
"lodash": "^4.17.21",
"lru-cache": "^6.0.0",
"minio": "7.0.17",
"moment-timezone": "^0.5.32",
"mongodb": "^3.6.6",
"nodemailer": "^6.6.0",
"moment-timezone": "^0.5.33",
"mongodb": "^3.6.8",
"nodemailer": "^6.6.1",
"p-queue": "^6.6.2",
"reflect-metadata": "^0.1.13",
"serialize-javascript": "^5.0.1",
"sockjs": "^0.3.20",
"superagent": "^6.1.0",
"yargs": "^17.0.1"
"sockjs": "^0.3.21",
"superagent": "^6.1.0"
},
"devDependencies": {
"@types/adm-zip": "^0.4.34",
"@types/fs-extra": "^9.0.10",
"@types/js-yaml": "^4.0.0",
"@types/fs-extra": "^9.0.11",
"@types/js-yaml": "^4.0.1",
"@types/koa": "^2.13.1",
"@types/koa-compress": "^4.0.1",
"@types/koa-router": "^7.4.1",
"@types/koa-router": "^7.4.2",
"@types/koa-static-cache": "^5.1.0",
"@types/lodash": "^4.14.168",
"@types/lodash": "^4.14.170",
"@types/lru-cache": "^5.1.0",
"@types/minio": "^7.0.7",
"@types/mongodb": "^3.6.12",
"@types/nodemailer": "^6.4.1",
"@types/mongodb": "^3.6.16",
"@types/nodemailer": "^6.4.2",
"@types/serialize-javascript": "^5.0.0",
"@types/sockjs": "^0.3.32",
"@types/superagent": "^4.1.11",
"@types/yargs": "^16.0.1",
"formidable": "^1.2.2"
"formidable": "^1.2.2",
"moment": "^2.29.1"
}
}
+3 -2
View File
@@ -1,7 +1,7 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable import/no-dynamic-require */
import { argv } from 'yargs';
import { ObjectID } from 'mongodb';
import cac from 'cac';
import {
lib, service, model, script,
builtinLib, builtinModel, builtinScript,
@@ -11,6 +11,7 @@ import { validate } from '../lib/validator';
import * as bus from '../service/bus';
import db from '../service/db';
const argv = cac().parse();
const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const ARR = /=>.*$/mg;
function parseParameters(fn: Function) {
@@ -29,7 +30,7 @@ async function runScript(name: string, arg: any) {
}
async function cli() {
const [, modelName, func, ...args] = argv._ as [string, string, string, ...any[]];
const [, modelName, func, ...args] = argv.args as [string, string, string, ...any[]];
if (modelName === 'script') {
let arg: any;
try {
+3 -2
View File
@@ -3,7 +3,7 @@
import os from 'os';
import path from 'path';
import fs from 'fs-extra';
import { argv } from 'yargs';
import cac from 'cac';
import { builtinModel } from './common';
import { Entry } from '../loader';
import { Logger } from '../logger';
@@ -11,13 +11,14 @@ import options from '../options';
import * as bus from '../service/bus';
import db from '../service/db';
const argv = cac().parse();
const logger = new Logger('entry/master');
const tmpdir = path.resolve(os.tmpdir(), 'hydro');
const lockfile = path.resolve(tmpdir, 'lock.json');
export async function load(call: Entry) {
fs.ensureDirSync(tmpdir);
if (fs.existsSync(lockfile) && !argv.ignorelock) {
if (fs.existsSync(lockfile) && !argv.options.ignorelock) {
try {
const file = require(lockfile);
process.kill(file.pid, 0);
+2 -2
View File
@@ -6,11 +6,11 @@ import Koa, { Context } from 'koa';
import Body from 'koa-body';
import cache from 'koa-static-cache';
import mongodb from 'mongodb';
import { argv } from 'yargs';
import cac from 'cac';
import { Logger } from '../logger';
const logger = new Logger('setup');
const listenPort = argv.port || 8888;
const listenPort = cac().parse().options.port || 8888;
async function get(ctx: Context) {
ctx.body = `<!DOCTYPE html>
+23 -22
View File
@@ -1,6 +1,6 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable import/no-dynamic-require */
import { argv } from 'yargs';
import cac from 'cac';
import {
locale, template, lib, service, model, handler, script, setting, uistatic,
builtinLib, builtinScript, builtinHandler, builtinModel,
@@ -11,32 +11,33 @@ import db from '../service/db';
import { Logger } from '../logger';
const logger = new Logger('loader/worker');
const detail = cac().parse().options.loaderDetail;
export async function load() {
const pending = global.addons;
const fail = [];
const active = [];
if (argv.loaderDetail) logger.info('start');
if (detail) logger.info('start');
require('../lib/i18n');
require('../utils');
require('../error');
require('../options');
if (argv.loaderDetail) logger.info('finish: options');
if (detail) logger.info('finish: options');
await Promise.all([
locale(pending, fail),
template(pending, fail),
uistatic(pending, fail),
]);
if (argv.loaderDetail) logger.info('finish: locale/template/static');
if (detail) logger.info('finish: locale/template/static');
const opts = options();
await db.start(opts);
if (argv.loaderDetail) logger.info('finish: db.connect');
if (detail) logger.info('finish: db.connect');
const modelSystem = require('../model/system');
await modelSystem.runConfig();
if (argv.loaderDetail) logger.info('finish: config');
if (detail) logger.info('finish: config');
const storage = require('../service/storage');
await storage.start();
if (argv.loaderDetail) logger.info('finish: storage.connect');
if (detail) logger.info('finish: storage.connect');
for (const i of builtinLib) {
let t;
try {
@@ -46,40 +47,40 @@ export async function load() {
}
require(t);
}
if (argv.loaderDetail) logger.info('finish: lib.builtin');
if (detail) logger.info('finish: lib.builtin');
await lib(pending, fail);
if (argv.loaderDetail) logger.info('finish: lib.extra');
if (detail) logger.info('finish: lib.extra');
require('../service/gridfs');
require('../service/monitor');
if (argv.loaderDetail) logger.info('finish: gridfs/monitor');
if (detail) logger.info('finish: gridfs/monitor');
const server = require('../service/server');
await server.prepare();
if (argv.loaderDetail) logger.info('finish: server');
if (detail) logger.info('finish: server');
await service(pending, fail);
if (argv.loaderDetail) logger.info('finish: service.extra');
if (detail) logger.info('finish: service.extra');
for (const i of builtinModel) require(`../model/${i}`);
if (argv.loaderDetail) logger.info('finish: model.builtin');
if (detail) logger.info('finish: model.builtin');
for (const i of builtinHandler) require(`../handler/${i}`);
if (argv.loaderDetail) logger.info('finish: handler.builtin');
if (detail) logger.info('finish: handler.builtin');
await model(pending, fail);
if (argv.loaderDetail) logger.info('finish: model.extra');
if (detail) logger.info('finish: model.extra');
const modelSetting = require('../model/setting');
await setting(pending, fail, modelSetting);
if (argv.loaderDetail) logger.info('finish: setting');
if (detail) logger.info('finish: setting');
await handler(pending, fail);
if (argv.loaderDetail) logger.info('finish: handler.extra');
if (detail) logger.info('finish: handler.extra');
for (const i in global.Hydro.handler) await global.Hydro.handler[i]();
if (argv.loaderDetail) logger.info('finish: handler.apply');
if (detail) logger.info('finish: handler.apply');
const notfound = require('../handler/notfound');
await notfound.apply();
for (const i of builtinScript) require(`../script/${i}`);
if (argv.loaderDetail) logger.info('finish: script.builtin');
if (detail) logger.info('finish: script.builtin');
await script(pending, fail, active);
if (argv.loaderDetail) logger.info('finish: script.extra');
if (detail) logger.info('finish: script.extra');
await bus.serial('app/started');
if (argv.loaderDetail) logger.info('finish: bus.serial(start)');
if (detail) logger.info('finish: bus.serial(start)');
await server.start();
if (argv.loaderDetail) logger.info('finish: server.start');
if (detail) logger.info('finish: server.start');
setInterval(() => {
process.send({ event: 'stat', count: global.Hydro.stat.reqCount });
global.Hydro.stat.reqCount = 0;
+19 -11
View File
@@ -8,6 +8,15 @@ import 'reflect-metadata';
const versionNum = +process.version.replace(/v/gim, '').split('.')[0];
if (versionNum < 14) throw new Error('NodeJS >=v14 required');
import cac from 'cac';
const argv = cac().parse();
if (argv.options.debug) {
process.env.NODE_ENV = 'development';
process.env.DEV = 'on';
} else process.env.NODE_ENV = process.env.NODE_ENV || 'production';
if (!global.Hydro) {
global.Hydro = {
version: {
@@ -44,7 +53,6 @@ import os from 'os';
import path from 'path';
import cluster from 'cluster';
import fs from 'fs-extra';
import { argv } from 'yargs';
import './utils';
import { Logger } from './logger';
import './ui';
@@ -95,7 +103,7 @@ async function stopWorker() {
}
async function startWorker(cnt: number, createFirst = true) {
if (argv.single) {
if (argv.options.single) {
await entry({ entry: 'worker' });
} else {
await fork(createFirst ? ['--firstWorker'] : undefined);
@@ -154,7 +162,7 @@ export function addon(addonPath: string, prepend = false) {
export async function load() {
addon(path.resolve(__dirname, '..'), true);
Error.stackTraceLimit = 50;
if (cluster.isMaster || argv.startAsMaster) {
if (cluster.isMaster || argv.options.startAsMaster) {
logger.info(`Master ${process.pid} Starting`);
const cnt = await entry({ entry: 'master' });
logger.info('Master started');
@@ -173,14 +181,14 @@ export async function load() {
});
await startWorker(cnt);
} else {
global.addons = JSON.parse(Buffer.from(argv.addons as string, 'base64').toString());
global.addons = JSON.parse(Buffer.from(argv.options.addons as string, 'base64').toString());
logger.info('%o', global.addons);
if (argv.entry) {
logger.info(`Worker ${process.pid} Starting as ${argv.entry}`);
await entry({ entry: argv.entry as string });
logger.success(`Worker ${process.pid} Started as ${argv.entry}`);
if (argv.options.entry) {
logger.info(`Worker ${process.pid} Starting as ${argv.options.entry}`);
await entry({ entry: argv.options.entry });
logger.success(`Worker ${process.pid} Started as ${argv.options.entry}`);
} else {
if (argv.firstWorker) global.Hydro.isFirstWorker = true;
if (argv.options.firstWorker) global.Hydro.isFirstWorker = true;
else global.Hydro.isFirstWorker = false;
logger.info(`Worker ${process.pid} Starting`);
await entry({ entry: 'worker' });
@@ -195,8 +203,8 @@ export async function loadCli() {
process.kill(process.pid, 'SIGINT');
}
if (argv.pandora || require.main === module) {
const func = argv._[0] === 'cli' ? load : loadCli;
if (argv.options.pandora || require.main === module) {
const func = argv.args[0] === 'cli' ? load : loadCli;
func().catch((e) => {
logger.error(e);
process.exit(1);
+1 -2
View File
@@ -1,5 +1,4 @@
import { inspect, format, InspectOptions } from 'util';
import { argv } from 'yargs';
import { Time } from './utils';
const colors = [
@@ -20,7 +19,7 @@ export class Logger {
static readonly INFO = 2;
static readonly WARN = 2;
static readonly DEBUG = 3;
static baseLevel = argv.debug ? 3 : 2;
static baseLevel = process.env.DEV ? 3 : 2;
static showDiff = false;
static levels: Record<string, number> = {};
static lastTime = 0;
+1 -1
View File
@@ -16,7 +16,7 @@ class BlackListModel {
const res = await coll.findOneAndUpdate(
{ _id: id },
{ $set: { expireAt } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
+17 -17
View File
@@ -100,7 +100,7 @@ export async function set<K extends keyof DocType>(
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
update,
{ returnOriginal: false, upsert: true },
{ returnDocument: 'after', upsert: true },
);
return res.value;
}
@@ -141,7 +141,7 @@ export async function inc<K extends keyof DocType>(
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $inc: { [key]: value } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -153,7 +153,7 @@ export async function incAndSet<K extends keyof DocType>(
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $inc: { [key]: value }, $set: args },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -183,7 +183,7 @@ export async function push(
const doc = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $push: { [key]: v } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return [doc.value, _id];
}
@@ -195,7 +195,7 @@ export async function pull<K extends keyof DocType, T extends ArrayKeys<DocType[
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $pull: { [setKey]: { $in: contents } } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -208,7 +208,7 @@ export async function deleteSub<T extends keyof DocType, K extends ArrayKeys<Doc
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $pull: { [key]: { _id: { $in: subId } } } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -244,7 +244,7 @@ export async function setSub<T extends keyof DocType, K extends ArrayKeys<DocTyp
[key]: { $elemMatch: { _id: subId } },
},
{ $set },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -256,7 +256,7 @@ export async function addToSet<T extends keyof DocType, K extends ArrayKeys<DocT
const res = await coll.findOneAndUpdate(
{ domainId, docType, docId },
{ $addToSet: { [setKey]: content } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
@@ -285,7 +285,7 @@ export async function setStatus<K extends keyof DocStatusType>(
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $set: args },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -308,7 +308,7 @@ export async function setIfNotStatus<T extends keyof DocStatusType, K extends ke
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $set: { [key]: value, ...args } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -322,7 +322,7 @@ export async function setStatusIfNotCondition<T extends keyof DocStatusType>(
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $set: args },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -336,7 +336,7 @@ export async function cappedIncStatus<T extends keyof DocStatusType>(
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid, [key]: { $not } },
{ $inc: { [key]: value } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -348,7 +348,7 @@ export async function incStatus<T extends keyof DocStatusType>(
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $inc: { [key]: value } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -360,13 +360,13 @@ export async function revPushStatus<T extends keyof DocStatusType>(
let res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid, [`${key}.${id}`]: value[id] },
{ $set: { [`${key}.$`]: value }, $inc: { rev: 1 } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
if (!res.value) {
res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $push: { [key]: value }, $inc: { rev: 1 } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
}
return res.value;
@@ -378,7 +378,7 @@ export async function revInitStatus<T extends keyof DocStatusType>(
const res = await collStatus.findOneAndUpdate(
{ domainId, docType, docId, uid },
{ $inc: { rev: 1 } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value;
}
@@ -389,7 +389,7 @@ export async function revSetStatus<T extends keyof DocStatusType>(
): Promise<any> {
const filter = { domainId, docType, docId, uid, rev };
const update = { $set: args, $inc: { rev: 1 } };
const res = await collStatus.findOneAndUpdate(filter, update, { returnOriginal: false });
const res = await collStatus.findOneAndUpdate(filter, update, { returnDocument: 'after' });
return res.value;
}
+3 -3
View File
@@ -80,7 +80,7 @@ class DomainModel {
static async edit(domainId: string, $set: Partial<DomainDoc>) {
await bus.serial('domain/before-update', domainId, $set);
const result = await coll.findOneAndUpdate({ _id: domainId }, { $set }, { returnOriginal: false });
const result = await coll.findOneAndUpdate({ _id: domainId }, { $set }, { returnDocument: 'after' });
await bus.serial('domain/update', domainId, $set, result.value);
return result.value;
}
@@ -92,7 +92,7 @@ class DomainModel {
// FIXME
// @ts-expect-error
{ $inc: { [field]: n } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value[field];
}
@@ -113,7 +113,7 @@ class DomainModel {
@ArgMethod
static async setUserRole(domainId: string, uid: MaybeArray<number>, role: string) {
if (!(uid instanceof Array)) {
const res = await collUser.findOneAndUpdate({ domainId, uid }, { $set: { role } }, { upsert: true, returnOriginal: false });
const res = await collUser.findOneAndUpdate({ domainId, uid }, { $set: { role } }, { upsert: true, returnDocument: 'after' });
const udoc = await UserModel.getById(domainId, uid);
deleteUserCache(udoc);
return res;
+1 -1
View File
@@ -46,7 +46,7 @@ class MessageModel {
const result = await coll.findOneAndUpdate(
{ _id: messageId },
{ $bit: { flag: { xor: flag } } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return result.value;
}
+1 -1
View File
@@ -19,7 +19,7 @@ class OauthModel {
const res = await coll.findOneAndUpdate(
{ _id },
{ $set: { value } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
return res.value.uid;
}
+1 -1
View File
@@ -132,7 +132,7 @@ class RecordModel {
const res = await RecordModel.coll.findOneAndUpdate(
{ _id, domainId },
$update,
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
+2 -2
View File
@@ -35,7 +35,7 @@ export class StorageModel {
}
static async get(path: string, savePath?: string) {
const { value } = await StorageModel.coll.findOneAndUpdate({ path }, { $set: { lastUsage: new Date() } }, { returnOriginal: false });
const { value } = await StorageModel.coll.findOneAndUpdate({ path }, { $set: { lastUsage: new Date() } }, { returnDocument: 'after' });
if (value) return await storage.get(value._id, savePath);
return await storage.get(path, savePath);
}
@@ -61,7 +61,7 @@ export class StorageModel {
}
static async getMeta(path: string) {
const { value } = await StorageModel.coll.findOneAndUpdate({ path }, { $set: { lastUsage: new Date() } }, { returnOriginal: false });
const { value } = await StorageModel.coll.findOneAndUpdate({ path }, { $set: { lastUsage: new Date() } }, { returnDocument: 'after' });
if (!value) return null;
return {
...value.meta,
+7 -7
View File
@@ -15,22 +15,22 @@ export function get(key: string): any {
export function getMany<
A extends keyof SystemKeys, B extends keyof SystemKeys,
>(keys: [A, B]): [SystemKeys[A], SystemKeys[B]];
>(keys: [A, B]): [SystemKeys[A], SystemKeys[B]];
export function getMany<
A extends keyof SystemKeys, B extends keyof SystemKeys, C extends keyof SystemKeys,
>(keys: [A, B, C]): [SystemKeys[A], SystemKeys[B], SystemKeys[C]];
>(keys: [A, B, C]): [SystemKeys[A], SystemKeys[B], SystemKeys[C]];
export function getMany<
A extends keyof SystemKeys, B extends keyof SystemKeys, C extends keyof SystemKeys,
D extends keyof SystemKeys,
>(keys: [A, B, C, D]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D]];
>(keys: [A, B, C, D]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D]];
export function getMany<
A extends keyof SystemKeys, B extends keyof SystemKeys, C extends keyof SystemKeys,
D extends keyof SystemKeys, E extends keyof SystemKeys,
>(keys: [A, B, C, D, E]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D], SystemKeys[E]];
>(keys: [A, B, C, D, E]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D], SystemKeys[E]];
export function getMany<
A extends keyof SystemKeys, B extends keyof SystemKeys, C extends keyof SystemKeys,
D extends keyof SystemKeys, E extends keyof SystemKeys, F extends keyof SystemKeys,
>(keys: [A, B, C, D, E, F]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D], SystemKeys[E], SystemKeys[F]];
>(keys: [A, B, C, D, E, F]): [SystemKeys[A], SystemKeys[B], SystemKeys[C], SystemKeys[D], SystemKeys[E], SystemKeys[F]];
export function getMany(keys: (keyof SystemKeys)[]): any[];
export function getMany(keys: string[]): any[] {
return keys.map((key) => cache[key]);
@@ -43,7 +43,7 @@ export async function set(_id: string, value: any, boardcast = true) {
const res = await coll.findOneAndUpdate(
{ _id },
{ $set: { value } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
cache[_id] = res.value.value;
return res.value.value;
@@ -55,7 +55,7 @@ export async function inc<K extends NumberKeys<SystemKeys>>(_id: K) {
// FIXME NumberKeys<>
// @ts-ignore
{ $inc: { value: 1 } },
{ upsert: true, returnOriginal: false },
{ upsert: true, returnDocument: 'after' },
);
cache[_id] = res.value.value;
return res.value.value;
+1 -1
View File
@@ -53,7 +53,7 @@ class TokenModel {
tokenType,
},
},
{ returnOriginal: false },
{ returnDocument: 'after' },
);
return res.value;
}
+3 -3
View File
@@ -204,7 +204,7 @@ class UserModel {
const op: any = {};
if ($set && Object.keys($set).length) op.$set = $set;
if ($unset && Object.keys($unset).length) op.$unset = $unset;
const res = await coll.findOneAndUpdate({ _id: uid }, op, { returnOriginal: false });
const res = await coll.findOneAndUpdate({ _id: uid }, op, { returnDocument: 'after' });
deleteUserCache(res.value);
return res;
}
@@ -220,7 +220,7 @@ class UserModel {
const res = await coll.findOneAndUpdate(
{ _id: uid },
{ $set: { salt, hash: pwhash(password, salt), hashType: 'hydro' } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
deleteUserCache(res.value);
return res.value;
@@ -290,7 +290,7 @@ class UserModel {
const res = await coll.findOneAndUpdate(
{ _id: uid },
{ $set: { priv } },
{ returnOriginal: false },
{ returnDocument: 'after' },
);
deleteUserCache(res.value);
return res.value;
+7 -6
View File
@@ -1,7 +1,7 @@
/* eslint-disable no-await-in-loop */
import cluster from 'cluster';
import serialize from 'serialize-javascript';
import { argv } from 'yargs';
import cac from 'cac';
import type { Db, FilterQuery, OnlyFieldsOfType } from 'mongodb';
import type { Handler } from './server';
import { Logger } from '../logger';
@@ -16,6 +16,7 @@ import type { UserRegisterHandler } from '../handler/user';
const _hooks: Record<keyof any, Array<(...args: any[]) => any>> = {};
const logger = new Logger('bus', true);
const argv = cac().parse();
function isBailed(value: any) {
return value !== null && value !== false && value !== undefined;
@@ -146,9 +147,9 @@ export function off<K extends keyof EventMap>(name: K, listener: EventMap[K]) {
export async function parallel<K extends keyof EventMap>(name: K, ...args: Parameters<EventMap[K]>): Promise<void> {
const tasks: Promise<any>[] = [];
if (argv.showBus) logger.debug('parallel: %s %o', name, args);
if (argv.options.showBus) logger.debug('parallel: %s %o', name, args);
for (const callback of _hooks[name] || []) {
if (argv.busDetail) logger.debug(callback.toString());
if (argv.options.busDetail) logger.debug(callback.toString());
tasks.push(callback.apply(this, args));
}
await Promise.all(tasks);
@@ -159,16 +160,16 @@ export function emit<K extends keyof EventMap>(name: K, ...args: Parameters<Even
}
export async function serial<K extends keyof EventMap>(name: K, ...args: Parameters<EventMap[K]>): Promise<void> {
if (argv.showBus) logger.debug('serial: %s %o', name, args);
if (argv.options.showBus) logger.debug('serial: %s %o', name, args);
const hooks = Array.from(_hooks[name] || []);
for (const callback of hooks) {
if (argv.busDetail) logger.debug(callback.toString());
if (argv.options.busDetail) logger.debug(callback.toString());
await callback.apply(this, args);
}
}
export function bail<K extends keyof EventMap>(name: K, ...args: Parameters<EventMap[K]>): ReturnType<EventMap[K]> {
if (argv.showBus) logger.debug('bail: %s %o', name, args);
if (argv.options.showBus) logger.debug('bail: %s %o', name, args);
const hooks = Array.from(_hooks[name] || []);
for (const callback of hooks) {
const result = callback.apply(this, args);
+8 -7
View File
@@ -15,7 +15,7 @@ import Router from 'koa-router';
import proxy from 'koa-proxies';
import cache from 'koa-static-cache';
import sockjs from 'sockjs';
import { argv } from 'yargs';
import cac from 'cac';
import { createHash } from 'crypto';
import type { SetOption } from 'cookies';
import * as bus from './bus';
@@ -38,6 +38,7 @@ import token from '../model/token';
import * as opcount from '../model/opcount';
import { PERM, PRIV } from '../model/builtin';
const argv = cac().parse();
const logger = new Logger('server');
export const app = new Koa();
export const server = http.createServer(app.callback());
@@ -248,8 +249,8 @@ export async function prepare() {
rewrite: (p) => p.replace('/fs', ''),
}));
app.use(Compress());
if (argv.public) {
app.use(cache(argv.public, {
if (argv.options.public) {
app.use(cache(argv.options.public, {
maxAge: 0,
}));
} else {
@@ -257,7 +258,7 @@ export async function prepare() {
maxAge: 30 * 24 * 60 * 60,
}));
}
if (argv.debug) {
if (process.env.DEV) {
app.use(async (ctx: Context, next: Function) => {
const startTime = new Date().getTime();
await next();
@@ -482,7 +483,7 @@ export class Handler extends HandlerCommon {
}
async init({ domainId }) {
if (!argv.benchmark) await this.limitRate('global', 10, 88);
if (!argv.options.benchmark) await this.limitRate('global', 10, 88);
const [absoluteDomain, inferDomain, bdoc] = await Promise.all([
domain.get(domainId),
domain.getByHost(this.request.host),
@@ -844,8 +845,8 @@ export function start() {
if (started) return;
const port = system.get('server.port');
app.use(router.routes()).use(router.allowedMethods());
server.listen(argv.port || port);
logger.success('Server listening at: %d', argv.port || port);
server.listen(argv.options.port || port);
logger.success('Server listening at: %d', argv.options.port || port);
started = true;
}
-4
View File
@@ -1,10 +1,7 @@
/* eslint-disable @typescript-eslint/no-shadow */
import cluster from 'cluster';
import { argv } from 'yargs';
import * as bus from './service/bus';
const disabledTerminal = argv.legacy || argv._.length || process.env.NODE_ENV === 'test';
export namespace Progress {
export class Progress {
constructor(public args) {
@@ -40,7 +37,6 @@ async function terminate() {
}
process.on('SIGINT', terminate);
if (cluster.isMaster) {
if (!disabledTerminal) console.log('Not running in a terminal environment. Interactive mode disabled.');
bus.on('message/log', (message) => {
process.stdout.write(`${message}\n`);
});