@@ -757,6 +757,9 @@ pub struct StateTransition {
757757 pub state : AlertState ,
758758 /// Timestamp when this state was set/updated
759759 pub last_updated_at : DateTime < Utc > ,
760+ pub previous_alert_state : Option < AlertState > ,
761+ /// Duration in seconds
762+ pub previous_state_duration : Option < i64 > ,
760763}
761764
762765#[ derive( Debug , Clone , Serialize , Deserialize ) ]
@@ -768,10 +771,23 @@ pub struct AlertStateEntry {
768771
769772impl StateTransition {
770773 /// Creates a new state transition with the current timestamp
771- pub fn new ( state : AlertState ) -> Self {
774+ pub fn new (
775+ state : AlertState ,
776+ previous_alert_state : Option < AlertState > ,
777+ previous_alert_time : Option < DateTime < Utc > > ,
778+ ) -> Self {
779+ let now = Utc :: now ( ) ;
780+ // calculate duration if previous alert time is provided
781+ let previous_state_duration = if let Some ( alert_time) = previous_alert_time {
782+ Some ( ( now - alert_time) . num_seconds ( ) )
783+ } else {
784+ None
785+ } ;
772786 Self {
773787 state,
774- last_updated_at : Utc :: now ( ) ,
788+ last_updated_at : now,
789+ previous_alert_state,
790+ previous_state_duration,
775791 }
776792 }
777793}
@@ -781,7 +797,7 @@ impl AlertStateEntry {
781797 pub fn new ( alert_id : Ulid , initial_state : AlertState ) -> Self {
782798 Self {
783799 alert_id,
784- states : vec ! [ StateTransition :: new( initial_state) ] ,
800+ states : vec ! [ StateTransition :: new( initial_state, None , None ) ] ,
785801 }
786802 }
787803
@@ -792,7 +808,11 @@ impl AlertStateEntry {
792808 Some ( last_transition) => {
793809 if last_transition. state != new_state {
794810 // State changed - add new transition
795- self . states . push ( StateTransition :: new ( new_state) ) ;
811+ self . states . push ( StateTransition :: new (
812+ new_state,
813+ Some ( last_transition. state ) ,
814+ Some ( last_transition. last_updated_at ) ,
815+ ) ) ;
796816 true
797817 } else {
798818 // If state hasn't changed, do nothing - preserve the original timestamp
@@ -801,7 +821,8 @@ impl AlertStateEntry {
801821 }
802822 None => {
803823 // No previous states - add the first one
804- self . states . push ( StateTransition :: new ( new_state) ) ;
824+ self . states
825+ . push ( StateTransition :: new ( new_state, None , None ) ) ;
805826 true
806827 }
807828 }
0 commit comments