Skip to content

Commit

Permalink
Code re-structuring
Browse files Browse the repository at this point in the history
  • Loading branch information
Eswar2103 committed Aug 26, 2024
1 parent 3c8f42e commit 54eab54
Show file tree
Hide file tree
Showing 9 changed files with 145 additions and 124 deletions.
4 changes: 2 additions & 2 deletions server/src/configureAPI.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ function configureAPI(app) {
app.post('/api/v1/state/revert', stateApi.revertState);

// Start the interaction log service
app.post('/api/v1/user/enableInteractionLogs', userApi.enableInteractionLogs);
app.post('/api/v1/state/interactionLogs/start', stateApi.enableInteractionLogs);

// Stop the interaction log service
app.post('/api/v1/user/disableInteractionLogs', userApi.disableInteractionLogs);
app.post('/api/v1/state/interactionLogs/stop', stateApi.disableInteractionLogs);

// ======================= State-Related API Routes =======================

Expand Down
3 changes: 2 additions & 1 deletion server/src/events.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import { logger } from './logger.mjs';
import * as fireboltOpenRpc from './fireboltOpenRpc.mjs';
import { config } from './config.mjs';
import { updateCallWithResponse } from './sessionManagement.mjs';
import { createCaseAgnosticMethod, createAndSendInteractionLog } from './util.mjs';
import { createCaseAgnosticMethod } from './util.mjs';
import { createAndSendInteractionLog } from './interactionService.mjs';


const { dotConfig: { eventConfig } } = config;
Expand Down
64 changes: 64 additions & 0 deletions server/src/interactionLog.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/

// InteractionLogs

import { logger } from './logger.mjs';

/**
* @function: createAndSendInteractionLog
* @Description: Create interaction log and send it to the client
* @param {String} response - Response of the method call
* @param {String} method - Name of the method
* @param {String} params - Params of the method call
* @param {Object} ws - WS object to send the interaction log
* @param {String} ws - UserId value
*/
function createAndSendInteractionLog(response, method, params, ws, userId) {
try {
const interactionLog = {
app_id: "mock-firebolt",
method: "",
params: "",
success: true,
response: "",
};

interactionLog.params = params;
interactionLog.method = method;
interactionLog.response = response;
if (ws) {
ws.send(JSON.stringify({ FireboltInteraction: interactionLog }));
logger.debug(
`Sent interaction log for user ${userId}: ${JSON.stringify({
FireboltInteraction: interactionLog,
})}`
);
} else {
logger.error(
`Error in createAndSendInteractionLog: ws object is not provided`
);
}
} catch (error) {
logger.error(`Error in createAndSendInteractionLog: ${error}`);
}
}

// ----exports----

export { createAndSendInteractionLog };
3 changes: 2 additions & 1 deletion server/src/messageHandler.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { addCall, updateCallWithResponse } from './sessionManagement.mjs';
import * as proxyManagement from './proxyManagement.mjs';
import * as conduit from './conduit.mjs';
import { config } from './config.mjs';
import { createAndSendInteractionLog } from './interactionLog.mjs';

const { dotConfig: { eventConfig } } = config;

Expand Down Expand Up @@ -352,7 +353,7 @@ async function handleMessage(message, userId, ws) {

config.interactionService && config.interactionService.forEach((_, userId) => {
const userWSData = userManagement.getWsForUser(userId);
util.createAndSendInteractionLog(finalResponse, JSON.parse(message).method, JSON.parse(message).params, userWSData, userId); // creating interaction log and send it to the client
createAndSendInteractionLog(finalResponse, JSON.parse(message).method, JSON.parse(message).params, userWSData, userId); // creating interaction log and send it to the client
});
}

Expand Down
39 changes: 38 additions & 1 deletion server/src/routes/api/state.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -289,11 +289,48 @@ function revertState(req, res) {
});
}

