@@ -757,6 +757,10 @@ pub struct StateTransition {
757757 pub state : AlertState ,
758758 /// Timestamp when this state was set/updated
759759 pub last_updated_at : DateTime < Utc > ,
760+ /// The previous alert state before this transition, if any
761+ pub previous_alert_state : Option < AlertState > ,
762+ /// Duration in seconds
763+ pub previous_state_duration : Option < i64 > ,
760764}
761765
762766#[ derive( Debug , Clone , Serialize , Deserialize ) ]
@@ -768,10 +772,23 @@ pub struct AlertStateEntry {
768772
769773impl StateTransition {
770774 /// Creates a new state transition with the current timestamp
771- pub fn new ( state : AlertState ) -> Self {
775+ pub fn new (
776+ state : AlertState ,
777+ previous_alert_state : Option < AlertState > ,
778+ previous_alert_time : Option < DateTime < Utc > > ,
779+ ) -> Self {
780+ let now = Utc :: now ( ) ;
781+ // calculate duration if previous alert time is provided
782+ let previous_state_duration = if let Some ( alert_time) = previous_alert_time {
783+ Some ( ( now - alert_time) . num_seconds ( ) )
784+ } else {
785+ None
786+ } ;
772787 Self {
773788 state,
774- last_updated_at : Utc :: now ( ) ,
789+ last_updated_at : now,
790+ previous_alert_state,
791+ previous_state_duration,
775792 }
776793 }
777794}
@@ -781,7 +798,7 @@ impl AlertStateEntry {
781798 pub fn new ( alert_id : Ulid , initial_state : AlertState ) -> Self {
782799 Self {
783800 alert_id,
784- states : vec ! [ StateTransition :: new( initial_state) ] ,
801+ states : vec ! [ StateTransition :: new( initial_state, None , None ) ] ,
785802 }
786803 }
787804
@@ -792,7 +809,11 @@ impl AlertStateEntry {
792809 Some ( last_transition) => {
793810 if last_transition. state != new_state {
794811 // State changed - add new transition
795- self . states . push ( StateTransition :: new ( new_state) ) ;
812+ self . states . push ( StateTransition :: new (
813+ new_state,
814+ Some ( last_transition. state ) ,
815+ Some ( last_transition. last_updated_at ) ,
816+ ) ) ;
796817 true
797818 } else {
798819 // If state hasn't changed, do nothing - preserve the original timestamp
@@ -801,7 +822,8 @@ impl AlertStateEntry {
801822 }
802823 None => {
803824 // No previous states - add the first one
804- self . states . push ( StateTransition :: new ( new_state) ) ;
825+ self . states
826+ . push ( StateTransition :: new ( new_state, None , None ) ) ;
805827 true
806828 }
807829 }
0 commit comments