import { Logger } from 'src/core/server' ; import { RuleTaskState , AlertExecutionStatus , RawRuleExecutionStatus } from '../types' ; import { getReasonFromError } from './error_with_reason' ; import { getEsErrorMessage } from './errors' ; import { AlertExecutionStatuses } from '../../common' ; export function executionStatusFromState ( state ) { const alertIds = Object . keys ( state . alertInstances ?? { } ) ; return { lastExecutionDate : new Date ( ) , status : alertIds . length === 0 ? 'ok' : 'active' , } ; } export function executionStatusFromError ( error ) { return { lastExecutionDate : new Date ( ) , status : 'error' , error : { reason : getReasonFromError ( error ) , message : getEsErrorMessage ( error ) , } , } ; } export function ruleExecutionStatusToRaw ( { lastExecutionDate , lastDuration , status , error , } ) { return { lastExecutionDate : lastExecutionDate . toISOString ( ) , lastDuration : lastDuration ?? 0 , status , error : error ?? null , } ; } export function ruleExecutionStatusFromRaw ( logger , ruleId , rawRuleExecutionStatus ? ) { if ( ! rawRuleExecutionStatus ) return undefined ; const { lastExecutionDate , lastDuration , status = 'unknown' , error } = rawRuleExecutionStatus ; let parsedDateMillis = lastExecutionDate ? Date . parse ( lastExecutionDate ) : Date . now ( ) ; if ( isNaN ( parsedDateMillis ) ) { logger . debug ( `invalid ruleExecutionStatus lastExecutionDate "${ lastExecutionDate }" in raw rule ${ ruleId }` ) ; parsedDateMillis = Date . now ( ) ; } const executionStatus = { status , lastExecutionDate : new Date ( parsedDateMillis ) , } ; if ( null != lastDuration ) { executionStatus . lastDuration = lastDuration ; } if ( error ) { executionStatus . error = error ; } return executionStatus ; } export const getRuleExecutionStatusPending = ( lastExecutionDate ) => ( { status : 'pending' as AlertExecutionStatuses , lastExecutionDate , error : null , } ) ;