-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7b7cd3c
commit fd2a3ac
Showing
15 changed files
with
656 additions
and
466 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
const env = { ...process.env }; | ||
process.env = { | ||
NODE_ENV: 'test', | ||
OTEL_SDK_DISABLED: 'true', | ||
KNEX_DRIVER: 'better-sqlite3', | ||
KNEX_DATABASE: ':memory:', | ||
}; | ||
|
||
/** @type {import('mocha').RootHookObject} */ | ||
export const mochaHooks = { | ||
afterAll() { | ||
process.env = { ...env }; | ||
}, | ||
}; |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,23 @@ | ||
/* c8 ignore start */ | ||
import { configure } from './lib/tracing.mjs'; | ||
import { run } from './server.mjs'; | ||
import { OpenTelemetryConfigurator, getExpressInstrumentations } from '@myrotvorets/opentelemetry-configurator'; | ||
import { KnexInstrumentation } from '@myrotvorets/opentelemetry-plugin-knex'; | ||
import { initProcessMetrics } from '@myrotvorets/otel-utils'; | ||
|
||
configure(); | ||
run().catch((e) => console.error(e)); | ||
process.env['OTEL_SERVICE_NAME'] = 'psb-api-identigraf-auth'; | ||
|
||
export const configurator = new OpenTelemetryConfigurator({ | ||
serviceName: process.env['OTEL_SERVICE_NAME'], | ||
instrumentations: [...getExpressInstrumentations(), new KnexInstrumentation()], | ||
}); | ||
|
||
configurator.start(); | ||
|
||
await initProcessMetrics(); | ||
|
||
try { | ||
const { run } = await import('./server.mjs'); | ||
await run(); | ||
} catch (e) { | ||
console.error(e); | ||
} | ||
/* c8 ignore stop */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import { AwilixContainer, asFunction, asValue, createContainer } from 'awilix'; | ||
import type { NextFunction, Request, Response } from 'express'; | ||
import * as knexpkg from 'knex'; | ||
import { type Logger, type Meter, getLogger, getMeter } from '@myrotvorets/otel-utils'; | ||
import { Model } from 'objection'; | ||
import { environment } from './environment.mjs'; | ||
import { buildKnexConfig } from '../knexfile.mjs'; | ||
|
||
export interface Container { | ||
environment: ReturnType<typeof environment>; | ||
logger: Logger; | ||
meter: Meter; | ||
db: knexpkg.Knex; | ||
} | ||
|
||
export interface RequestContainer { | ||
req: Request; | ||
} | ||
|
||
export const container = createContainer<Container>(); | ||
|
||
function createEnvironment(): ReturnType<typeof environment> { | ||
return environment(true); | ||
} | ||
|
||
function createLogger({ req }: Partial<RequestContainer>): Logger { | ||
const logger = getLogger(); | ||
logger.clearAttributes(); | ||
if (req) { | ||
logger.setAttribute('ip', req.ip); | ||
logger.setAttribute('request', `${req.method} ${req.url}`); | ||
} | ||
|
||
return logger; | ||
} | ||
|
||
function createMeter(): Meter { | ||
return getMeter(); | ||
} | ||
|
||
function createDatabase(): knexpkg.Knex { | ||
const { knex } = knexpkg.default; | ||
const db = knex(buildKnexConfig()); | ||
Model.knex(db); | ||
return db; | ||
} | ||
|
||
export type LocalsWithContainer = Record<'container', AwilixContainer<RequestContainer & Container>>; | ||
|
||
export function initializeContainer(): typeof container { | ||
container.register({ | ||
environment: asFunction(createEnvironment).singleton(), | ||
logger: asFunction(createLogger).scoped(), | ||
meter: asFunction(createMeter).singleton(), | ||
db: asFunction(createDatabase).singleton(), | ||
}); | ||
|
||
container.register('req', asValue(undefined)); | ||
|
||
return container; | ||
} | ||
|
||
export function scopedContainerMiddleware( | ||
req: Request, | ||
res: Response<unknown, LocalsWithContainer>, | ||
next: NextFunction, | ||
): void { | ||
res.locals.container = container.createScope<RequestContainer>(); | ||
res.locals.container.register({ | ||
req: asValue(req), | ||
}); | ||
|
||
next(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
/* c8 ignore start */ | ||
import { ValueType } from '@opentelemetry/api'; | ||
import { getMeter } from '@myrotvorets/otel-utils'; | ||
|
||
const meter = getMeter(); | ||
|
||
export const requestDurationHistogram = meter.createHistogram('psbapi.request.duration', { | ||
description: 'Measures the duration of requests.', | ||
unit: 'ms', | ||
valueType: ValueType.DOUBLE, | ||
}); | ||
|
||
/* c8 ignore stop */ |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import type { RequestHandler } from 'express'; | ||
import { hrTime, hrTimeDuration, hrTimeToMilliseconds } from '@opentelemetry/core'; | ||
import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; | ||
import type { OpenApiRequest } from '@myrotvorets/oav-installer'; | ||
import { requestDurationHistogram } from '../lib/metrics.mjs'; | ||
|
||
export const requestDurationMiddleware: RequestHandler = (req, res, next): void => { | ||
const start = hrTime(); | ||
const recordDurarion = (): void => { | ||
res.removeListener('error', recordDurarion); | ||
res.removeListener('finish', recordDurarion); | ||
const end = hrTime(); | ||
const duration = hrTimeDuration(start, end); | ||
|
||
let route: string | undefined; | ||
if ('openapi' in req && req.openapi) { | ||
const r = req as OpenApiRequest; | ||
route = r.openapi!.openApiRoute || r.openapi!.expressRoute; | ||
} | ||
|
||
if (!route && req.route) { | ||
route = (req.route as Record<'path', string>).path; | ||
} | ||
|
||
if (!route) { | ||
route = '<unknown>'; | ||
} | ||
|
||
requestDurationHistogram.record(hrTimeToMilliseconds(duration), { | ||
[SemanticAttributes.HTTP_METHOD]: req.method, | ||
[SemanticAttributes.HTTP_ROUTE]: route, | ||
[SemanticAttributes.HTTP_STATUS_CODE]: res.statusCode, | ||
}); | ||
}; | ||
|
||
res.prependOnceListener('error', recordDurarion); | ||
res.prependOnceListener('finish', recordDurarion); | ||
next(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { requestLogger } from '@myrotvorets/express-request-logger'; | ||
import type { NextFunction, Request, Response } from 'express'; | ||
import type { LocalsWithContainer } from '../lib/container.mjs'; | ||
|
||
export const loggerMiddleware = | ||
process.env['NODE_ENV'] !== 'test' /* c8 ignore start */ | ||
? requestLogger<never, never, never, never, LocalsWithContainer>({ | ||
format: '[PSBAPI-identigraf-auth] :method\t:url\t:status :res[content-length]\t:date[iso]\t:total-time', | ||
beforeLogHook: (err, _req, res, line, tokens): string => { | ||
const { status } = tokens; | ||
const message = `Status: ${status} len: ${tokens['res[content-length]']} time: ${tokens['total-time']}`; | ||
const logger = res.locals.container.resolve('logger'); | ||
if (+(status ?? '') >= 500 || err) { | ||
logger.error(message); | ||
} else if (+(status ?? '') >= 400) { | ||
logger.warning(message); | ||
} else { | ||
logger.info(message); | ||
} | ||
|
||
return line; | ||
}, | ||
}) | ||
: /* c8 ignore stop */ | ||
(_req: Request, _res: Response, next: NextFunction): void => next(); |
Oops, something went wrong.