import { LogMeta , SavedObjectMigrationContext , SavedObjectMigrationFn , SavedObjectMigrationMap , SavedObjectsUtils , SavedObjectUnsanitizedDoc , } from '../../../../../src/core/server' ; import { TaskInstance , TaskInstanceWithDeprecatedFields } from '../task' ; interface TaskInstanceLogMeta extends LogMeta { migrations : { taskInstanceDocument : SavedObjectUnsanitizedDoc < TaskInstanceWithDeprecatedFields > ; } ; } type TaskInstanceMigration = ( doc : SavedObjectUnsanitizedDoc < TaskInstanceWithDeprecatedFields > ) => SavedObjectUnsanitizedDoc < TaskInstanceWithDeprecatedFields > ; export function getMigrations ( ) { return { '7.4.0' : executeMigrationWithErrorHandling ( ( doc ) => ( { ... doc , updated_at : new Date ( ) . toISOString ( ) , } ) , '7.4.0' ) , '7.6.0' : executeMigrationWithErrorHandling ( moveIntervalIntoSchedule , '7.6.0' ) , '8.0.0' : executeMigrationWithErrorHandling ( pipeMigrations ( alertingTaskLegacyIdToSavedObjectIds , actionsTasksLegacyIdToSavedObjectIds ) , '8.0.0' ) , } ; } function executeMigrationWithErrorHandling ( migrationFunc , version ) { return ( doc , context ) => { try { return migrationFunc ( doc , context ) ; } catch ( ex ) { context . log . error < TaskInstanceLogMeta > ( `savedObject ${ version } migration failed for task instance ${ doc . id } with error: ${ ex . message }` , { migrations : { taskInstanceDocument : doc , } , } ) ; throw ex ; } } ; } function alertingTaskLegacyIdToSavedObjectIds ( doc ) { if ( doc . attributes . taskType . startsWith ( 'alerting:' ) ) { let params = { } ; params = JSON . parse ( doc . attributes . params as unknown as string ) ; if ( params . alertId && params . spaceId && params . spaceId !== 'default' ) { const newId = SavedObjectsUtils . getConvertedObjectId ( params . spaceId , 'alert' , params . alertId ) ; return { ... doc , attributes : { ... doc . attributes , params : JSON . stringify ( { ... params , alertId : newId , } ) as any , } , } ; } } return doc ; } function actionsTasksLegacyIdToSavedObjectIds ( doc ) { if ( doc . attributes . taskType . startsWith ( 'actions:' ) ) { let params = { } ; params = JSON . parse ( doc . attributes . params as unknown as string ) ; if ( params . actionTaskParamsId && params . spaceId && params . spaceId !== 'default' ) { const newId = SavedObjectsUtils . getConvertedObjectId ( params . spaceId , 'action_task_params' , params . actionTaskParamsId ) ; return { ... doc , attributes : { ... doc . attributes , params : JSON . stringify ( { ... params , actionTaskParamsId : newId , } ) as any , } , } ; } } return doc ; } function moveIntervalIntoSchedule ( { attributes : { interval , ... attributes } , ... doc } ) { return { ... doc , attributes : { ... attributes , ... ( interval ? { schedule : { interval , } , } : { } ) , } , } ; } function pipeMigrations ( ... migrations ) { return ( doc ) => migrations . reduce ( ( migratedDoc , nextMigration ) => nextMigration ( migratedDoc ) , doc ) ; }