// POST /api/v1/state/enableInteractionLogs
// Expected body: None
// Expected headers: x-mockfirebolt-userid - The user id of the user making the request
function enableInteractionLogs(req, res) {
const user = getUserIdFromReq(req);
logger.info(`Enabling interaction logs for user ${user}`);
config.interactionService == undefined &&
(config.interactionService = new Map());
config.interactionService.set(user, { enabled: true });
return res.status(200).send({
status: "SUCCESS",
message: "Successfully started interactionService",
});
}

// POST /api/v1/state/disableInteractionLogs
// Expected body: None
// Expected headers: x-mockfirebolt-userid - The user id of the user making the request
function disableInteractionLogs(req, res) {
const user = getUserIdFromReq(req);
logger.info(`Disabling interaction logs for user ${user}`);
// If the user is not found in the interactionService, return an error
if (!config.interactionService.has(user)) {
return res.status(400).send({
status: "ERROR",
errorCode: "USER-NOT-FOUND",
message: "User not found",
});
}
config.interactionService.delete(user);
return res.status(200).send({
status: "SUCCESS",
message: "Successfully stopped interactionService",
});
}

// --- Exports ---

export {
getState,
setLatency, setMode,
setMethodResult, setMethodError,
updateState, revertState
updateState, revertState,
enableInteractionLogs, disableInteractionLogs
};
71 changes: 1 addition & 70 deletions server/src/routes/api/user.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import { v4 as uuidv4 } from 'uuid';
import * as userManagement from '../../userManagement.mjs';
import * as stateManagement from '../../stateManagement.mjs';
import { config } from '../../config.mjs';
import { logger } from '../../logger.mjs';


Expand Down Expand Up @@ -85,76 +84,8 @@ function getUsers(req, res) {
});
}

// POST /api/v1/state/enableInteractionLogs
// Expected body: { enabled: true }
// Expected headers: x-mockfirebolt-userid - The user id of the user making the request
// E.g., { enabled: true }
function enableInteractionLogs(req, res) {
if (req.body.hasOwnProperty("enabled")) {
if (req.body.enabled !== true) {
return res.status(400).send({
status: "ERROR",
errorCode: "INVALID-ENABLED-VALUE",
message: "Enabled value must be true",
});
}
const user = req.get("x-mockfirebolt-userid");
config.interactionService == undefined && (config.interactionService = new Map());
config.interactionService.set(user, req.body);
return res.status(200).send({
status: "SUCCESS",
message: "Successfully started interactionService",
});
} else {
return res.status(400).send({
status: "ERROR",
errorCode: "MISSING-STATE",
message: "Did not find expected 'enabled' key within post body",
});
}
}

// POST /api/v1/state/disableInteractionLogs
// Expected body: { enabled: false }
// Expected headers: x-mockfirebolt-userid - The user id of the user making the request
// E.g., { enabled: false }
function disableInteractionLogs(req, res) {
if (req.body.hasOwnProperty("enabled")) {
if (req.body.enabled !== false) {
// If the incoming request enabled value is not `false`, return an error
return res.status(400).send({
status: "ERROR",
errorCode: "INVALID-ENABLED-VALUE",
message: "Enabled value must be false",
});
}
const user = req.get("x-mockfirebolt-userid");
// If the user is not found in the interactionService, return an error
if (!config.interactionService.has(user)) {
return res.status(400).send({
status: "ERROR",
errorCode: "USER-NOT-FOUND",
message: "User not found in interactionService",
});
}
config.interactionService.delete(user);
return res.status(200).send({
status: "SUCCESS",
message: "Successfully stopped interactionService",
});
} else {
// If the incoming request does not have an enabled key, return an error
return res.status(400).send({
status: "ERROR",
errorCode: "MISSING-STATE",
message: "Did not find expected 'enabled' key within post body",
});
}
}


// --- Exports ---

export {
addUser,getUsers,enableInteractionLogs,disableInteractionLogs
addUser,getUsers
};
36 changes: 1 addition & 35 deletions server/src/util.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { fileURLToPath } from 'url';
import path from 'path';

