
    j                         d dl Z d dlZd dlZd dlmZ d dlmZ ddlmZm	Z	 ddlm
Z
  e j                  e      Zdee   d	dfd
Z G d dej                         Zy)    N)Optional)connection_monitor   )
db_managertypes   )messages
message_idreturnc                     | t        d      y )NzMessage ID expected)
ValueError)r
   s    /Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/message_processing/replay/replay_manager.py_check_message_idr      s    .//     c                   ~    e Zd ZdZdej
                  dededef fdZd fd	Z	dd
Z
edej                  fd       Zedefd       Zej"                  j$                  fdej(                  dej"                  ddfdZdeddfdZ	 ddedee   ddfdZdej6                  ddfdZddZddZddZddZ ddZ! xZ"S )ReplayManagera  
    Manages replaying messages to the server for a connection management system.

    The ReplayManager is responsible for ensuring that messages which fail to be
    delivered due to dropped connections are replayed to the server
    when the connection is restored. It continuously monitors the connection status
    and triggers failed message replays as necessary. The class runs in its own
    thread, leveraging the threading.Thread base class.
    monitor
batch_sizebatch_replay_delaytick_interval_secondsc                 H   t         |   dd       t        j                         | _        || _        d| _        || _        t        j                         | j                  z   | _	        d| _
        t        j                         | _        t        j                  ||      | _        y)a  
        Initializes the ReplayManager instance.

        Creates the replay manager thread with a specified connection monitor and tick interval.

        Args:
            monitor: An instance of OpikConnectionMonitor used for monitoring the connection.
            batch_size: The size of batches for processing.
            batch_replay_delay: The delay (in seconds) between replaying batches of messages.
            tick_interval_seconds: Interval in seconds between execution ticks. Default is 0.3.
        Tr   )daemonnameNr   )r   r   )super__init__	threadingEvent_stop_running_monitor_replay_callback_tick_interval_secondstime_next_tick_time_next_message_idRLock_message_id_lockr   	DBManager_db_manager)selfr   r   r   r   	__class__s        r   r   zReplayManager.__init__   s    $ 	?;&__.@D&;##yy{T-H-HH ! ) 1%//!1
r   r   Nc                 B    | j                          t        | 	          y N)_check_replay_callbackr   start)r)   r*   s    r   r.   zReplayManager.start@   s    ##%r   c                    	 | j                   j                         s+| j                          | j                   j                         s+| j                  j	                          y # | j                  j	                          w xY wr,   )r   is_set_loopr(   closer)   s    r   runzReplayManager.runD   s]    	%((//1

 ((//1 ""$D""$s   AA" "A>c                     | j                   S r,   )r(   r3   s    r   database_managerzReplayManager.database_managerL   s    r   c                 .    | j                   j                  S )z2Checks if SDK has a connection to the OPIK server.)r   has_server_connectionr3   s    r   r8   z#ReplayManager.has_server_connectionP   s     }}222r   messagestatusc                 B   | j                   5  |j                  &| j                  |_        | xj                  dz  c_        ddd       	 | j                  j	                  ||       y# 1 sw Y   (xY w# t
        $ r"}t        j                  d|d       Y d}~yd}~ww xY w)z=Registers a message to be replayed if the connection is lost.Nr   r:   z1Failed to register message for replay, reason: %sTexc_info)r&   r
   r$   r(   register_message	ExceptionLOGGERerror)r)   r9   r:   exs       r   r?   zReplayManager.register_messageU   s     ""!!)%)%:%:"%%*%	 #	--gf-E #"  	LLCRRV   	s#   3A'	A3 'A03	B<BBr
   c                     t        |       	 | j                  j                  |t        j                  j
                         y# t        $ r"}t        j                  d|d       Y d}~yd}~ww xY w)zDUnregisters a message from being replayed if the connection is lost.r<   z5Failed to un-register message from replay, reason: %sTr=   N)	r   r(   update_messager   MessageStatus	deliveredr@   rA   rB   )r)   r
   rC   s      r   unregister_messagez ReplayManager.unregister_messageh   sj    *%		++:#;#;#E#E ,   	LLG   	s   5A 	A.A))A.failure_reasonc                    t        |       	 | j                  j                  |       | j                  j	                  |t
        j                  j                         y# t        $ r"}t        j                  d|d       Y d}~yd}~ww xY w)zMNotifies the manager that a message was not sent due to a connection failure.)rI   r<   zCFailed to mark message as send-failed in replay manager, reason: %sTr=   N)r   r   connection_failedr(   rE   r   rF   failedr@   rA   rB   )r)   r
   rI   rC   s       r   message_sent_failedz!ReplayManager.message_sent_failedv   s     	*%
	MM++>+J++:#;#;#B#B ,   	LLU   	s   AA 	B
(BB
callbackc                     || _         y)z?Sets the callback to be invoked when replaying failed messages.N)r    )r)   rN   s     r   set_replay_callbackz!ReplayManager.set_replay_callback   s
     (r   c                 8    | j                   j                          y)zStop the replay manager.N)r   setr3   s    r   r2   zReplayManager.close   s     r   c                 D    | j                          | j                          y)z2Force replay of all failed messages to the server.N)r-   _replay_failed_messagesr3   s    r   flushzReplayManager.flush   s    ##%$$&r   c                    | j                   t        j                         z
  }|dkD  r| j                  j                  |       	 | j                  j                         }|t        j                  j                  k(  r*| j                          | j                  j                          t        j                         | j                  z   | _         y # t        $ r"}t        j                  d||       Y d }~Md }~ww xY w)Nr   zXFailed to tick the connection monitor or replay failed messages, will repeat. Reason: %sr=   )r#   r"   r   waitr   tickr   ConnectionStatusconnection_restoredrT   resetr@   rA   warningr!   )r)   
sleep_timer:   rC   s       r   r1   zReplayManager._loop   s    ))DIIK7
>##J/	]]'')F+<<PPP,,.##%  $yy{T-H-HH  	NNj   	s   A!C 	C6C11C6c                 2    | j                   t        d      y )Nz>Replay callback must be set before starting the replay manager)r    r   r3   s    r   r-   z$ReplayManager._check_replay_callback   s#      (P  )r   c                    | j                          	 | j                  j                  | j                        }|dkD  rt        j                  d|       y y # t        $ r"}t        j                  d|d       Y d }~y d }~ww xY w)Nr   zIReplayed %d message(s) that were not sent due to server connection issuesz,Failed to replay failed messages, reason: %sTr=   )r-   r(   replay_failed_messagesr    rA   infor@   rB   )r)   replayedrC   s      r   rT   z%ReplayManager._replay_failed_messages   s    ##%	''>>%%H !|_ 
  	LL>T   	s   A A 	A?A::A?)r   Nr,   )#__name__
__module____qualname____doc__r   OpikConnectionMonitorintfloatr   r.   r4   propertyr   r'   r6   boolr8   rF   
registeredr	   BaseMessager?   rH   r   strrM   r   ReplayCallbackrP   r2   rU   r1   r-   rT   __classcell__)r*   s   @r   r   r      s,   
#99
 
 "	

  %
B%  *"6"6     3t 3 3 ,6+C+C+N+N%% (( 
	&S T  @D/7}	")E,@,@ )T )!'I,r   r   )loggingr   r"   typingr   opik.healthcheckr    r   r   r	   	getLoggerrc   rA   rh   r   Threadr    r   r   <module>rx      sY        /   
		8	$0(3- 0D 0mI$$ mr   