Skip to content

Commit

Permalink
Merge pull request #163 from Chia-Network/refactor
Browse files Browse the repository at this point in the history
feat: stop server gracefully during tests
  • Loading branch information
MichaelTaylor3D authored Sep 26, 2023
2 parents 16710e4 + d2607c3 commit 2afd9f1
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 46 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "",
"main": "proxy.js",
"scripts": {
"test": "jest",
"test": "jest --detectOpenHandles",
"start": "node --no-warnings src/server.js",
"prepare-binary": "rm -rf dist && mkdir dist",
"create-win-x64-dist": "pkg package.json -t node16-win-x64 --out-path dist",
Expand Down
10 changes: 5 additions & 5 deletions src/api/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const wallet = require("../chia/wallet");
const utils = require("../utils");

const registryUri = utils.generateUriForHostAndPort(
CONFIG().REGISTRY.PROTOCOL,
CONFIG().REGISTRY.HOST,
CONFIG().REGISTRY.PORT
CONFIG().CADT.PROTOCOL,
CONFIG().CADT.HOST,
CONFIG().CADT.PORT
);

/**
Expand All @@ -18,8 +18,8 @@ const registryUri = utils.generateUriForHostAndPort(
* @returns {Object} Headers with API Key added if available
*/
const maybeAppendRegistryApiKey = (headers = {}) => {
if (CONFIG().REGISTRY.API_KEY) {
headers["x-api-key"] = CONFIG().REGISTRY.API_KEY;
if (CONFIG().CADT.API_KEY) {
headers["x-api-key"] = CONFIG().CADT.API_KEY;
}
return headers;
};
Expand Down
12 changes: 6 additions & 6 deletions src/api/token-driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ const {
} = require("../utils");

const tokenDriverUri = generateUriForHostAndPort(
CONFIG().TOKEN_DRIVER.PROTOCOL,
CONFIG().TOKEN_DRIVER.HOST,
CONFIG().TOKEN_DRIVER.PORT
CONFIG().CHIA_CLIMATE_TOKENIZATION.PROTOCOL,
CONFIG().CHIA_CLIMATE_TOKENIZATION.HOST,
CONFIG().CHIA_CLIMATE_TOKENIZATION.PORT
);

/**
Expand All @@ -20,8 +20,8 @@ const tokenDriverUri = generateUriForHostAndPort(
* @returns {Object} Headers with API Key added if available
*/
const maybeAppendTokenDriverApiKey = (headers = {}) => {
if (CONFIG().TOKEN_DRIVER.API_KEY) {
headers["x-api-key"] = CONFIG().TOKEN_DRIVER.API_KEY;
if (CONFIG().CHIA_CLIMATE_TOKENIZATION.API_KEY) {
headers["x-api-key"] = CONFIG().CHIA_CLIMATE_TOKENIZATION.API_KEY;
}
return headers;
};
Expand Down Expand Up @@ -129,7 +129,7 @@ const createToken = async (tokenizationBody) => {
);
}

logger.debug(`Token creation response: ${JSON.stringify(response.body)}`);
logger.trace(`Token creation response: ${JSON.stringify(response.body)}`);

return response?.body;
} catch (error) {
Expand Down
18 changes: 9 additions & 9 deletions src/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ const { updateQueryWithParam, generateUriForHostAndPort } = require("./utils");
const { CONFIG } = require("./config");

const registryUri = generateUriForHostAndPort(
CONFIG().REGISTRY.PROTOCOL,
CONFIG().REGISTRY.HOST,
CONFIG().REGISTRY.PORT
CONFIG().CADT.PROTOCOL,
CONFIG().CADT.HOST,
CONFIG().CADT.PORT
);

const getTokenizedUnits = () => {
Expand All @@ -26,8 +26,8 @@ const getTokenizedUnits = () => {
return "/v1/units" + newQuery;
},
onProxyReq: (proxyReq) => {
if (CONFIG().REGISTRY.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().REGISTRY.API_KEY);
if (CONFIG().CADT.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().CADT.API_KEY);
}
},
onProxyRes: async (proxyRes) => {
Expand Down Expand Up @@ -55,8 +55,8 @@ const getProjectsFromRegistry = () => {
return "/v1/projects" + newQuery;
},
onProxyReq: (proxyReq) => {
if (CONFIG().REGISTRY.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().REGISTRY.API_KEY);
if (CONFIG().CADT.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().CADT.API_KEY);
}
},
onProxyRes: async (proxyRes) => {
Expand Down Expand Up @@ -87,8 +87,8 @@ const getUntokenizedUnits = () => {
return "/v1/units" + newQuery;
},
onProxyReq: (proxyReq) => {
if (CONFIG().REGISTRY.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().REGISTRY.API_KEY);
if (CONFIG().CADT.API_KEY) {
proxyReq.setHeader("x-api-key", CONFIG().CADT.API_KEY);
}
},
onProxyRes: async (proxyRes) => {
Expand Down
55 changes: 40 additions & 15 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,12 @@ app.get("/health", (req, res) => {
});

// Initialize server
let shouldListen = false;

// Check if CONFIG.TOKENIZATION_ENGINE.HOST is either "localhost" or "127.0.0.1"
// OR if CONFIG.TOKENIZATION_ENGINE.API_KEY exists.
// In either case, set shouldListen to true.
if (
["localhost", "127.0.0.1"].includes(CONFIG().TOKENIZATION_ENGINE.HOST) ||
CONFIG().TOKENIZATION_ENGINE.API_KEY
) {
shouldListen = true;
}
let server;

if (shouldListen) {
app.listen(
const startServer = () => {
server = app.listen(
CONFIG().TOKENIZATION_ENGINE.PORT,
CONFIG().TOKENIZATION_ENGINE.HOST,
CONFIG().TOKENIZATION_ENGINE.BIND_ADDRESS,
() => {
logger.info(
`Application is running on port ${CONFIG().TOKENIZATION_ENGINE.PORT}.`
Expand All @@ -93,10 +83,45 @@ if (shouldListen) {
if (CONFIG().GENERAL.CORE_REGISTRY_MODE) {
setTimeout(() => scheduler.start(), 5000);
}
};

const stopServer = () => {
if (server) {
server.close((err) => {
if (err) {
logger.error("Error closing server:", err);
} else {
logger.info("Server closed gracefully.");
}
});
}
};

let shouldListen = false;

// Check if CONFIG.TOKENIZATION_ENGINE.BIND_ADDRESS is either "localhost" or "127.0.0.1"
// OR if CONFIG.TOKENIZATION_ENGINE.API_KEY exists.
// In either case, set shouldListen to true.
if (
["localhost", "127.0.0.1"].includes(
CONFIG().TOKENIZATION_ENGINE.BIND_ADDRESS
) ||
CONFIG().TOKENIZATION_ENGINE.API_KEY
) {
shouldListen = true;
}

if (shouldListen) {
startServer();
} else {
logger.warn(
"Server not started due to missing CONFIG.TOKENIZATION_ENGINE.API_KEY on a non-local host."
);
}

module.exports = app;
// Export the start and stop server functions
module.exports = {
app,
startServer,
stopServer,
};
2 changes: 1 addition & 1 deletion src/tasks/sync-retirements.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const task = new Task("sync-retirements", async () => {
await startSyncRetirementsTask();
}
} catch (error) {
logger.task_error(`Error in sync-retirements task: ${error.message}`);
logger.error(`Error in sync-retirements task: ${error.message}`);
} finally {
isTaskInProgress = false;
}
Expand Down
5 changes: 3 additions & 2 deletions src/utils/defaultConfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"CERTIFICATE_FOLDER_PATH": null,
"ALLOW_SELF_SIGNED_CERTIFICATES": true
},
"REGISTRY": {
"CADT": {
"PROTOCOL": "http",
"HOST": "127.0.0.1",
"PORT": 31310,
Expand All @@ -22,7 +22,7 @@
"PORT": 31313,
"API_KEY": null
},
"TOKEN_DRIVER": {
"CHIA_CLIMATE_TOKENIZATION": {
"PROTOCOL": "http",
"HOST": "127.0.0.1",
"PORT": 31312,
Expand All @@ -33,6 +33,7 @@
"HOST": "127.0.0.1",
"API_KEY": null,
"PORT": 31311,
"BIND_ADDRESS": "localhost",
"UNITS_FILTER": "unitStatus:[\"Retired\", \"Cancelled\", \"Expired\"]:not",
"TASKS": {
"SYNC_RETIREMENTS_TO_REGISTRY_INTERVAL_SECONDS": 300
Expand Down
17 changes: 10 additions & 7 deletions tests/create-token.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const sinon = require("sinon");
const request = require("supertest");
const nock = require("nock");

const app = require("../src/server");
const { app, stopServer } = require("../src/server");
const wallet = require("../src/chia/wallet");
const registry = require("../src/api/registry");
const tokenDriver = require("../src/api/token-driver");
Expand All @@ -14,14 +14,12 @@ const { CONFIG, setConfig } = require("../src/config");

// Create a nock interceptor for the registry API
const registryMock = nock(
`${CONFIG().REGISTRY.PROTOCOL}://${CONFIG().REGISTRY.HOST}:${
CONFIG().REGISTRY.PORT
}`
`${CONFIG().CADT.PROTOCOL}://${CONFIG().CADT.HOST}:${CONFIG().CADT.PORT}`
);
const tokenDriverMock = nock(
`${CONFIG().TOKEN_DRIVER.PROTOCOL}://${CONFIG().TOKEN_DRIVER.HOST}:${
CONFIG().TOKEN_DRIVER.PORT
}`
`${CONFIG().CHIA_CLIMATE_TOKENIZATION.PROTOCOL}://${
CONFIG().CHIA_CLIMATE_TOKENIZATION.HOST
}:${CONFIG().CHIA_CLIMATE_TOKENIZATION.PORT}`
);

describe("Create Token Process", () => {
Expand Down Expand Up @@ -56,6 +54,11 @@ describe("Create Token Process", () => {
nock.cleanAll();
});

afterAll(async () => {
// Close the server gracefully
await stopServer();
});

it("health check", async () => {
const response = await request(app).get("/health");
expect(response.status).to.equal(200);
Expand Down

0 comments on commit 2afd9f1

Please sign in to comment.