Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions impress.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ process.title = 'impress';
const fsp = require('node:fs').promises;
const { Worker } = require('node:worker_threads');
const path = require('node:path');

const { Config } = require('metaconfiguration');
const metavm = require('metavm');
const { Pool, isError } = require('metautil');
Expand Down Expand Up @@ -39,7 +40,7 @@ const exit = async (message, code) => {
if (impress.finalization) return;
impress.finalization = true;
impress.console.info(message);
if (impress.logger && impress.logger.active) await impress.logger.close();
if (impress.logger?.active) await impress.logger.close();
process.exit(code);
};

Expand Down Expand Up @@ -150,7 +151,8 @@ const validateConfig = async (config) => {
const checkResult = schema.check(config[section]);
if (!checkResult.valid) {
for (const error of checkResult.errors) {
impress.console.error(`${error} in application/config/${section}.js`);
const loc = `application/config/${section}.js`;
impress.console.error(`${error} in ${loc}`);
}
valid = false;
}
Expand All @@ -162,7 +164,8 @@ const loadApplication = async (root, dir, master) => {
impress.console.info(`Start: ${dir}`);
const configPath = path.join(dir, 'config');
const config = await new Config(configPath, CFG_OPTIONS).catch((error) => {
exit(`Can not read configuration: ${configPath}\n${error.stack}`, 1);
const { stack } = error;
exit(`Can not read configuration: ${configPath}\n${stack}`, 1);
});
await validateConfig(config);
if (master) {
Expand Down Expand Up @@ -190,11 +193,17 @@ const loadApplication = async (root, dir, master) => {
impress.applications.set(dir, app);
};

const parseApplicationsFile = async () => {
try {
const data = await fsp.readFile('.applications', 'utf8');
return data.split(/[\r\n\s]+/).filter((s) => s.length !== 0);
} catch {
return [path.join(PATH, 'application')];
}
};

const loadApplications = async () => {
const applications = await fsp
.readFile('.applications', 'utf8')
.then((data) => data.split(/[\r\n\s]+/).filter((s) => s.length !== 0))
.catch(() => [path.join(PATH, 'application')]);
const applications = await parseApplicationsFile();
let master = true;
for (const dir of applications) {
const location = path.isAbsolute(dir) ? dir : path.join(PATH, dir);
Expand Down
13 changes: 7 additions & 6 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ class Api extends Place {
const unit = proc.exports;
const relPath = filePath.substring(this.path.length + 1);
const [unitDir, methodFile] = relPath.split(node.path.sep);
const unitName = unitDir.includes('.') ? unitDir : `${unitDir}.1`;
const hasVersion = unitDir.includes('.');
const unitName = hasVersion ? unitDir : `${unitDir}.1`;
if (methodFile) {
const name = node.path.basename(methodFile, '.js');
return void this.changeUnit(unitName, name, proc);
Expand All @@ -72,8 +73,8 @@ class Api extends Place {
return void this.loadPlugin(unitName, unit);
}
for (const name of Object.keys(unit)) {
const proc = new Procedure(script, name, this.application);
this.changeUnit(unitName, name, proc);
const methodProc = new Procedure(script, name, this.application);
this.changeUnit(unitName, name, methodProc);
}
}

Expand All @@ -87,9 +88,9 @@ class Api extends Place {
const options = { context };
const { exports } = metarhia.metavm.createScript(name, pluginSrc, options);
const plugin = exports(unit);
for (const [name, script] of Object.entries(plugin)) {
const proc = new Procedure(script, name, this.application);
this.changeUnit(unitName, name, proc);
for (const [methodName, script] of Object.entries(plugin)) {
const proc = new Procedure(script, methodName, this.application);
this.changeUnit(unitName, methodName, proc);
}
}

Expand Down
46 changes: 28 additions & 18 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ const ERR_INIT = 'Can not initialize an Application';
const ERR_TEST = 'Application tests failed';
const TEST_DELAY = 100;

const placeFromPath = (filePath, appPath) => {
const relPath = filePath.substring(appPath.length + 1);
const sepIndex = relPath.indexOf(node.path.sep);
const place = relPath.substring(0, sepIndex);
return { relPath, place };
};

class Application extends EventEmitter {
constructor() {
super();
Expand Down Expand Up @@ -98,35 +105,42 @@ class Application extends EventEmitter {
async start() {
const { sandbox, config, cert, mode } = this;
const { kind, port } = workerData;
if (sandbox.api.auth) {
const provider = sandbox.api.auth.provider || auth(config.sessions);
this.auth = provider;
sandbox.api.auth.provider = provider;
}
const { concurrency, size, timeout } = config.server.queue;
this.semaphore = new Semaphore({ concurrency, size, timeout });
if (kind === 'balancer') {
const options = { ...config.server, port };
this.server = new Balancer(this, options);
await this.server.listen();
} else if (kind === 'server') {
const options = { ...config.server, port };
if (config.server.protocol === 'https') {
const isHttps = config.server.protocol === 'https';
if (isHttps) {
options.SNICallback = (servername, callback) => {
const domain = cert.get(servername);
if (!domain) callback(new Error(`No certificate for ${servername}`));
else callback(null, domain.creds);
if (domain === undefined) {
const err = new Error(`No certificate for ${servername}`);
callback(err);
} else {
callback(null, domain.creds);
}
};
}
this.server = new Server(this, options);
this.server.httpServer.on('request', (req, res) => {
if (!req.url.startsWith('/api')) this.static.serve(req.url, req, res);
const isApi = req.url.startsWith('/api');
if (!isApi) this.static.serve(req.url, req, res);
});
await this.server.listen();
}
if (sandbox.api.auth) {
const provider = sandbox.api.auth.provider || auth(config.sessions);
this.auth = provider;
sandbox.api.auth.provider = provider;
}
const { concurrency, size, timeout } = config.server.queue;
this.semaphore = new Semaphore({ concurrency, size, timeout });
this.initialization = false;
sandbox.application.emit('started');
if (mode === 'test' && threadId === 1) this.runTests();
const shouldRunTests = mode === 'test' && threadId === 1;
if (shouldRunTests) this.runTests();
}

async runTests() {
Expand Down Expand Up @@ -201,9 +215,7 @@ class Application extends EventEmitter {
this.watcher = new DirectoryWatcher({ timeout });

this.watcher.on('change', (filePath) => {
const relPath = filePath.substring(this.path.length + 1);
const sepIndex = relPath.indexOf(node.path.sep);
const place = relPath.substring(0, sepIndex);
const { relPath, place } = placeFromPath(filePath, this.path);
const target = this[place];
if (!target) return;
node.fs.stat(filePath, (error, stat) => {
Expand All @@ -221,9 +233,7 @@ class Application extends EventEmitter {
});

this.watcher.on('delete', async (filePath) => {
const relPath = filePath.substring(this.path.length + 1);
const sepIndex = relPath.indexOf(node.path.sep);
const place = relPath.substring(0, sepIndex);
const { relPath, place } = placeFromPath(filePath, this.path);
const target = this[place];
if (!target) return;
target.delete(filePath);
Expand Down
2 changes: 1 addition & 1 deletion lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module.exports = ({ characters, secret, length }) => ({
},

async readSession(token) {
return sessions.get(token) || null;
return sessions.get(token) ?? null;
},

async deleteSession(token) {
Expand Down
8 changes: 6 additions & 2 deletions lib/balancer.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';

const http = require('node:http');

const { parseHost, sample } = require('metautil');
const { buildHeaders } = require('metacom');

const DEFAULT_LISTEN_RETRY = 3;
const SAFE_REDIRECT_METHODS = ['GET', 'HEAD'];

class Balancer {
#console = null;
Expand Down Expand Up @@ -35,7 +37,8 @@ class Balancer {
const targetPath = req.url;
const location = `${protocol}://${host}:${targetPort}${targetPath}`;
if (res.headersSent) return;
const code = ['GET', 'HEAD'].includes(req.method) ? 302 : 307;
const isSafe = SAFE_REDIRECT_METHODS.includes(req.method);
const code = isSafe ? 302 : 307;
res.writeHead(code, { ...this.#headers, Location: location });
res.end();
}
Expand All @@ -57,7 +60,8 @@ class Balancer {

const onError = (error) => {
count--;
const fatal = error.code !== 'EADDRINUSE' || count === 0;
const addressInUse = error.code === 'EADDRINUSE';
const fatal = !addressInUse || count === 0;
if (fatal) return void reject(error);
this.#console.warn(`Address in use: ${host}:${port}, retry...`);
setTimeout(listen, timeouts.bind);
Expand Down
21 changes: 13 additions & 8 deletions lib/bus.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,31 @@ const prepare = (unit, application) => {
const { parameters, query, returns } = validation;
if (parameters) {
const { valid, errors } = parameters.check(args);
const problems = errors.join('; ');
if (!valid) return new Error(`Invalid parameters type: ${problems}`);
if (!valid) {
return new Error(`Invalid parameters type: ${errors.join('; ')}`);
}
}
if (unit.query.params) {
const { valid, errors } = query.check(args);
const problems = errors.join('; ');
if (!valid) return new Error(`Invalid query type: ${problems}`);
if (!valid) {
return new Error(`Invalid query type: ${errors.join('; ')}`);
}
}
const service = method.parent['.service'];
const verb = unit.method.get ? 'get' : 'post';
const target = [service.url, unit.method[verb]];
if (unit.method.path) {
target.push(...unit.method.path.map((arg) => args[arg]));
const pathParts = unit.method.path.map((arg) => args[arg]);
target.push(...pathParts);
}
let url = target.join('/');
if (unit.query) {
const params = [];
const { prefix = '', suffix = '' } = unit.query;
for (const param of Object.keys(unit.query.params)) {
if (!args[param]) continue;
params.push([`${prefix}${param}${suffix}`, args[param]]);
const key = `${prefix}${param}${suffix}`;
params.push([key, args[param]]);
}
const parsedParams = Object.fromEntries(params);
const stringParams = new URLSearchParams(parsedParams).toString();
Expand All @@ -46,8 +50,9 @@ const prepare = (unit, application) => {
const result = await metarhia.metautil.httpApiCall(url, options);
if (returns) {
const { valid, errors } = returns.check(result);
const problems = errors.join('; ');
if (!valid) return new Error(`Invalid result type: ${problems}`);
if (!valid) {
return new Error(`Invalid result type: ${errors.join('; ')}`);
}
}
return result;
};
Expand Down
5 changes: 3 additions & 2 deletions lib/cert.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ class Cert extends Static {
const creds = node.tls.createSecureContext(options);
const context = { ...options, creds };
for (const domain of domains) this.domains.set(domain, context);
if (!this.application.server?.httpServer.setSecureContext) continue;
this.application.server.httpServer.setSecureContext(options);
const httpServer = this.application.server?.httpServer;
if (!httpServer?.setSecureContext) continue;
httpServer.setSecureContext(options);
} catch (error) {
for (const domain of domains) this.domains.delete(domain);
this.application.console.error(error.stack);
Expand Down
9 changes: 6 additions & 3 deletions lib/code.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ class Code extends Place {
for (let depth = 0; depth <= last; depth++) {
const name = names[depth];
let next = level[name];
if (depth === last) {
const isLeaf = depth === last;
if (isLeaf) {
if (unit === null) {
if (name === 'stop') this.stopModule(names[0], level);
delete level[name];
Expand All @@ -48,8 +49,10 @@ class Code extends Place {
let { start } = unit;
if (start) start = start.bind(unit);
if (depth === 1 && name === 'start') start = unit;
if (start) {
if (start.constructor.name === 'AsyncFunction') {
const shouldRegister = start && (isLeaf || name === 'start');
if (shouldRegister) {
const isAsync = start.constructor.name === 'AsyncFunction';
if (isAsync) {
this.application.starts.push(start);
} else {
const msg = `${relPath}/start expected to be async function`;
Expand Down
10 changes: 7 additions & 3 deletions lib/deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const CWD = process.cwd();

const wt = require('node:worker_threads');
const { createRequire, builtinModules } = require('node:module');

const metautil = require('metautil');
const appRequire = createRequire(`file://${CWD}/server.js`);

Expand Down Expand Up @@ -46,7 +47,8 @@ const validSubmodules = (key) =>

const loadModule = (name) => {
const lib = appRequire(name);
const pkg = require(`${CWD}/node_modules/${name}/package.json`);
const pkgPath = `${CWD}/node_modules/${name}/package.json`;
const pkg = require(pkgPath);
if (!pkg.exports) return lib;
const subKeys = Object.keys(pkg.exports).map((key) => key.substring(2));
const subNames = subKeys.filter(validSubmodules);
Expand All @@ -73,13 +75,15 @@ for (const name of dependencies) {
let lib = null;
try {
if (internals.includes(name)) {
const realName = name.startsWith('node:') ? name : `node:${name}`;
const hasPrefix = name.startsWith('node:');
const realName = hasPrefix ? name : `node:${name}`;
lib = require(realName);
} else {
lib = loadModule(name);
}
} catch (error) {
if (npmpkg.includes(name) || !optional.includes(name)) {
const isRequired = npmpkg.includes(name) || !optional.includes(name);
if (isRequired) {
notLoaded.add(`- ${name}: ${error.stack}`);
}
continue;
Expand Down
2 changes: 1 addition & 1 deletion lib/place.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Place {
else await this.change(filePath);
}
} catch (error) {
const console = this.application.console || global.console;
const console = this.application.console ?? global.console;
console.error(error.stack);
}
}
Expand Down
Loading
Loading