Skip to content

Commit

Permalink
chore: added support for stats calculation middleware on the endpoint…
Browse files Browse the repository at this point in the history
… customTransform
  • Loading branch information
abhimanyubabbar committed Nov 15, 2024
1 parent 6554893 commit 90777ec
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
15 changes: 15 additions & 0 deletions src/middlewares/stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Context, Next } from 'koa';

export class StatsMiddleware {
private static instanceID: string = process.env.INSTANCE_ID || 'unknown';

private static workerID: string = process.env.WORKER_ID || 'unknown';

public static async executionStats(ctx: Context, next: Next) {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
ctx.set('X-Instance-ID', `${StatsMiddleware.instanceID}/${StatsMiddleware.workerID}`);
}
}
7 changes: 5 additions & 2 deletions src/routes/userTransform.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import Router from '@koa/router';
import { RouteActivationMiddleware } from '../middlewares/routeActivation';
import { FeatureFlagMiddleware } from '../middlewares/featureFlag';
import { Context } from 'koa';
import { UserTransformController } from '../controllers/userTransform';
import { FeatureFlagMiddleware } from '../middlewares/featureFlag';
import { RouteActivationMiddleware } from '../middlewares/routeActivation';
import { StatsMiddleware } from '../middlewares/stats';

const router = new Router();

Expand All @@ -15,6 +17,7 @@ router.post(
'/customTransform',
RouteActivationMiddleware.isUserTransformRouteActive,
FeatureFlagMiddleware.handle,
StatsMiddleware.executionStats,
UserTransformController.transform,
);
router.post(
Expand Down
6 changes: 5 additions & 1 deletion src/util/cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ async function shutdownWorkers() {
}

function start(port, app, metricsApp) {
console.log(numWorkers);

if (cluster.isMaster) {
logger.info(`Master (pid: ${process.pid}) has started`);

Expand All @@ -44,7 +46,9 @@ function start(port, app, metricsApp) {

// Fork workers.
for (let i = 0; i < numWorkers; i += 1) {
cluster.fork();
cluster.fork({
WORKER_ID: `worker-${i + 1}`,
});
}

cluster.on('online', (worker) => {
Expand Down

0 comments on commit 90777ec

Please sign in to comment.