import fs from 'fs';
import { logger } from './logger.mjs';

// Use: await delay(2000);
function delay(ms) {
Expand Down Expand Up @@ -170,39 +169,6 @@ function createCaseAgnosticMethod(method){
return method;
}

/**
* @function: createAndSendInteractionLog
* @Description: Create interaction log and send it to the client
* @param {String} response - Response of the method call
* @param {String} method - Name of the method
* @param {String} params - Params of the method call
* @param {Object} ws - WS object to send the interaction log
* @param {String} ws - UserId value
*/
function createAndSendInteractionLog(response, method, params, ws, userId) {
try {
const interactionLog = {
app_id: "mock-firebolt",
method: "",
params: "",
success: true,
response: "",
};

interactionLog.params = params;
interactionLog.method = method;
interactionLog.response = response;
if (ws) {
ws.send(JSON.stringify({ FireboltInteraction: interactionLog }));
logger.debug(`Sent interaction log for user ${userId}: ${JSON.stringify({ FireboltInteraction: interactionLog })}`);
} else {
logger.error(`Error in createAndSendInteractionLog: ws object is not provided`);
}
} catch (error) {
logger.error(`Error in createAndSendInteractionLog: ${error}`);
}
}

// --- Exports ---

export { delay, randomIntFromInterval, getUserIdFromReq, createTmpFile, mergeArrayOfStrings, createAbsoluteFilePath, getCreationDate, getModificationDate, searchObjectForKey, replaceKeyInObject, createCaseAgnosticMethod, createAndSendInteractionLog };
export { delay, randomIntFromInterval, getUserIdFromReq, createTmpFile, mergeArrayOfStrings, createAbsoluteFilePath, getCreationDate, getModificationDate, searchObjectForKey, replaceKeyInObject, createCaseAgnosticMethod };
35 changes: 35 additions & 0 deletions server/test/suite/interactionLogs.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/

// InteractionLogs: Tests

import {jest} from '@jest/globals';
import { createAndSendInteractionLog } from "../../src/interactionLog.mjs";
import { logger } from "../../src/logger.mjs";

test(`interactionLogs.createAndSendInteractionLog works properly`, () => {
const debugSpy = jest.spyOn(logger, "debug");
createAndSendInteractionLog('{name: "id"}', "account.id", {}, {send: () => {}}, '12345' );
expect(debugSpy).toHaveBeenCalled();
});

test(`interactionLogs.createAndSendInteractionLog works properly without ws object`, () => {
const errorSpy = jest.spyOn(logger, "error");
createAndSendInteractionLog('{name: "id"}', "account.id", {}, undefined );
expect(errorSpy).toHaveBeenCalled();
});
14 changes: 0 additions & 14 deletions server/test/suite/util.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
import {jest} from '@jest/globals';
import * as fs from 'fs';
import * as util from '../../src/util.mjs';
import { logger } from "../../src/logger.mjs";
import { config } from "../../src/config.mjs";

test(`util.delay works properly`, () => {
jest.useFakeTimers();
Expand Down Expand Up @@ -100,15 +98,3 @@ test(`util.mergeArrayOfStrings works properly`, () => {
);
expect(result).toEqual(["test"]);
});

test(`util.createAndSendInteractionLog works properly`, () => {
const debugSpy = jest.spyOn(logger, "debug");
util.createAndSendInteractionLog('{name: "id"}', "account.id", {}, {send: () => {}}, '12345' );
expect(debugSpy).toHaveBeenCalled();
});

test(`util.createAndSendInteractionLog works properly without ws object`, () => {
const errorSpy = jest.spyOn(logger, "error");
util.createAndSendInteractionLog('{name: "id"}', "account.id", {}, undefined );
expect(errorSpy).toHaveBeenCalled();
});

0 comments on commit 54eab54

Please sign in to comment.