Added response time

This commit is contained in:
Alex Holliday committed 2024-06-17 11:05:22 -07:00
1 parent 14f68d58f7
commit a0ca205d6a
1 file changed
+29 -21
+29 -21
View File
@@ -11,49 +11,55 @@ class NetworkService {
} }
async handlePing(job) { async handlePing(job) {
const startTime = Date.now();
try { try {
const response = await ping.promise.probe(job.data.url); const response = await ping.promise.probe(job.data.url);
const isAlive = response.alive; const isAlive = response.alive;
await this.logAndStoreCheck(job, isAlive); const endTime = Date.now();
const responseTime = endTime - startTime;
await this.logAndStoreCheck(job, isAlive, responseTime);
return isAlive; return isAlive;
} catch (error) { } catch (error) {
await this.logAndStoreCheck(job, false, error); const endTime = Date.now();
const responseTime = endTime - startTime;
await this.logAndStoreCheck(job, false, responseTime, error);
return false; return false;
} }
} }
async handleHttp(job) { async handleHttp(job) {
try { try {
const startTime = Date.now();
const response = await axios.get(job.data.url); const response = await axios.get(job.data.url);
const isAlive = response.status >= 200 && response.status < 300; const isAlive = response.status >= 200 && response.status < 300;
await this.logAndStoreCheck(job, isAlive); const endTime = Date.now();
const responseTime = endTime - startTime;
await this.logAndStoreCheck(job, isAlive, responseTime);
return isAlive; return isAlive;
} catch (error) { } catch (error) {
await this.logAndStoreCheck(job, false, error); const endTime = Date.now();
const responseTime = endTime - startTime;
await this.logAndStoreCheck(job, false, responseTime, error);
return false; return false;
} }
} }
async getStatus(job) { async getStatus(job) {
try { switch (job.data.type) {
switch (job.data.type) { case this.TYPE_PING:
case this.TYPE_PING: return await this.handlePing(job);
return await this.handlePing(job); case this.TYPE_HTTP:
case this.TYPE_HTTP: return await this.handleHttp(job);
return await this.handleHttp(job); default:
default: console.error(`Unsupported type: ${job.data.type}`, {
console.error(`Unsupported type: ${job.data.type}`, { service: this.SERVICE_NAME,
service: this.SERVICE_NAME, timestamp: new Date().toISOString(),
timestamp: new Date().toISOString(), });
}); return false;
return false;
}
} catch (error) {
throw error;
} }
} }
async logAndStoreCheck(job, isAlive, error = null) { async logAndStoreCheck(job, isAlive, responseTime, error = null) {
const status = isAlive ? "alive" : "dead"; const status = isAlive ? "alive" : "dead";
if (error) { if (error) {
logger.error(`Error processing job ${job.id}: ${error.message}`, { logger.error(`Error processing job ${job.id}: ${error.message}`, {
@@ -65,7 +71,9 @@ class NetworkService {
} }
if (isAlive) { if (isAlive) {
console.log(`Job ${job.data.url} is alive`); console.log(
`Job ${job.data.url} is alive, response time: ${responseTime}ms`
);
return; return;
} }