techprotrade commited on
Commit
d91b684
·
verified ·
1 Parent(s): f4691b0

Add loan-advisor-agent

Browse files
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from sse_starlette.event import ServerSentEvent, JSONServerSentEvent
2
+ from sse_starlette.sse import EventSourceResponse
3
+
4
+ __all__ = ["EventSourceResponse", "ServerSentEvent", "JSONServerSentEvent"]
5
+ __version__ = "3.3.4"
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (412 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/__pycache__/event.cpython-312.pyc ADDED
Binary file (4.55 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/__pycache__/sse.cpython-312.pyc ADDED
Binary file (20.7 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/event.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import re
3
+ import json
4
+ from typing import Optional, Any, Union
5
+
6
+
7
+ class ServerSentEvent:
8
+ """
9
+ Helper class to format data for Server-Sent Events (SSE).
10
+ """
11
+
12
+ _LINE_SEP_EXPR = re.compile(r"\r\n|\r|\n")
13
+ DEFAULT_SEPARATOR = "\r\n"
14
+
15
+ def __init__(
16
+ self,
17
+ data: Optional[Any] = None,
18
+ *,
19
+ event: Optional[str] = None,
20
+ id: Optional[str] = None,
21
+ retry: Optional[int] = None,
22
+ comment: Optional[str] = None,
23
+ sep: Optional[str] = None,
24
+ ) -> None:
25
+ self.data = data
26
+ self.event = event
27
+ self.id = id
28
+ self.retry = retry
29
+ self.comment = comment
30
+ self._sep = sep if sep is not None else self.DEFAULT_SEPARATOR
31
+
32
+ def encode(self) -> bytes:
33
+ buffer = io.StringIO()
34
+ if self.comment is not None:
35
+ for chunk in self._LINE_SEP_EXPR.split(str(self.comment)):
36
+ buffer.write(f": {chunk}{self._sep}")
37
+
38
+ if self.id is not None:
39
+ # Clean newlines in the event id
40
+ buffer.write("id: " + self._LINE_SEP_EXPR.sub("", self.id) + self._sep)
41
+
42
+ if self.event is not None:
43
+ # Clean newlines in the event name
44
+ buffer.write(
45
+ "event: " + self._LINE_SEP_EXPR.sub("", self.event) + self._sep
46
+ )
47
+
48
+ if self.data is not None:
49
+ # Break multi-line data into multiple data: lines
50
+ for chunk in self._LINE_SEP_EXPR.split(str(self.data)):
51
+ buffer.write(f"data: {chunk}{self._sep}")
52
+
53
+ if self.retry is not None:
54
+ if not isinstance(self.retry, int):
55
+ raise TypeError("retry argument must be int")
56
+ buffer.write(f"retry: {self.retry}{self._sep}")
57
+
58
+ buffer.write(self._sep)
59
+ return buffer.getvalue().encode("utf-8")
60
+
61
+
62
+ class JSONServerSentEvent(ServerSentEvent):
63
+ """
64
+ Helper class to format JSON data for Server-Sent Events (SSE).
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ data: Optional[Any] = None,
70
+ *args,
71
+ **kwargs,
72
+ ) -> None:
73
+ super().__init__(
74
+ json.dumps(
75
+ data,
76
+ ensure_ascii=False,
77
+ allow_nan=False,
78
+ indent=None,
79
+ separators=(",", ":"),
80
+ )
81
+ if data is not None
82
+ else None,
83
+ *args,
84
+ **kwargs,
85
+ )
86
+
87
+
88
+ def ensure_bytes(data: Union[bytes, dict, ServerSentEvent, Any], sep: str) -> bytes:
89
+ if isinstance(data, bytes):
90
+ return data
91
+ if isinstance(data, ServerSentEvent):
92
+ return data.encode()
93
+ if isinstance(data, dict):
94
+ data["sep"] = sep
95
+ return ServerSentEvent(**data).encode()
96
+ return ServerSentEvent(str(data), sep=sep).encode()
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/py.typed ADDED
File without changes
loan-advisor-agent/.venv/Lib/site-packages/sse_starlette/sse.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import signal
4
+ import threading
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ from typing import (
8
+ Any,
9
+ AsyncIterable,
10
+ Awaitable,
11
+ Callable,
12
+ Coroutine,
13
+ Iterator,
14
+ Mapping,
15
+ Optional,
16
+ Set,
17
+ Union,
18
+ )
19
+
20
+ import anyio
21
+ from starlette.background import BackgroundTask
22
+ from starlette.concurrency import iterate_in_threadpool
23
+ from starlette.datastructures import MutableHeaders
24
+ from starlette.responses import Response
25
+ from starlette.types import Receive, Scope, Send, Message
26
+
27
+ from sse_starlette.event import ServerSentEvent, ensure_bytes
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ @dataclass
34
+ class _ShutdownState:
35
+ """Per-thread state for shutdown coordination.
36
+
37
+ Issue #152 fix: Uses threading.local() instead of ContextVar to ensure
38
+ one watcher per thread rather than one per async context.
39
+ """
40
+
41
+ events: Set[anyio.Event] = field(default_factory=set)
42
+ watcher_started: bool = False
43
+
44
+
45
+ # Each thread gets its own shutdown state (one event loop per thread typically)
46
+ _thread_state = threading.local()
47
+
48
+
49
+ def _get_shutdown_state() -> _ShutdownState:
50
+ """Get or create shutdown state for the current thread."""
51
+ state = getattr(_thread_state, "shutdown_state", None)
52
+ if state is None:
53
+ state = _ShutdownState()
54
+ _thread_state.shutdown_state = state
55
+ return state
56
+
57
+
58
+ def _get_uvicorn_server():
59
+ """
60
+ Try to get uvicorn Server instance via signal handler introspection.
61
+
62
+ When uvicorn registers signal handlers, they're bound methods on the Server instance.
63
+ We can retrieve the Server from the handler's __self__ attribute.
64
+
65
+ Returns None if:
66
+ - Not running under uvicorn
67
+ - Signal handler isn't a bound method
68
+ - Any introspection fails
69
+ """
70
+ try:
71
+ handler = signal.getsignal(signal.SIGTERM)
72
+ if hasattr(handler, "__self__"):
73
+ server = handler.__self__
74
+ if hasattr(server, "should_exit"):
75
+ return server
76
+ except Exception:
77
+ pass
78
+ return None
79
+
80
+
81
+ async def _shutdown_watcher() -> None:
82
+ """
83
+ Poll for shutdown and broadcast to all events in this context.
84
+
85
+ One watcher runs per thread (event loop). Checks two shutdown sources:
86
+ 1. AppStatus.should_exit - set when our monkey-patch works
87
+ 2. uvicorn Server.should_exit - via signal handler introspection (Issue #132 fix)
88
+
89
+ When either becomes True, signals all registered events.
90
+ """
91
+ state = _get_shutdown_state()
92
+ uvicorn_server = _get_uvicorn_server()
93
+
94
+ try:
95
+ while True:
96
+ # Check our flag (monkey-patch worked or manually set)
97
+ if AppStatus.should_exit:
98
+ break
99
+ # Check uvicorn's flag directly (monkey-patch failed - Issue #132)
100
+ if (
101
+ AppStatus.enable_automatic_graceful_drain
102
+ and uvicorn_server is not None
103
+ and uvicorn_server.should_exit
104
+ ):
105
+ AppStatus.should_exit = True # Sync state for consistency
106
+ break
107
+ await anyio.sleep(0.5)
108
+
109
+ # Shutdown detected - broadcast to all waiting events
110
+ for event in list(state.events):
111
+ event.set()
112
+ finally:
113
+ # Allow watcher to be restarted if loop is reused
114
+ state.watcher_started = False
115
+
116
+
117
+ def _ensure_watcher_started_on_this_loop() -> None:
118
+ """Ensure the shutdown watcher is running for this thread (event loop)."""
119
+ state = _get_shutdown_state()
120
+ if not state.watcher_started:
121
+ state.watcher_started = True
122
+ try:
123
+ loop = asyncio.get_running_loop()
124
+ loop.create_task(_shutdown_watcher())
125
+ except RuntimeError:
126
+ # No running loop - shouldn't happen in normal use
127
+ state.watcher_started = False
128
+
129
+
130
+ class SendTimeoutError(TimeoutError):
131
+ pass
132
+
133
+
134
+ class AppStatus:
135
+ """Helper to capture a shutdown signal from Uvicorn so we can gracefully terminate SSE streams."""
136
+
137
+ should_exit = False
138
+ enable_automatic_graceful_drain = True
139
+ original_handler: Optional[Callable] = None
140
+
141
+ @staticmethod
142
+ def disable_automatic_graceful_drain():
143
+ """
144
+ Prevent automatic SSE stream termination on server shutdown.
145
+
146
+ WARNING: When disabled, you MUST set AppStatus.should_exit = True
147
+ at some point during shutdown, or streams will never close and the
148
+ server will hang indefinitely (or until uvicorn's graceful shutdown
149
+ timeout expires).
150
+ """
151
+ AppStatus.enable_automatic_graceful_drain = False
152
+
153
+ @staticmethod
154
+ def enable_automatic_graceful_drain_mode():
155
+ """
156
+ Re-enable automatic SSE stream termination on server shutdown.
157
+
158
+ This restores the default behavior where SIGTERM triggers immediate
159
+ stream draining. Call this to undo a previous call to
160
+ disable_automatic_graceful_drain().
161
+ """
162
+ AppStatus.enable_automatic_graceful_drain = True
163
+
164
+ @staticmethod
165
+ def handle_exit(*args, **kwargs):
166
+ if AppStatus.enable_automatic_graceful_drain:
167
+ AppStatus.should_exit = True
168
+ if AppStatus.original_handler is not None:
169
+ AppStatus.original_handler(*args, **kwargs)
170
+
171
+
172
+ try:
173
+ from uvicorn.main import Server
174
+
175
+ AppStatus.original_handler = Server.handle_exit
176
+ Server.handle_exit = AppStatus.handle_exit # type: ignore
177
+ except ImportError:
178
+ logger.debug(
179
+ "Uvicorn not installed. Graceful shutdown on server termination disabled."
180
+ )
181
+
182
+ Content = Union[str, bytes, dict, ServerSentEvent, Any]
183
+ SyncContentStream = Iterator[Content]
184
+ AsyncContentStream = AsyncIterable[Content]
185
+ ContentStream = Union[AsyncContentStream, SyncContentStream]
186
+
187
+
188
+ class EventSourceResponse(Response):
189
+ """Streaming response implementing the SSE (Server-Sent Events) specification.
190
+
191
+ Args:
192
+ content: Async iterable or sync iterator yielding SSE event data.
193
+ status_code: HTTP status code. Default: 200.
194
+ headers: Additional HTTP headers.
195
+ media_type: Response media type. Default: "text/event-stream".
196
+ background: Background task to run after response completes.
197
+ ping: Ping interval in seconds (0 to disable). Default: 15.
198
+ sep: Line separator for SSE messages ("\\r\\n", "\\r", or "\\n").
199
+ ping_message_factory: Callable returning custom ping ServerSentEvent.
200
+ data_sender_callable: Async callable for push-based data sending.
201
+ send_timeout: Timeout in seconds for individual send operations.
202
+ client_close_handler_callable: Async callback on client disconnect.
203
+ shutdown_event: Optional ``anyio.Event`` set by the library when server
204
+ shutdown is detected. Generators can watch this event to send farewell
205
+ messages and exit cooperatively instead of receiving CancelledError.
206
+ shutdown_grace_period: Seconds to wait after setting ``shutdown_event``
207
+ before force-cancelling the generator. Must be >= 0. Should be less
208
+ than your ASGI server's graceful shutdown timeout. Default: 0
209
+ (immediate cancel, identical to pre-v3.3.0 behavior).
210
+ """
211
+
212
+ DEFAULT_PING_INTERVAL = 15
213
+ DEFAULT_SEPARATOR = "\r\n"
214
+
215
+ def __init__(
216
+ self,
217
+ content: ContentStream,
218
+ status_code: int = 200,
219
+ headers: Optional[Mapping[str, str]] = None,
220
+ media_type: str = "text/event-stream",
221
+ background: Optional[BackgroundTask] = None,
222
+ ping: Optional[int] = None,
223
+ sep: Optional[str] = None,
224
+ ping_message_factory: Optional[Callable[[], ServerSentEvent]] = None,
225
+ data_sender_callable: Optional[
226
+ Callable[[], Coroutine[None, None, None]]
227
+ ] = None,
228
+ send_timeout: Optional[float] = None,
229
+ client_close_handler_callable: Optional[
230
+ Callable[[Message], Awaitable[None]]
231
+ ] = None,
232
+ shutdown_event: Optional[anyio.Event] = None,
233
+ shutdown_grace_period: float = 0,
234
+ ) -> None:
235
+ # Validate separator
236
+ if sep not in (None, "\r\n", "\r", "\n"):
237
+ raise ValueError(f"sep must be one of: \\r\\n, \\r, \\n, got: {sep}")
238
+ self.sep = sep or self.DEFAULT_SEPARATOR
239
+
240
+ # If content is sync, wrap it for async iteration
241
+ if isinstance(content, AsyncIterable):
242
+ self.body_iterator = content
243
+ else:
244
+ self.body_iterator = iterate_in_threadpool(content)
245
+
246
+ self.status_code = status_code
247
+ self.media_type = self.media_type if media_type is None else media_type
248
+ self.background = background
249
+ self.data_sender_callable = data_sender_callable
250
+ self.send_timeout = send_timeout
251
+
252
+ # Build SSE-specific headers.
253
+ _headers = MutableHeaders()
254
+ if headers is not None: # pragma: no cover
255
+ _headers.update(headers)
256
+
257
+ # "The no-store response directive indicates that any caches of any kind (private or shared)
258
+ # should not store this response."
259
+ # -- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
260
+ # allow cache control header to be set by user to support fan out proxies
261
+ # https://www.fastly.com/blog/server-sent-events-fastly
262
+
263
+ _headers.setdefault("Cache-Control", "no-store")
264
+ # mandatory for servers-sent events headers
265
+ _headers["Connection"] = "keep-alive"
266
+ _headers["X-Accel-Buffering"] = "no"
267
+ self.init_headers(_headers)
268
+
269
+ self.ping_interval = self.DEFAULT_PING_INTERVAL if ping is None else ping
270
+ self.ping_message_factory = ping_message_factory
271
+
272
+ self.client_close_handler_callable = client_close_handler_callable
273
+
274
+ # Cooperative shutdown (Issue #167): Allow generators to send farewell
275
+ # events before force-cancellation. The grace period should be less than
276
+ # your ASGI server's graceful shutdown timeout (e.g. uvicorn's
277
+ # --timeout-graceful-shutdown), otherwise the process is killed before
278
+ # the grace period expires.
279
+ if shutdown_grace_period < 0:
280
+ raise ValueError("shutdown_grace_period must be >= 0")
281
+ self._shutdown_event = shutdown_event
282
+ self._shutdown_grace_period = shutdown_grace_period
283
+
284
+ self.active = True
285
+ # https://github.com/sysid/sse-starlette/pull/55#issuecomment-1732374113
286
+ self._send_lock = anyio.Lock()
287
+
288
+ @property
289
+ def ping_interval(self) -> Union[int, float]:
290
+ return self._ping_interval
291
+
292
+ @ping_interval.setter
293
+ def ping_interval(self, value: Union[int, float]) -> None:
294
+ if not isinstance(value, (int, float)):
295
+ raise TypeError("ping interval must be int")
296
+ if value < 0:
297
+ raise ValueError("ping interval must be greater than 0")
298
+ self._ping_interval = value
299
+
300
+ def enable_compression(self, force: bool = False) -> None:
301
+ raise NotImplementedError("Compression is not supported for SSE streams.")
302
+
303
+ async def _stream_response(self, send: Send) -> None:
304
+ """Send out SSE data to the client as it becomes available in the iterator."""
305
+ await send(
306
+ {
307
+ "type": "http.response.start",
308
+ "status": self.status_code,
309
+ "headers": self.raw_headers,
310
+ }
311
+ )
312
+
313
+ async for data in self.body_iterator:
314
+ chunk = ensure_bytes(data, self.sep)
315
+ logger.debug("chunk: %s", chunk)
316
+ with anyio.move_on_after(self.send_timeout) as cancel_scope:
317
+ await send(
318
+ {"type": "http.response.body", "body": chunk, "more_body": True}
319
+ )
320
+
321
+ if cancel_scope and cancel_scope.cancel_called:
322
+ aclose = getattr(self.body_iterator, "aclose", None)
323
+ if aclose is not None:
324
+ await aclose()
325
+ raise SendTimeoutError()
326
+
327
+ async with self._send_lock:
328
+ self.active = False
329
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
330
+
331
+ async def _listen_for_disconnect(self, receive: Receive) -> None:
332
+ """Watch for a disconnect message from the client."""
333
+ while self.active:
334
+ message = await receive()
335
+ if message["type"] == "http.disconnect":
336
+ self.active = False
337
+ logger.debug("Got event: http.disconnect. Stop streaming.")
338
+ if self.client_close_handler_callable:
339
+ await self.client_close_handler_callable(message)
340
+ break
341
+
342
+ @staticmethod
343
+ async def _listen_for_exit_signal() -> None:
344
+ """Wait for shutdown signal via the shared watcher."""
345
+ if AppStatus.should_exit:
346
+ return
347
+
348
+ _ensure_watcher_started_on_this_loop()
349
+
350
+ state = _get_shutdown_state()
351
+ event = anyio.Event()
352
+ state.events.add(event)
353
+
354
+ try:
355
+ # Double-check after registration
356
+ if AppStatus.should_exit:
357
+ return
358
+ await event.wait()
359
+ finally:
360
+ state.events.discard(event)
361
+
362
+ async def _listen_for_exit_signal_with_grace(self) -> None:
363
+ """Wait for shutdown signal, then optionally give generator a grace period.
364
+
365
+ Issue #167: When a shutdown_event is provided, the library sets it before
366
+ returning, giving the generator a chance to send farewell events and exit
367
+ cooperatively. The shutdown_grace_period controls how long to wait before
368
+ force-cancelling via task group cancellation.
369
+ """
370
+ await self._listen_for_exit_signal()
371
+
372
+ # Signal the user's generator that shutdown is happening
373
+ if self._shutdown_event:
374
+ self._shutdown_event.set()
375
+
376
+ # Grace period: let generator finish naturally before force-cancel
377
+ if self._shutdown_grace_period > 0:
378
+ with anyio.move_on_after(self._shutdown_grace_period):
379
+ while self.active:
380
+ await anyio.sleep(0.1)
381
+
382
+ async def _ping(self, send: Send) -> None:
383
+ """Periodically send ping messages to keep the connection alive on proxies.
384
+ - frequenccy ca every 15 seconds.
385
+ - Alternatively one can send periodically a comment line (one starting with a ':' character)
386
+ """
387
+ while self.active:
388
+ await anyio.sleep(self._ping_interval)
389
+ sse_ping = (
390
+ self.ping_message_factory()
391
+ if self.ping_message_factory
392
+ else ServerSentEvent(
393
+ comment=f"ping - {datetime.now(timezone.utc)}", sep=self.sep
394
+ )
395
+ )
396
+ ping_bytes = ensure_bytes(sse_ping, self.sep)
397
+ logger.debug("ping: %s", ping_bytes)
398
+
399
+ async with self._send_lock:
400
+ if self.active:
401
+ await send(
402
+ {
403
+ "type": "http.response.body",
404
+ "body": ping_bytes,
405
+ "more_body": True,
406
+ }
407
+ )
408
+
409
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
410
+ """Entrypoint for Starlette's ASGI contract. We spin up tasks:
411
+ - _stream_response to push events
412
+ - _ping to keep the connection alive
413
+ - _listen_for_exit_signal to respond to server shutdown
414
+ - _listen_for_disconnect to respond to client disconnect
415
+ """
416
+ async with anyio.create_task_group() as task_group:
417
+ # https://trio.readthedocs.io/en/latest/reference-core.html#custom-supervisors
418
+ async def cancel_on_finish(coro: Callable[[], Awaitable[None]]):
419
+ await coro()
420
+ task_group.cancel_scope.cancel()
421
+
422
+ task_group.start_soon(cancel_on_finish, lambda: self._stream_response(send))
423
+ task_group.start_soon(cancel_on_finish, lambda: self._ping(send))
424
+ task_group.start_soon(
425
+ cancel_on_finish, self._listen_for_exit_signal_with_grace
426
+ )
427
+
428
+ if self.data_sender_callable:
429
+ task_group.start_soon(self.data_sender_callable)
430
+
431
+ # Wait for the client to disconnect last
432
+ task_group.start_soon(
433
+ cancel_on_finish, lambda: self._listen_for_disconnect(receive)
434
+ )
435
+
436
+ if self.background is not None:
437
+ await self.background()