import Boom from '@hapi/boom' ; import { i18n } from '@kbn/i18n' ; import { IScopedClusterClient } from 'kibana/server' ; import { ModelSnapshot } from '../../../common/types/anomaly_detection_jobs' ; import { datafeedsProvider } from './datafeeds' ; import { FormCalendar , CalendarManager } from '../calendar' ; import type { MlClient } from '../../lib/ml_client' ; export interface ModelSnapshotsResponse { count : number ; model_snapshots : ModelSnapshot [ ] ; } export interface RevertModelSnapshotResponse { model : ModelSnapshot ; } export function modelSnapshotProvider ( client , mlClient ) { const { forceStartDatafeeds , getDatafeedIdsByJobId } = datafeedsProvider ( client , mlClient ) ; async function revertModelSnapshot ( jobId , snapshotId , replay , end ? , deleteInterveningResults = true , calendarEvents ? ) { let datafeedId = `datafeed-${ jobId }` ; await mlClient . getJobs ( { job_id : jobId } ) ; try { await mlClient . getDatafeeds ( { datafeed_id : datafeedId , } ) ; } catch ( e ) { const datafeedIds = await getDatafeedIdsByJobId ( ) ; datafeedId = datafeedIds [ jobId ] ; if ( datafeedId === undefined ) { throw Boom . notFound ( `Cannot find datafeed for job ${ jobId }` ) ; } } const { body : snapshot } = await mlClient . getModelSnapshots < ModelSnapshotsResponse > ( { job_id : jobId , snapshot_id : snapshotId , } ) ; const { body : { model } , } = await mlClient . revertModelSnapshot < RevertModelSnapshotResponse > ( { job_id : jobId , snapshot_id : snapshotId , body : { delete_intervening_results : deleteInterveningResults , } , } ) ; if ( replay && model . snapshot_id === snapshotId && snapshot . model_snapshots . length ) { if ( calendarEvents !== undefined && calendarEvents . length ) { const calendarId = String ( Date . now ( ) ) ; const calendar = { calendarId , job_ids : [ jobId ] , description : i18n . translate ( 'xpack.ml.models.jobService.revertModelSnapshot.autoCreatedCalendar.description' , { defaultMessage : 'Auto created' , } ) , events : calendarEvents . map ( ( s ) => ( { calendar_id : calendarId , description : s . description , start_time : `${ s . start }` , end_time : `${ s . end }` , } ) ) , } ; const cm = new CalendarManager ( mlClient ) ; await cm . newCalendar ( calendar ) ; } forceStartDatafeeds ( [ datafeedId ] , + snapshot . model_snapshots [ 0 ] . latest_record_time_stamp , end ) ; } return { success : true } ; } return { revertModelSnapshot } ; }