-
Notifications
You must be signed in to change notification settings - Fork 845
/
Copy path__init__.py
256 lines (227 loc) · 11 KB
/
__init__.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""websockets bassd Socket Mode client
* https://api.slack.com/apis/connections/socket
* https://slack.dev/python-slack-sdk/socket-mode/
* https://pypi.org/project/websockets/
"""
import asyncio
import logging
from asyncio import Future, Lock
from logging import Logger
from asyncio import Queue
from typing import Union, Optional, List, Callable, Awaitable
import websockets
from websockets.exceptions import WebSocketException
# To keep compatibility with websockets 8.x, we use this import over .legacy.client
from websockets import WebSocketClientProtocol
from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient
from slack_sdk.socket_mode.async_listeners import (
AsyncWebSocketMessageListener,
AsyncSocketModeRequestListener,
)
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.web.async_client import AsyncWebClient
from ..logger.messages import debug_redacted_message_string
class SocketModeClient(AsyncBaseSocketModeClient):
logger: Logger
web_client: AsyncWebClient
app_token: str
wss_uri: Optional[str]
auto_reconnect_enabled: bool
message_queue: Queue
message_listeners: List[
Union[
AsyncWebSocketMessageListener,
Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]],
]
]
socket_mode_request_listeners: List[
Union[
AsyncSocketModeRequestListener,
Callable[["AsyncBaseSocketModeClient", SocketModeRequest], Awaitable[None]],
]
]
message_receiver: Optional[Future]
message_processor: Future
ping_interval: float
trace_enabled: bool
current_session: Optional[WebSocketClientProtocol]
current_session_monitor: Optional[Future]
auto_reconnect_enabled: bool
default_auto_reconnect_enabled: bool
closed: bool
connect_operation_lock: Lock
def __init__(
self,
app_token: str,
logger: Optional[Logger] = None,
web_client: Optional[AsyncWebClient] = None,
auto_reconnect_enabled: bool = True,
ping_interval: float = 10,
trace_enabled: bool = False,
):
"""Socket Mode client
Args:
app_token: App-level token
logger: Custom logger
web_client: Web API client
auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
ping_interval: interval for ping-pong with Slack servers (seconds)
trace_enabled: True if more verbose logs to see what's happening under the hood
"""
self.app_token = app_token
self.logger = logger or logging.getLogger(__name__)
self.web_client = web_client or AsyncWebClient()
self.closed = False
self.connect_operation_lock = Lock()
self.default_auto_reconnect_enabled = auto_reconnect_enabled
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.ping_interval = ping_interval
self.trace_enabled = trace_enabled
self.wss_uri = None
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_monitor = None
self.message_receiver = None
self.message_processor = asyncio.ensure_future(self.process_messages())
async def monitor_current_session(self) -> None:
# In the asyncio runtime, accessing a shared object (self.current_session here) from
# multiple tasks can cause race conditions and errors.
# To avoid such, we access only the session that is active when this loop starts.
session: WebSocketClientProtocol = self.current_session
session_id: str = await self.session_id()
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started")
try:
while not self.closed:
if session != self.current_session:
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
break
await asyncio.sleep(self.ping_interval)
try:
if self.auto_reconnect_enabled and (session is None or session.closed):
self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...")
await self.connect_to_new_endpoint()
except Exception as e:
self.logger.error(
"Failed to check the current session or reconnect to the server "
f"(error: {type(e).__name__}, message: {e}, session: {session_id})"
)
except asyncio.CancelledError:
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
raise
async def receive_messages(self) -> None:
# In the asyncio runtime, accessing a shared object (self.current_session here) from
# multiple tasks can cause race conditions and errors.
# To avoid such, we access only the session that is active when this loop starts.
session: WebSocketClientProtocol = self.current_session
session_id: str = await self.session_id()
consecutive_error_count = 0
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"A new receive_messages() execution loop with {session_id} started")
try:
while not self.closed:
if session != self.current_session:
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
break
try:
message = await session.recv()
if message is not None:
if isinstance(message, bytes):
message = message.decode("utf-8")
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Received message: {debug_redacted_message_string(message)}, session: {session_id}"
)
await self.enqueue_message(message)
consecutive_error_count = 0
except Exception as e:
consecutive_error_count += 1
self.logger.error(
f"Failed to receive or enqueue a message: {type(e).__name__}, error: {e}, session: {session_id}"
)
if isinstance(e, websockets.ConnectionClosedError):
await asyncio.sleep(self.ping_interval)
else:
await asyncio.sleep(consecutive_error_count)
except asyncio.CancelledError:
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
raise
async def is_connected(self) -> bool:
return not self.closed and self.current_session is not None and not self.current_session.closed
async def session_id(self) -> str:
return self.build_session_id(self.current_session)
async def connect(self):
if self.wss_uri is None:
self.wss_uri = await self.issue_new_wss_url()
old_session: Optional[WebSocketClientProtocol] = None if self.current_session is None else self.current_session
# NOTE: websockets does not support proxy settings
self.current_session = await websockets.connect(
uri=self.wss_uri,
ping_interval=self.ping_interval,
)
session_id = await self.session_id()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.logger.info(f"A new session ({session_id}) has been established")
if self.current_session_monitor is not None:
self.current_session_monitor.cancel()
self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session())
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}")
if self.message_receiver is not None:
self.message_receiver.cancel()
self.message_receiver = asyncio.ensure_future(self.receive_messages())
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}")
if old_session is not None:
await old_session.close()
old_session_id = self.build_session_id(old_session)
self.logger.info(f"The old session ({old_session_id}) has been abandoned")
async def disconnect(self):
if self.current_session is not None:
await self.current_session.close()
async def send_message(self, message: str):
session = self.current_session
session_id = self.build_session_id(session)
if self.logger.level <= logging.DEBUG:
self.logger.debug(f"Sending a message: {message}, session: {session_id}")
try:
await session.send(message)
except WebSocketException as e:
# We rarely get this exception while replacing the underlying WebSocket connections.
# We can do one more try here as the self.current_session should be ready now.
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Failed to send a message (error: {e}, message: {message}, session: {session_id})"
" as the underlying connection was replaced. Retrying the same request only one time..."
)
# Although acquiring self.connect_operation_lock also for the first method call is the safest way,
# we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
try:
if await self.is_connected():
await self.current_session.send(message)
else:
self.logger.warning(f"The current session ({session_id}) is no longer active. Failed to send a message")
raise e
finally:
if self.connect_operation_lock.locked() is True:
self.connect_operation_lock.release()
async def close(self):
self.closed = True
self.auto_reconnect_enabled = False
await self.disconnect()
self.message_processor.cancel()
if self.current_session_monitor is not None:
self.current_session_monitor.cancel()
if self.message_receiver is not None:
self.message_receiver.cancel()
@classmethod
def build_session_id(cls, session: WebSocketClientProtocol) -> str:
if session is None:
return ""
return "s_" + str(hash(session))