Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
myrotvorets-team committed Oct 14, 2023
1 parent df309b7 commit 732c946
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 37 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"@myrotvorets/facex": "^2.6.1",
"@myrotvorets/oav-installer": "^4.1.1",
"@myrotvorets/opentelemetry-configurator": "^7.0.0",
"@myrotvorets/otel-utils": "^0.0.9",
"@myrotvorets/otel-utils": "^0.0.10",
"@opentelemetry/api": "^1.6.0",
"@opentelemetry/core": "^1.17.1",
"@opentelemetry/semantic-conventions": "^1.17.1",
Expand Down
7 changes: 2 additions & 5 deletions src/controllers/compare.mts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,10 @@ async function statusHandler(
}

export function compareController(): Router {
const router = Router();
const router = Router({ strict: true, caseSensitive: true });

router.post('/compare', asyncWrapperMiddleware(startCompareHandler));
router.get(
'/compare/:guid([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})',
asyncWrapperMiddleware(statusHandler),
);
router.get('/compare/:guid', asyncWrapperMiddleware(statusHandler));

router.use(uploadErrorHandlerMiddleware);
router.use(faceXErrorHandlerMiddleware);
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/count.mts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async function countHandler(
}

export function countController(): Router {
const router = Router();
const router = Router({ strict: true, caseSensitive: true });
router.get('/count', asyncWrapperMiddleware(countHandler));
router.use(faceXErrorHandlerMiddleware);
return router;
Expand Down
37 changes: 24 additions & 13 deletions src/controllers/search.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type Request, type Response, Router } from 'express';
import { type NextFunction, type Request, type Response, Router } from 'express';
import type { SearchStats } from '@myrotvorets/facex';
import { asyncWrapperMiddleware } from '@myrotvorets/express-async-middleware-wrapper';
import type { MatchedFace, RecoginizedFace } from '../services/search.mjs';
Expand Down Expand Up @@ -73,9 +73,9 @@ async function capturedFacesHandler(

interface MatchedFacesParams {
guid: string;
faceid: string;
offset: string;
count: string;
faceid: number;
offset: number;
count: number;
}

interface MatchedFacesResponse {
Expand All @@ -87,23 +87,34 @@ async function matchedFacesHandler(
req: Request<MatchedFacesParams, MatchedFacesResponse, never, never, LocalsWithContainer>,
res: Response<MatchedFacesResponse, LocalsWithContainer>,
): Promise<void> {
const { guid } = req.params;
const { guid, faceid, offset, count } = req.params;
const service = res.locals.container.resolve('searchService');
const faceid = parseInt(req.params.faceid, 10);
const offset = parseInt(req.params.offset, 10);
const count = parseInt(req.params.count, 10);
const result = await service.matchedFaces(guid, faceid, offset, count);
res.json({ success: true, matches: result });
}

function intParamHandler(
req: Request<Record<string, unknown>>,
_res: Response,
next: NextFunction,
value: string,
name: string,
): void {
req.params[name] = +value;
next();
}

export function searchController(): Router {
const router = Router();
const guid = '[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}';
const router = Router({ strict: true, caseSensitive: true });

router.param('offset', intParamHandler);
router.param('count', intParamHandler);
router.param('faceid', intParamHandler);

router.post('/search', asyncWrapperMiddleware(startSearchHandler));
router.get(`/search/:guid(${guid})`, asyncWrapperMiddleware(statusHandler));
router.get(`/search/:guid(${guid})/captured`, asyncWrapperMiddleware(capturedFacesHandler));
router.get(`/search/:guid(${guid})/matches/:faceid/:offset/:count`, asyncWrapperMiddleware(matchedFacesHandler));
router.get(`/search/:guid`, asyncWrapperMiddleware(statusHandler));
router.get(`/search/:guid/captured`, asyncWrapperMiddleware(capturedFacesHandler));
router.get(`/search/:guid/matches/:faceid/:offset/:count`, asyncWrapperMiddleware(matchedFacesHandler));

router.use(uploadErrorHandlerMiddleware);
router.use(faceXErrorHandlerMiddleware);
Expand Down
31 changes: 31 additions & 0 deletions src/lib/metrics.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* c8 ignore start */
import { ValueType } from '@opentelemetry/api';
import { getMeter } from '@myrotvorets/otel-utils';
import type { Container } from './container.mjs';

type AsyncMetricOptions = Pick<Container, 'faceXClient' | 'meter'>;

export function initAsyncMetrics({ meter, faceXClient }: AsyncMetricOptions): void {
meter
.createObservableUpDownCounter('facex.faces.count', {
description: 'Number of stored faces',
unit: '{count}',
valueType: ValueType.INT,
})
.addCallback(async (result) => {
try {
const r = await faceXClient.baseStatus();
result.observe(r.numberOfRecords);
} catch {
result.observe(NaN);
}
});
}

export const requestDurationHistogram = getMeter().createHistogram('psbapi.request.duration', {
description: 'Measures the duration of requests.',
unit: 'ms',
valueType: ValueType.DOUBLE,
});

/* c8 ignore stop */
11 changes: 0 additions & 11 deletions src/lib/otel.mts

This file was deleted.

2 changes: 1 addition & 1 deletion src/middleware/duration.mts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { RequestHandler } from 'express';
import { hrTime, hrTimeDuration, hrTimeToMilliseconds } from '@opentelemetry/core';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { requestDurationHistogram } from '../lib/otel.mjs';
import { requestDurationHistogram } from '../lib/metrics.mjs';

export const requestDurationMiddleware: RequestHandler = (req, res, next): void => {
const start = hrTime();
Expand Down
4 changes: 3 additions & 1 deletion src/server.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import express, { type Express } from 'express';
import { cleanUploadedFilesMiddleware } from '@myrotvorets/clean-up-after-multer';
import { errorMiddleware, notFoundMiddleware } from '@myrotvorets/express-microservice-middlewares';
import { installOpenApiValidator } from '@myrotvorets/oav-installer';

import { createServer, getTracer, recordErrorToSpan } from '@myrotvorets/otel-utils';

import { initializeContainer, scopedContainerMiddleware } from './lib/container.mjs';
import { initAsyncMetrics } from './lib/metrics.mjs';

import { requestDurationMiddleware } from './middleware/duration.mjs';
import { loggerMiddleware } from './middleware/logger.mjs';
Expand Down Expand Up @@ -58,6 +59,7 @@ export function configureApp(app: Express): Promise<ReturnType<typeof initialize
errorMiddleware,
);

initAsyncMetrics(container.cradle);
return container;
} /* c8 ignore start */ catch (e) {
recordErrorToSpan(e, span);
Expand Down

0 comments on commit 732c946

Please sign in to comment.