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
|
#!/usr/bin/env node
|
||||||
const { runCli } = require('..');
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
runCli();
|
const { CliRunner } = require('..');
|
||||||
|
new CliRunner().run();
|
||||||
|
@ -1,30 +1,37 @@
|
|||||||
|
/* eslint-disable unicorn/no-process-exit */
|
||||||
|
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import type { ReadStream, WriteStream } from 'tty';
|
import type { ReadStream, WriteStream } from 'tty';
|
||||||
import type { LoaderProperties } from 'componentsjs';
|
import type { LoaderProperties } from 'componentsjs';
|
||||||
import { Loader } from 'componentsjs';
|
import { Loader } from 'componentsjs';
|
||||||
import yargs from 'yargs';
|
import yargs from 'yargs';
|
||||||
|
import { getLoggerFor } from '../logging/LogUtil';
|
||||||
import { ensureTrailingSlash } from '../util/PathUtil';
|
import { ensureTrailingSlash } from '../util/PathUtil';
|
||||||
import type { Initializer } from './Initializer';
|
import type { Initializer } from './Initializer';
|
||||||
|
|
||||||
/**
|
export class CliRunner {
|
||||||
|
private readonly logger = getLoggerFor(this);
|
||||||
|
|
||||||
|
/**
|
||||||
* Generic run function for starting the server from a given config
|
* Generic run function for starting the server from a given config
|
||||||
* @param args - Command line arguments.
|
* @param args - Command line arguments.
|
||||||
* @param stderr - Standard error stream.
|
* @param stderr - Standard error stream.
|
||||||
* @param properties - Components loader properties.
|
* @param loaderProperties - Components loader properties.
|
||||||
*/
|
*/
|
||||||
export const runCli = function({
|
public run({
|
||||||
argv = process.argv,
|
argv = process.argv,
|
||||||
stderr = process.stderr,
|
stderr = process.stderr,
|
||||||
properties = {
|
loaderProperties = {
|
||||||
mainModulePath: path.join(__dirname, '../../'),
|
mainModulePath: path.join(__dirname, '../../'),
|
||||||
},
|
},
|
||||||
}: {
|
}: {
|
||||||
argv?: string[];
|
argv?: string[];
|
||||||
stdin?: ReadStream;
|
stdin?: ReadStream;
|
||||||
stdout?: WriteStream;
|
stdout?: WriteStream;
|
||||||
stderr?: WriteStream;
|
stderr?: WriteStream;
|
||||||
properties?: LoaderProperties;
|
loaderProperties?: LoaderProperties;
|
||||||
} = {}): void {
|
} = {}): void {
|
||||||
|
// Parse the command-line arguments
|
||||||
const { argv: params } = yargs(argv.slice(2))
|
const { argv: params } = yargs(argv.slice(2))
|
||||||
.usage('node ./bin/server.js [args]')
|
.usage('node ./bin/server.js [args]')
|
||||||
.options({
|
.options({
|
||||||
@ -38,18 +45,33 @@ export const runCli = function({
|
|||||||
})
|
})
|
||||||
.help();
|
.help();
|
||||||
|
|
||||||
(async(): Promise<void> => {
|
// Gather settings for instantiating the server
|
||||||
// Load provided or default config file
|
const configFile = params.config ?
|
||||||
const configPath = params.config ?
|
|
||||||
path.join(process.cwd(), params.config) :
|
path.join(process.cwd(), params.config) :
|
||||||
path.join(__dirname, '/../../config/config-default.json');
|
path.join(__dirname, '/../../config/config-default.json');
|
||||||
|
const variables = this.createVariables(params);
|
||||||
|
|
||||||
// Setup from config file
|
// Create and execute the server initializer
|
||||||
const loader = new Loader(properties);
|
this.createInitializer(loaderProperties, configFile, variables)
|
||||||
await loader.registerAvailableModuleResources();
|
.then(
|
||||||
const initializer: Initializer = await loader
|
async(initializer): Promise<void> => initializer.handleSafe(),
|
||||||
.instantiateFromUrl('urn:solid-server:default:Initializer', configPath, undefined, {
|
(error: Error): void => {
|
||||||
variables: {
|
// 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':
|
'urn:solid-server:default:variable:baseUrl':
|
||||||
params.baseUrl ? ensureTrailingSlash(params.baseUrl) : `http://localhost:${params.port}/`,
|
params.baseUrl ? ensureTrailingSlash(params.baseUrl) : `http://localhost:${params.port}/`,
|
||||||
'urn:solid-server:default:variable:loggingLevel': params.loggingLevel,
|
'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:sparqlEndpoint': params.sparqlEndpoint,
|
||||||
'urn:solid-server:default:variable:podTemplateFolder':
|
'urn:solid-server:default:variable:podTemplateFolder':
|
||||||
params.podTemplateFolder ?? path.join(__dirname, '../../templates'),
|
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.
|
* Creates the server initializer
|
||||||
stderr.write(`${error}\n`);
|
*/
|
||||||
});
|
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 * as path from 'path';
|
||||||
import { Loader } from 'componentsjs';
|
import { Loader } from 'componentsjs';
|
||||||
import { runCli } from '../../../src/init/CliRunner';
|
import { CliRunner } from '../../../src/init/CliRunner';
|
||||||
import type { Initializer } from '../../../src/init/Initializer';
|
import type { Initializer } from '../../../src/init/Initializer';
|
||||||
|
|
||||||
const mainModulePath = path.join(__dirname, '../../../');
|
const mainModulePath = path.join(__dirname, '../../../');
|
||||||
@ -19,13 +19,16 @@ jest.mock('componentsjs', (): any => ({
|
|||||||
Loader: jest.fn((): Loader => loader),
|
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 => {
|
describe('CliRunner', (): void => {
|
||||||
afterEach((): void => {
|
afterEach((): void => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('starts the server with default settings.', async(): Promise<void> => {
|
it('starts the server with default settings.', async(): Promise<void> => {
|
||||||
runCli({
|
new CliRunner().run({
|
||||||
argv: [ 'node', 'script' ],
|
argv: [ 'node', 'script' ],
|
||||||
});
|
});
|
||||||
await initializer.handleSafe();
|
await initializer.handleSafe();
|
||||||
@ -55,7 +58,7 @@ describe('CliRunner', (): void => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts abbreviated flags.', async(): Promise<void> => {
|
it('accepts abbreviated flags.', async(): Promise<void> => {
|
||||||
runCli({
|
new CliRunner().run({
|
||||||
argv: [
|
argv: [
|
||||||
'node', 'script',
|
'node', 'script',
|
||||||
'-p', '4000',
|
'-p', '4000',
|
||||||
@ -87,7 +90,7 @@ describe('CliRunner', (): void => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts full flags.', async(): Promise<void> => {
|
it('accepts full flags.', async(): Promise<void> => {
|
||||||
runCli({
|
new CliRunner().run({
|
||||||
argv: [
|
argv: [
|
||||||
'node', 'script',
|
'node', 'script',
|
||||||
'--port', '4000',
|
'--port', '4000',
|
||||||
@ -118,15 +121,29 @@ describe('CliRunner', (): void => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('writes to stderr when an error occurs.', async(): Promise<void> => {
|
it('exits with output to stderr when instantiation fails.', async(): Promise<void> => {
|
||||||
const write = jest.spyOn(process.stderr, 'write').mockImplementation((): any => null);
|
|
||||||
loader.instantiateFromUrl.mockRejectedValueOnce(new Error('Fatal'));
|
loader.instantiateFromUrl.mockRejectedValueOnce(new Error('Fatal'));
|
||||||
|
new CliRunner().run();
|
||||||
runCli();
|
|
||||||
await new Promise((resolve): any => setImmediate(resolve));
|
await new Promise((resolve): any => setImmediate(resolve));
|
||||||
|
|
||||||
expect(write).toHaveBeenCalledTimes(1);
|
expect(write).toHaveBeenCalledTimes(2);
|
||||||
expect(write).toHaveBeenCalledWith('Error: Fatal\n');
|
expect(write).toHaveBeenNthCalledWith(1,
|
||||||
write.mockClear();
|
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