import * as appInsights from "applicationinsights" ; import { ApplicationInsightsConfig , initAppInsights as startAppInsights } from "italia-ts-commons/lib/appinsights" ; import { toFiscalCodeHash } from "../types/notification" ; import { User } from "../types/user" ; const SESSION_TRACKING_ID_KEY = "session_tracking_id" ; const USER_TRACKING_ID_KEY = "user_tracking_id" ; see https export function attachTrackingData ( user ) { const correlationContext = appInsights . getCorrelationContext ( ) ; if ( ! correlationContext ) { return ; } const customProperties = correlationContext . customProperties ; customProperties . setProperty ( USER_TRACKING_ID_KEY , toFiscalCodeHash ( user . fiscal_code ) ) ; if ( user . session_tracking_id !== undefined ) { customProperties . setProperty ( SESSION_TRACKING_ID_KEY , user . session_tracking_id ) ; } } export function sessionIdPreprocessor ( envelope , context ? ) { if ( context !== undefined ) { try { const userTrackingId = context . correlationContext . customProperties . getProperty ( USER_TRACKING_ID_KEY ) ; if ( userTrackingId !== undefined ) { envelope . tags [ appInsights . defaultClient . context . keys . userId ] = userTrackingId ; } const sessionTrackingId = context . correlationContext . customProperties . getProperty ( SESSION_TRACKING_ID_KEY ) ; if ( sessionTrackingId !== undefined ) { envelope . tags [ appInsights . defaultClient . context . keys . sessionId ] = sessionTrackingId ; } } catch ( e ) { } } return true ; } export enum StartupEventName { SERVER = "api-backend.httpserver.startup" , SPID = "api-backend.spid.config" } export const trackStartupTime = ( telemetryClient , type , timeMs ) : void => { telemetryClient . trackEvent ( { name : type , properties : { time : timeMs . toString ( ) } , tagOverrides : { samplingEnabled : "false" } } ) ; } ; /**
 * App Insights is initialized to collect the following informations:
 * - Incoming API calls
 * - Server performance information (CPU, RAM)
 * - Unandled Runtime Exceptions
 * - Outcoming API Calls (dependencies)
 * - Realtime API metrics
 */ export function initAppInsights ( instrumentationKey , config = { } ) { startAppInsights ( instrumentationKey , config ) ; appInsights . defaultClient . addTelemetryProcessor ( sessionIdPreprocessor ) ; return appInsights . defaultClient ; }