Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] upgrade hapi #571

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
upgrade to @happi/hapi
  • Loading branch information
AlvaroVega committed Dec 21, 2021
commit 2b0be8399bf875b3dab1464b33ad28da609a03a2
140 changes: 78 additions & 62 deletions lib/server/sthServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const sthRemoveDataHandler = require(ROOT_PATH + '/lib/server/handlers/sthRemove
const sthGetLogLevelHandler = require(ROOT_PATH + '/lib/server/handlers/sthGetLogLevelHandler');
const sthSetLogLevelHandler = require(ROOT_PATH + '/lib/server/handlers/sthSetLogLevelHandler');
const sthNotFoundHandler = require(ROOT_PATH + '/lib/server/handlers/sthNotFoundHandler');
const hapi = require('hapi');
const hapi = require('@hapi/hapi');
const joi = require('joi');

let server;
Expand All @@ -57,15 +57,21 @@ function doStartServer(host, port, callback) {
* @param ngsiVersion NGSI version to use. Anything different from 2 (included undefined) means v1
*/
function getNgsiHandlerConfig(ngsiVersion) {
function failActionHandler(request, reply, source, error) {
function failActionHandler(request, reply, error) {
sthLogger.info('failActionHandler %j', error);
let response;
// In the case of NGSIv2, this function adapts from the error response format used
// by hapi to the one used in NGSIv2
reply({ error: 'BadRequest', description: error.output.payload.message }).code(400);
response = reply
.response({ error: 'BadRequest', description: error.output.payload.message })
.code(400)
.takeover();
return response;
}

const config = {
const options = {
validate: {
headers: sthHeaderValidator,
//headers: sthHeaderValidator,
query: {
// prettier-ignore
lastN: joi.number().integer().greater(-1).optional(),
Expand All @@ -88,47 +94,19 @@ function doStartServer(host, port, callback) {
};

if (ngsiVersion === 2) {
config.validate.failAction = failActionHandler;
options.validate.failAction = failActionHandler;

// In NGSIv2 type query param is mandatory
config.validate.query.type = joi.string().required();
options.validate.query.type = joi.string().required();
}

return config;
return options;
}

server = new hapi.Server();

server.on('log', function(event, tags) {
if (tags.load) {
sthLogger.warn(sthConfig.LOGGING_CONTEXT.SERVER_LOG, 'event=' + JSON.stringify(event));
}
});

server.on('request-internal', function(request, event, tags) {
if (tags.error) {
processedRequestsWithError++;
if (tags.auth || tags.handler || tags.state || tags.payload || tags.validation) {
sthLogger.warn(
sthServerUtils.getContext(request),
request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event)
);
} else {
sthLogger.error(
sthServerUtils.getContext(request),
request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event)
);
}
} else if (tags.error === undefined && request._isReplied) {
attendedRequests++;
}
});

if (sthConfig.corsEnabled) {
sthLogger.info('CORS is enabled');
server.connection({
host,
port,
server = new hapi.Server({
host: host,
port: port,
routes: {
cors: {
origin: sthConfig.corsOptions.origin,
Expand All @@ -140,24 +118,49 @@ function doStartServer(host, port, callback) {
});
} else {
sthLogger.info('CORS is disabled');
server.connection({
host,
port
server = new hapi.Server({
host: host,
port: port
});
}

server.events.on('log', function(event, tags) {
if (tags.load) {
sthLogger.warn(sthConfig.LOGGING_CONTEXT.SERVER_LOG, 'event=' + JSON.stringify(event));
}
});

// server.events.on('request-internal', function(request, event, tags) {
// if (tags.error) {
// processedRequestsWithError++;
// if (tags.auth || tags.handler || tags.state || tags.payload || tags.validation) {
// sthLogger.warn(
// sthServerUtils.getContext(request),
// request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event)
// );
// } else {
// sthLogger.error(
// sthServerUtils.getContext(request),
// request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event)
// );
// }
// } else if (tags.error === undefined && request._isReplied) {
// attendedRequests++;
// }
// });

server.route([
{
method: 'GET',
path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}/attributes/{attrName}',
handler: sthGetDataHandler,
config: getNgsiHandlerConfig(1)
options: getNgsiHandlerConfig(1)
},
{
method: 'GET',
path: '/STH/v2/entities/{entityId}/attrs/{attrName}',
handler: sthGetDataHandlerV2,
config: getNgsiHandlerConfig(2)
options: getNgsiHandlerConfig(2)
},
{
method: 'GET',
Expand All @@ -168,47 +171,47 @@ function doStartServer(host, port, callback) {
method: 'POST',
path: '/notify',
handler: sthNotificationHandler,
config: {
options: {
validate: {
headers: sthHeaderValidator
//headers: sthHeaderValidator // TBD
}
}
},
{
method: 'DELETE',
path: '/STH/v1/contextEntities',
handler: sthRemoveDataHandler,
config: {
options: {
validate: {
headers: sthHeaderValidator
//headers: sthHeaderValidator // TBD
}
}
},
{
method: 'DELETE',
path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}',
handler: sthRemoveDataHandler,
config: {
options: {
validate: {
headers: sthHeaderValidator
//headers: sthHeaderValidator // TBD
}
}
},
{
method: 'DELETE',
path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}/attributes/{attrName}',
handler: sthRemoveDataHandler,
config: {
options: {
validate: {
headers: sthHeaderValidator
//headers: sthHeaderValidator // TBD
}
}
},
{
method: 'PUT',
path: '/admin/log',
handler: sthSetLogLevelHandler,
config: {
options: {
validate: {
query: {
// prettier-ignore
Expand All @@ -228,11 +231,17 @@ function doStartServer(host, port, callback) {
handler: sthNotFoundHandler
}
]);

// Start the server
server.start(function(err) {
return callback(err, server);
});
server
.start()
.then(() => {
sthLogger.info('Server running on %s', server.info.uri);
return callback(null, server);
}) // if needed
.catch((err) => {
sthLogger.error('Server error %s', err);
return callback(err, null);
});
}

/**
Expand All @@ -257,11 +266,18 @@ function startServer(host, port, callback) {
function stopServer(callback) {
sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'Stopping the STH server...');
if (server && server.info && server.info.started) {
server.stop(function(err) {
// Server successfully stopped
sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server successfully stopped');
return callback(err);
});
// or use a promise
server
.stop()
.then(() => {
// Server successfully stopped
sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server successfully stopped');
return callback(null);
}) // if needed
.catch((err) => {
sthLogger.error(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server error stopped %s', err);
return callback(err);
});
} else {
sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'No hapi server running');
return process.nextTick(callback);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@
"watch": "~1.0.2"
},
"dependencies": {
"@hapi/hapi": "17.9.0",
"app-root-path": "~1.2.1",
"async": "~2.0.0-rc.5",
"boom": "7.2.2",
"bytes-counter": "~1.0.0",
"commander": "~2.9.0",
"csv-parser": "~1.9.3",
"hapi": "17.8.5",
"joi": "14.0.6",
"json-csv": "1.5.0",
"lodash": "~4.17.5",
Expand Down
2 changes: 1 addition & 1 deletion test/unit/sthGetLogLevelHandler_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration');
const sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming');
const sthTestConfig = require(ROOT_PATH + '/test/unit/sthTestConfiguration');
const sthTestHelper = require(ROOT_PATH + '/test/unit/sthTestUtils.js');
const hapi = require('hapi');
const hapi = require('@hapi/hapi');
const expect = require('expect.js');
const request = require('request');

Expand Down
2 changes: 1 addition & 1 deletion test/unit/sth_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const sthTestConfig = require(ROOT_PATH + '/test/unit/sthTestConfiguration');
const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration');
const sthTestUtils = require(ROOT_PATH + '/test/unit/sthTestUtils.js');
const sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming');
const hapi = require('hapi');
const hapi = require('@hapi/hapi');
const request = require('request');
const expect = require('expect.js');

Expand Down