66from typing import Any , cast , final
77
88from .._transport import Transport
9- from ..connection import Connection
9+ from ..connection import Connection , MethodHandler
1010from ..exceptions import RequestError
1111from ..interfaces import Agent , Client
1212from ..meta import AGENT_METHODS , CLIENT_METHODS
@@ -122,9 +122,7 @@ def __init__(
122122 use_unstable_protocol : bool = False ,
123123 ** connection_kwargs : Any ,
124124 ) -> None :
125- client = to_client (self ) if callable (to_client ) else to_client
126- self ._session_updates = _SessionUpdateTracker (cast (Client , client ))
127- handler = build_client_router (cast (Client , self ._session_updates ), use_unstable_protocol = use_unstable_protocol )
125+ client , handler = self ._prepare (to_client , use_unstable_protocol = use_unstable_protocol )
128126
129127 if isinstance (input_stream , Transport ):
130128 if output_stream is not None :
@@ -136,6 +134,34 @@ def __init__(
136134 ):
137135 raise TypeError (_CLIENT_CONNECTION_ERROR )
138136 self ._conn = Connection (handler , input_stream , output_stream , ** connection_kwargs )
137+ self ._notify_connected (client )
138+
139+ @classmethod
140+ def _attach (
141+ cls ,
142+ to_client : Callable [[Agent ], Client ] | Client ,
143+ connection : Connection ,
144+ * ,
145+ use_unstable_protocol : bool = False ,
146+ ) -> tuple [ClientSideConnection , MethodHandler ]:
147+ self = cls .__new__ (cls )
148+ client , handler = self ._prepare (to_client , use_unstable_protocol = use_unstable_protocol )
149+ self ._conn = connection
150+ self ._notify_connected (client )
151+ return self , handler
152+
153+ def _prepare (
154+ self ,
155+ to_client : Callable [[Agent ], Client ] | Client ,
156+ * ,
157+ use_unstable_protocol : bool ,
158+ ) -> tuple [Client , MethodHandler ]:
159+ client = cast (Client , to_client (self ) if callable (to_client ) else to_client )
160+ self ._session_updates = _SessionUpdateTracker (client )
161+ handler = build_client_router (cast (Client , self ._session_updates ), use_unstable_protocol = use_unstable_protocol )
162+ return client , handler
163+
164+ def _notify_connected (self , client : Client ) -> None :
139165 if on_connect := getattr (client , "on_connect" , None ):
140166 on_connect (self )
141167
0 commit comments