mirror of
https://github.com/CommunitySolidServer/CommunitySolidServer.git
synced 2024-10-03 14:55:10 +00:00
fix: Distinguish instantiation and initialization errors.
This commit is contained in:
parent
5a3a612dce
commit
49551eb9eb
@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env node
|
||||
const { runCli } = require('..');
|
||||
runCli();
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const { CliRunner } = require('..');
|
||||
new CliRunner().run();
|
||||
|
@ -1,21 +1,27 @@
|
||||
/* eslint-disable unicorn/no-process-exit */
|
||||
|
||||
import * as path from 'path';
|
||||
import type { ReadStream, WriteStream } from 'tty';
|
||||
import type { LoaderProperties } from 'componentsjs';
|
||||
import { Loader } from 'componentsjs';
|
||||
import yargs from 'yargs';
|
||||
import { getLoggerFor } from '../logging/LogUtil';
|
||||
import { ensureTrailingSlash } from '../util/PathUtil';
|
||||
import type { Initializer } from './Initializer';
|
||||
|
||||
export class CliRunner {
|
||||
private readonly logger = getLoggerFor(this);
|
||||
|
||||
/**
|
||||
* Generic run function for starting the server from a given config
|
||||
* @param args - Command line arguments.
|
||||
* @param stderr - Standard error stream.
|
||||
* @param properties - Components loader properties.
|
||||
* @param loaderProperties - Components loader properties.
|
||||
*/
|
||||
export const runCli = function({
|
||||
public run({
|
||||
argv = process.argv,
|
||||
stderr = process.stderr,
|
||||
properties = {
|
||||
loaderProperties = {
|
||||
mainModulePath: path.join(__dirname, '../../'),
|
||||
},
|
||||
}: {
|
||||
@ -23,8 +29,9 @@ export const runCli = function({
|
||||
stdin?: ReadStream;
|
||||
stdout?: WriteStream;
|
||||
stderr?: WriteStream;
|
||||
properties?: LoaderProperties;
|
||||
loaderProperties?: LoaderProperties;
|
||||
} = {}): void {
|
||||
// Parse the command-line arguments
|
||||
const { argv: params } = yargs(argv.slice(2))
|
||||
.usage('node ./bin/server.js [args]')
|
||||
.options({
|
||||
@ -38,18 +45,33 @@ export const runCli = function({
|
||||
})
|
||||
.help();
|
||||
|
||||
(async(): Promise<void> => {
|
||||
// Load provided or default config file
|
||||
const configPath = params.config ?
|
||||
// Gather settings for instantiating the server
|
||||
const configFile = params.config ?
|
||||
path.join(process.cwd(), params.config) :
|
||||
path.join(__dirname, '/../../config/config-default.json');
|
||||
const variables = this.createVariables(params);
|
||||
|
||||
// Setup from config file
|
||||
const loader = new Loader(properties);
|
||||
await loader.registerAvailableModuleResources();
|
||||
const initializer: Initializer = await loader
|
||||
.instantiateFromUrl('urn:solid-server:default:Initializer', configPath, undefined, {
|
||||
variables: {
|
||||
// Create and execute the server initializer
|
||||
this.createInitializer(loaderProperties, configFile, variables)
|
||||
.then(
|
||||
async(initializer): Promise<void> => initializer.handleSafe(),
|
||||
(error: Error): void => {
|
||||
// Instantiation of components has failed, so there is no logger to use
|
||||
stderr.write(`Error: could not instantiate server from ${configFile}\n`);
|
||||
stderr.write(`${error.stack}\n`);
|
||||
process.exit(1);
|
||||
},
|
||||
).catch((error): void => {
|
||||
this.logger.error(`Could not initialize server: ${error}`, { error });
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates command-line parameters into configuration variables
|
||||
*/
|
||||
protected createVariables(params: Record<string, any>): Record<string, any> {
|
||||
return {
|
||||
'urn:solid-server:default:variable:baseUrl':
|
||||
params.baseUrl ? ensureTrailingSlash(params.baseUrl) : `http://localhost:${params.port}/`,
|
||||
'urn:solid-server:default:variable:loggingLevel': params.loggingLevel,
|
||||
@ -58,11 +80,18 @@ export const runCli = function({
|
||||
'urn:solid-server:default:variable:sparqlEndpoint': params.sparqlEndpoint,
|
||||
'urn:solid-server:default:variable:podTemplateFolder':
|
||||
params.podTemplateFolder ?? path.join(__dirname, '../../templates'),
|
||||
},
|
||||
}) as Initializer;
|
||||
await initializer.handleSafe();
|
||||
})().catch((error): void => {
|
||||
// This is the only time we can *not* use the logger to print error messages, as dependency injection has failed.
|
||||
stderr.write(`${error}\n`);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the server initializer
|
||||
*/
|
||||
protected async createInitializer(loaderProperties: LoaderProperties, configFile: string,
|
||||
variables: Record<string, any>): Promise<Initializer> {
|
||||
const loader = new Loader(loaderProperties);
|
||||
await loader.registerAvailableModuleResources();
|
||||
|
||||
const initializer = 'urn:solid-server:default:Initializer';
|
||||
return await loader.instantiateFromUrl(initializer, configFile, undefined, { variables }) as Initializer;
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
import * as path from 'path';
|
||||
import { Loader } from 'componentsjs';
|
||||
import { runCli } from '../../../src/init/CliRunner';
|
||||
import { CliRunner } from '../../../src/init/CliRunner';
|
||||
import type { Initializer } from '../../../src/init/Initializer';
|
||||
|
||||
const mainModulePath = path.join(__dirname, '../../../');
|
||||
@ -19,13 +19,16 @@ jest.mock('componentsjs', (): any => ({
|
||||
Loader: jest.fn((): Loader => loader),
|
||||
}));
|
||||
|
||||
const write = jest.spyOn(process.stderr, 'write').mockImplementation(jest.fn());
|
||||
const exit = jest.spyOn(process, 'exit').mockImplementation(jest.fn() as any);
|
||||
|
||||
describe('CliRunner', (): void => {
|
||||
afterEach((): void => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts the server with default settings.', async(): Promise<void> => {
|
||||
runCli({
|
||||
new CliRunner().run({
|
||||
argv: [ 'node', 'script' ],
|
||||
});
|
||||
await initializer.handleSafe();
|
||||
@ -55,7 +58,7 @@ describe('CliRunner', (): void => {
|
||||
});
|
||||
|
||||
it('accepts abbreviated flags.', async(): Promise<void> => {
|
||||
runCli({
|
||||
new CliRunner().run({
|
||||
argv: [
|
||||
'node', 'script',
|
||||
'-p', '4000',
|
||||
@ -87,7 +90,7 @@ describe('CliRunner', (): void => {
|
||||
});
|
||||
|
||||
it('accepts full flags.', async(): Promise<void> => {
|
||||
runCli({
|
||||
new CliRunner().run({
|
||||
argv: [
|
||||
'node', 'script',
|
||||
'--port', '4000',
|
||||
@ -118,15 +121,29 @@ describe('CliRunner', (): void => {
|
||||
);
|
||||
});
|
||||
|
||||
it('writes to stderr when an error occurs.', async(): Promise<void> => {
|
||||
const write = jest.spyOn(process.stderr, 'write').mockImplementation((): any => null);
|
||||
it('exits with output to stderr when instantiation fails.', async(): Promise<void> => {
|
||||
loader.instantiateFromUrl.mockRejectedValueOnce(new Error('Fatal'));
|
||||
|
||||
runCli();
|
||||
new CliRunner().run();
|
||||
await new Promise((resolve): any => setImmediate(resolve));
|
||||
|
||||
expect(write).toHaveBeenCalledTimes(1);
|
||||
expect(write).toHaveBeenCalledWith('Error: Fatal\n');
|
||||
write.mockClear();
|
||||
expect(write).toHaveBeenCalledTimes(2);
|
||||
expect(write).toHaveBeenNthCalledWith(1,
|
||||
expect.stringMatching(/^Error: could not instantiate server from .*config-default\.json/u));
|
||||
expect(write).toHaveBeenNthCalledWith(2,
|
||||
expect.stringMatching(/^Error: Fatal/u));
|
||||
|
||||
expect(exit).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('exits without output to stderr when initialization fails.', async(): Promise<void> => {
|
||||
initializer.handleSafe.mockRejectedValueOnce(new Error('Fatal'));
|
||||
new CliRunner().run();
|
||||
await new Promise((resolve): any => setImmediate(resolve));
|
||||
|
||||
expect(write).toHaveBeenCalledTimes(0);
|
||||
|
||||
expect(exit).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user