Files
lolympus-tournament-support/apps/api/src/modules/global/observability/new-relic.ts
T

64 lines
2.5 KiB
TypeScript

// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 서버 계측 래퍼. 조사 종료 후 호출부와 함께
// 제거 대상(범용으로 남길 거면 이 마커만 떼면 됨).
import newrelicAgent from 'newrelic';
export type NewRelicAttributeValue = string | number | boolean | null;
// newrelic 기본 export는 타입이 느슨해 unsafe-call로 잡힌다. 우리가 쓰는 부분만
// 좁게 타입을 고정한다(에이전트는 -r newrelic로 이미 preload됨).
interface NewRelicCustomEventApi {
recordCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue>,
): void;
addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
setTransactionName(name: string): void;
}
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
/**
* 서버 커스텀 이벤트를 New Relic으로 보낸다(클라의 addPageAction 대응).
*
* - 에이전트는 `-r newrelic`로 이미 preload되어 있으므로 여기서 import만 하면 된다.
* - `recordCustomEvent`는 활성 트랜잭션이 없어도 동작하므로 durability 스케줄러
* tick이나 socket.io 핸들러처럼 HTTP 컨텍스트 밖에서도 그대로 호출할 수 있다.
* - 평탄한 스칼라만 받는다(중첩 객체/배열 불가). undefined 속성은 제거한다.
* - 에이전트 비활성/테스트 환경에서도 호출부가 깨지지 않도록 예외를 삼킨다.
*/
export function recordNewRelicCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue | undefined>,
): void {
try {
const flat: Record<string, NewRelicAttributeValue> = {};
for (const [key, value] of Object.entries(attributes)) {
if (value !== undefined) flat[key] = value;
}
agent.recordCustomEvent(eventType, flat);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
export function addNewRelicCustomAttributes(
attributes: Record<string, NewRelicAttributeValue | undefined>,
): void {
try {
const flat: Record<string, NewRelicAttributeValue> = {};
for (const [key, value] of Object.entries(attributes)) {
if (value !== undefined) flat[key] = value;
}
agent.addCustomAttributes(flat);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
export function setNewRelicTransactionName(name: string): void {
try {
agent.setTransactionName(name);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}