-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsse.py
183 lines (163 loc) · 6.25 KB
/
sse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from typing import AsyncGenerator
from fastapi import Request
from httpx import HTTPError, Response, Timeout
from shared import WEBHOOKS_URL
from shared.log_config import get_logger
from shared.util.rich_async_client import RichAsyncClient
logger = get_logger(__name__)
SSE_PING_PERIOD = 15
# SSE sends a ping every 15 seconds, so user will get at least one message within this timeout
default_timeout = Timeout(SSE_PING_PERIOD, read=3600.0) # 1 hour read timeout
event_timeout = Timeout(SSE_PING_PERIOD, read=180) # 3 minute timeout
async def yield_lines_with_disconnect_check(
request: Request, response: Response
) -> AsyncGenerator[str, None]:
async for line in response.aiter_lines():
if await request.is_disconnected():
logger.bind(body=request).debug("SSE Client disconnected.")
break # Client has disconnected, stop sending events
yield line + "\n"
async def sse_subscribe_wallet(
request: Request, wallet_id: str
) -> AsyncGenerator[str, None]:
"""
Subscribe to server-side events for a specific wallet ID.
Args:
wallet_id: The ID of the wallet subscribing to the events.
"""
bound_logger = logger.bind(body={"wallet_id": wallet_id})
try:
async with RichAsyncClient(timeout=default_timeout) as client:
bound_logger.debug("Connecting stream to /sse/wallet_id")
async with client.stream(
"GET", f"{WEBHOOKS_URL}/sse/{wallet_id}"
) as response:
async for line in yield_lines_with_disconnect_check(request, response):
yield line
except HTTPError as e:
bound_logger.exception(
"Caught HTTPError while handling SSE subscribe by wallet."
)
raise e
async def sse_subscribe_wallet_topic(
request: Request, wallet_id: str, topic: str
) -> AsyncGenerator[str, None]:
"""
Subscribe to server-side events for a specific wallet ID and topic.
Args:
wallet_id: The ID of the wallet subscribing to the events.
topic: The topic to which the wallet is subscribing.
"""
bound_logger = logger.bind(body={"wallet_id": wallet_id, "topic": topic})
try:
async with RichAsyncClient(timeout=default_timeout) as client:
bound_logger.debug("Connecting stream to /sse/wallet_id/topic")
async with client.stream(
"GET", f"{WEBHOOKS_URL}/sse/{wallet_id}/{topic}"
) as response:
async for line in yield_lines_with_disconnect_check(request, response):
yield line
except HTTPError as e:
bound_logger.exception(
"Caught HTTPError while handling SSE subscribe by wallet and topic."
)
raise e
async def sse_subscribe_event_with_state(
request: Request,
wallet_id: str,
topic: str,
desired_state: str,
) -> AsyncGenerator[str, None]:
"""
Subscribe to server-side events for a specific wallet ID and topic.
Args:
wallet_id: The ID of the wallet subscribing to the events.
topic: The topic to which the wallet is subscribing.
"""
bound_logger = logger.bind(
body={"wallet_id": wallet_id, "topic": topic, "state": desired_state}
)
try:
async with RichAsyncClient(timeout=event_timeout) as client:
bound_logger.debug(
"Connecting stream to /sse/wallet_id/topic/desired_state"
)
async with client.stream(
"GET", f"{WEBHOOKS_URL}/sse/{wallet_id}/{topic}/{desired_state}"
) as response:
async for line in yield_lines_with_disconnect_check(request, response):
yield line
except HTTPError as e:
bound_logger.exception(
"Caught HTTPError while handling SSE subscribe event by wallet, topic and state."
)
raise e
async def sse_subscribe_stream_with_fields(
request: Request,
wallet_id: str,
topic: str,
field: str,
field_id: str,
) -> AsyncGenerator[str, None]:
"""
Subscribe to server-side events for a specific wallet ID and topic.
Args:
wallet_id: The ID of the wallet subscribing to the events.
topic: The topic to which the wallet is subscribing.
"""
bound_logger = logger.bind(
body={"wallet_id": wallet_id, "topic": topic, field: field_id}
)
try:
async with RichAsyncClient(timeout=default_timeout) as client:
bound_logger.debug(
"Connecting stream to /sse/wallet_id/topic/field/field_id"
)
async with client.stream(
"GET", f"{WEBHOOKS_URL}/sse/{wallet_id}/{topic}/{field}/{field_id}"
) as response:
async for line in yield_lines_with_disconnect_check(request, response):
yield line
except HTTPError as e:
bound_logger.exception(
"Caught HTTPError while handling SSE subscribe stream by wallet, topic, and fields."
)
raise e
async def sse_subscribe_event_with_field_and_state(
request: Request,
wallet_id: str,
topic: str,
field: str,
field_id: str,
desired_state: str,
) -> AsyncGenerator[str, None]:
"""
Subscribe to server-side events for a specific wallet ID and topic.
Args:
wallet_id: The ID of the wallet subscribing to the events.
topic: The topic to which the wallet is subscribing.
"""
bound_logger = logger.bind(
body={
"wallet_id": wallet_id,
"topic": topic,
field: field_id,
"state": desired_state,
}
)
try:
async with RichAsyncClient(timeout=event_timeout) as client:
bound_logger.debug(
"Connecting stream to /sse/wallet_id/topic/field/field_id/desired_state"
)
async with client.stream(
"GET",
f"{WEBHOOKS_URL}/sse/{wallet_id}/{topic}/{field}/{field_id}/{desired_state}",
) as response:
async for line in yield_lines_with_disconnect_check(request, response):
yield line
except HTTPError as e:
bound_logger.exception(
"Caught HTTPError while handling SSE subscribe event by wallet, topic, fields, and state."
)
raise e