satori-python 1.3.10__tar.gz → 1.3.11__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {satori_python-1.3.10 → satori_python-1.3.11}/PKG-INFO +1 -1
- {satori_python-1.3.10 → satori_python-1.3.11}/pyproject.toml +1 -1
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/__init__.py +1 -1
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/__init__.py +8 -27
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/network/webhook.py +9 -14
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/network/websocket.py +58 -38
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/element.py +13 -9
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/parser.py +17 -8
- satori_python-1.3.11/src/satori/reconnect.py +105 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/LICENSE +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/README.md +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/_vendor/fleep.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/account.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/account.pyi +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/config.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/network/__init__.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/network/base.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/network/util.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/client/protocol.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/const.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/event.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/exception.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/model.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/py.typed +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/__init__.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/adapter.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/connection.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/formdata.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/model.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/route.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/server/utils.py +0 -0
- {satori_python-1.3.10 → satori_python-1.3.11}/src/satori/utils.py +0 -0
|
@@ -220,6 +220,8 @@ class App(Service):
|
|
|
220
220
|
self.lifecycle_callbacks.append(callback)
|
|
221
221
|
|
|
222
222
|
async def account_update(self, account: Account, state: LoginStatus):
|
|
223
|
+
if account.self_info.status != state:
|
|
224
|
+
account.self_info.status = state
|
|
223
225
|
if self.lifecycle_callbacks:
|
|
224
226
|
task = asyncio.gather(*(callback(account, state) for callback in self.lifecycle_callbacks))
|
|
225
227
|
try:
|
|
@@ -230,26 +232,7 @@ class App(Service):
|
|
|
230
232
|
|
|
231
233
|
async def post(self, event: Event, conn: BaseNetwork):
|
|
232
234
|
ev_type = event.type
|
|
233
|
-
if ev_type
|
|
234
|
-
if TYPE_CHECKING:
|
|
235
|
-
assert isinstance(event, events.LoginEvent)
|
|
236
|
-
login = event.login
|
|
237
|
-
if not login.user:
|
|
238
|
-
logger.warning(f"Received login-added event without user info: {login}")
|
|
239
|
-
return
|
|
240
|
-
login_sn = login.identifier
|
|
241
|
-
account = Account(
|
|
242
|
-
login,
|
|
243
|
-
conn.config,
|
|
244
|
-
conn.proxy_urls,
|
|
245
|
-
self.default_api_cls,
|
|
246
|
-
)
|
|
247
|
-
logger.info(f"account added: {account}")
|
|
248
|
-
(account.connected.set() if login.status == LoginStatus.ONLINE else account.connected.clear())
|
|
249
|
-
self.accounts[login_sn] = account
|
|
250
|
-
conn.accounts[login_sn] = account
|
|
251
|
-
await self.account_update(account, login.status)
|
|
252
|
-
elif ev_type == EventType.LOGIN_UPDATED:
|
|
235
|
+
if ev_type in (EventType.LOGIN_ADDED, EventType.LOGIN_UPDATED):
|
|
253
236
|
if TYPE_CHECKING:
|
|
254
237
|
assert isinstance(event, events.LoginEvent)
|
|
255
238
|
login = event.login
|
|
@@ -258,9 +241,6 @@ class App(Service):
|
|
|
258
241
|
return
|
|
259
242
|
login_sn = login.identifier
|
|
260
243
|
if login_sn not in self.accounts:
|
|
261
|
-
if login.status != LoginStatus.ONLINE:
|
|
262
|
-
logger.warning(f"Received event for unknown account: {event}")
|
|
263
|
-
return
|
|
264
244
|
account = Account(
|
|
265
245
|
login,
|
|
266
246
|
conn.config,
|
|
@@ -271,11 +251,11 @@ class App(Service):
|
|
|
271
251
|
account.connected.set()
|
|
272
252
|
self.accounts[login_sn] = account
|
|
273
253
|
conn.accounts[login_sn] = account
|
|
274
|
-
await self.account_update(account, LoginStatus.ONLINE)
|
|
275
254
|
else:
|
|
276
255
|
account = self.accounts[login_sn]
|
|
277
256
|
account.self_info = login
|
|
278
|
-
|
|
257
|
+
account.config = conn.config
|
|
258
|
+
logger.info(f"account updated: {account} to {login.status.name}")
|
|
279
259
|
(
|
|
280
260
|
account.connected.set()
|
|
281
261
|
if login.status in (LoginStatus.ONLINE, LoginStatus.CONNECT)
|
|
@@ -294,6 +274,7 @@ class App(Service):
|
|
|
294
274
|
logger.warning(f"Received event for unknown account: {event}")
|
|
295
275
|
return
|
|
296
276
|
account = self.accounts[login_sn]
|
|
277
|
+
account.self_info = login
|
|
297
278
|
else:
|
|
298
279
|
login_sn = event.login.identifier
|
|
299
280
|
if login_sn not in self.accounts:
|
|
@@ -318,7 +299,7 @@ class App(Service):
|
|
|
318
299
|
if event.type == EventType.LOGIN_REMOVED:
|
|
319
300
|
logger.info(f"account removed: {account}")
|
|
320
301
|
account.connected.clear()
|
|
321
|
-
await self.account_update(account,
|
|
302
|
+
await self.account_update(account, event.login.status)
|
|
322
303
|
del self.accounts[login_sn]
|
|
323
304
|
del conn.accounts[login_sn]
|
|
324
305
|
|
|
@@ -332,7 +313,7 @@ class App(Service):
|
|
|
332
313
|
async with self.stage("blocking"):
|
|
333
314
|
await any_completed(
|
|
334
315
|
manager.status.wait_for_sigexit(),
|
|
335
|
-
*(conn.status.wait_for("blocking-completed") for conn in self.connections),
|
|
316
|
+
# *(conn.status.wait_for("blocking-completed") for conn in self.connections),
|
|
336
317
|
)
|
|
337
318
|
|
|
338
319
|
async with self.stage("cleanup"):
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
|
+
from datetime import datetime
|
|
4
5
|
|
|
5
6
|
from aiohttp import ClientTimeout, web
|
|
6
7
|
from graia.amnesia.builtins.aiohttp import AiohttpClientService
|
|
@@ -10,7 +11,7 @@ from loguru import logger
|
|
|
10
11
|
from satori.model import Event, LoginStatus, Meta, MetaPayload, Opcode
|
|
11
12
|
from satori.utils import decode
|
|
12
13
|
|
|
13
|
-
from
|
|
14
|
+
from ... import EventType
|
|
14
15
|
from ..config import WebhookInfo as WebhookInfo
|
|
15
16
|
from .base import BaseNetwork
|
|
16
17
|
from .util import validate_response
|
|
@@ -103,25 +104,19 @@ class WebhookNetwork(BaseNetwork[WebhookInfo]):
|
|
|
103
104
|
meta = Meta.parse(data)
|
|
104
105
|
self.proxy_urls = meta.proxy_urls
|
|
105
106
|
for login in meta.logins:
|
|
106
|
-
if
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
logger.info(f"account registered: {account}")
|
|
111
|
-
(account.connected.set() if login.status == LoginStatus.ONLINE else account.connected.clear())
|
|
112
|
-
self.app.accounts[login_sn] = account
|
|
113
|
-
self.accounts[login_sn] = account
|
|
114
|
-
await self.app.account_update(account, LoginStatus.ONLINE)
|
|
107
|
+
if login.identifier in self.accounts:
|
|
108
|
+
await self.app.post(Event(EventType.LOGIN_UPDATED, datetime.now(), login), self)
|
|
109
|
+
else:
|
|
110
|
+
await self.app.post(Event(EventType.LOGIN_ADDED, datetime.now(), login), self)
|
|
115
111
|
await site.start()
|
|
116
112
|
await manager.status.wait_for_sigexit()
|
|
117
113
|
logger.info(f"{self.id} Webhook server exiting...")
|
|
118
114
|
self.close_signal.set()
|
|
119
115
|
for v in list(self.app.accounts.values()):
|
|
120
|
-
if
|
|
116
|
+
if v.self_info.identifier in self.accounts:
|
|
121
117
|
v.connected.clear()
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
del self.accounts[identity]
|
|
118
|
+
v.self_info.status = LoginStatus.OFFLINE
|
|
119
|
+
await self.app.post(Event(EventType.LOGIN_REMOVED, datetime.now(), v.self_info), self)
|
|
125
120
|
|
|
126
121
|
async with self.stage("cleanup"):
|
|
127
122
|
await site.stop()
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
|
+
from datetime import datetime
|
|
4
5
|
from typing import cast
|
|
5
6
|
|
|
6
7
|
import aiohttp
|
|
@@ -8,10 +9,11 @@ from launart.manager import Launart
|
|
|
8
9
|
from launart.utilles import any_completed
|
|
9
10
|
from loguru import logger
|
|
10
11
|
|
|
12
|
+
from satori.const import EventType
|
|
11
13
|
from satori.model import Event, Identify, LoginStatus, MetaPayload, Opcode, Ready
|
|
14
|
+
from satori.reconnect import RECONNECT_STABLE_SECONDS, ReconnectPolicy, is_normal_close, is_server_shutdown
|
|
12
15
|
from satori.utils import decode, encode
|
|
13
16
|
|
|
14
|
-
from ..account import Account
|
|
15
17
|
from ..config import WebsocketsInfo as WebsocketsInfo
|
|
16
18
|
from .base import BaseNetwork
|
|
17
19
|
|
|
@@ -108,24 +110,10 @@ class WsNetwork(BaseNetwork[WebsocketsInfo]):
|
|
|
108
110
|
ready = Ready.parse(data["body"])
|
|
109
111
|
self.proxy_urls = ready.proxy_urls
|
|
110
112
|
for login in ready.logins:
|
|
111
|
-
if
|
|
112
|
-
|
|
113
|
-
login_sn = login.identifier
|
|
114
|
-
if login_sn in self.app.accounts:
|
|
115
|
-
account = self.app.accounts[login_sn]
|
|
116
|
-
self.accounts[login_sn] = account
|
|
117
|
-
if login.status == LoginStatus.ONLINE:
|
|
118
|
-
account.connected.set()
|
|
119
|
-
else:
|
|
120
|
-
account.connected.clear()
|
|
121
|
-
account.config = self.config
|
|
113
|
+
if login.identifier in self.accounts:
|
|
114
|
+
await self.app.post(Event(EventType.LOGIN_UPDATED, datetime.now(), login), self)
|
|
122
115
|
else:
|
|
123
|
-
|
|
124
|
-
logger.info(f"account registered: {account}")
|
|
125
|
-
(account.connected.set() if login.status == LoginStatus.ONLINE else account.connected.clear())
|
|
126
|
-
self.app.accounts[login_sn] = account
|
|
127
|
-
self.accounts[login_sn] = account
|
|
128
|
-
await self.app.account_update(account, LoginStatus.ONLINE)
|
|
116
|
+
await self.app.post(Event(EventType.LOGIN_ADDED, datetime.now(), login), self)
|
|
129
117
|
if not self.accounts:
|
|
130
118
|
logger.warning(f"No account available for {self.config}")
|
|
131
119
|
# return False
|
|
@@ -140,16 +128,43 @@ class WsNetwork(BaseNetwork[WebsocketsInfo]):
|
|
|
140
128
|
logger.error(f"Error while sending heartbeat: {e!r}")
|
|
141
129
|
await asyncio.sleep(9)
|
|
142
130
|
|
|
131
|
+
async def _mark_accounts(self, status: LoginStatus, *, removed: bool = False):
|
|
132
|
+
event_type = EventType.LOGIN_REMOVED if removed else EventType.LOGIN_UPDATED
|
|
133
|
+
for account in list(self.accounts.values()):
|
|
134
|
+
if status in (LoginStatus.ONLINE, LoginStatus.CONNECT):
|
|
135
|
+
account.connected.set()
|
|
136
|
+
else:
|
|
137
|
+
account.connected.clear()
|
|
138
|
+
account.self_info.status = status
|
|
139
|
+
await self.app.post(Event(event_type, datetime.now(), account.self_info), self)
|
|
140
|
+
if removed:
|
|
141
|
+
self.accounts.clear()
|
|
142
|
+
|
|
143
143
|
async def daemon(self, manager: Launart, session: aiohttp.ClientSession):
|
|
144
|
+
policy = ReconnectPolicy()
|
|
144
145
|
while not manager.status.exiting:
|
|
145
146
|
try:
|
|
147
|
+
await self._mark_accounts(LoginStatus.RECONNECT)
|
|
146
148
|
async with session.ws_connect(self.config.ws_base / "events", timeout=300) as self.connection:
|
|
147
149
|
logger.debug(f"{self.id} Websocket client connected")
|
|
150
|
+
await self._mark_accounts(LoginStatus.CONNECT)
|
|
148
151
|
self.close_signal.clear()
|
|
149
152
|
result = await self._authenticate()
|
|
150
153
|
if not result:
|
|
151
|
-
|
|
154
|
+
code = self.connection.close_code
|
|
155
|
+
if is_normal_close(code):
|
|
156
|
+
logger.info(f"{self.id} Connection closed by server (code={code}), login removed")
|
|
157
|
+
await self._mark_accounts(LoginStatus.OFFLINE, removed=True)
|
|
158
|
+
if not is_server_shutdown(code):
|
|
159
|
+
return
|
|
160
|
+
await self._mark_accounts(LoginStatus.RECONNECT)
|
|
161
|
+
if not await policy.sleep():
|
|
162
|
+
logger.error(f"{self.id} Reconnect attempts exhausted, marking accounts offline")
|
|
163
|
+
await self._mark_accounts(LoginStatus.OFFLINE)
|
|
164
|
+
return
|
|
165
|
+
logger.info(f"{self.id} Reconnecting...")
|
|
152
166
|
continue
|
|
167
|
+
connected_at = asyncio.get_running_loop().time()
|
|
153
168
|
self.close_signal.clear()
|
|
154
169
|
close_task = asyncio.create_task(self.close_signal.wait())
|
|
155
170
|
receiver_task = asyncio.create_task(self.message_receive())
|
|
@@ -166,28 +181,33 @@ class WsNetwork(BaseNetwork[WebsocketsInfo]):
|
|
|
166
181
|
await self.connection.close()
|
|
167
182
|
self.close_signal.set()
|
|
168
183
|
self.connection = None
|
|
169
|
-
|
|
170
|
-
if (identity := v.self_info.identifier) in self.accounts:
|
|
171
|
-
v.connected.clear()
|
|
172
|
-
await self.app.account_update(v, LoginStatus.OFFLINE)
|
|
173
|
-
del self.app.accounts[identity]
|
|
174
|
-
del self.accounts[identity]
|
|
184
|
+
await self._mark_accounts(LoginStatus.OFFLINE, removed=True)
|
|
175
185
|
return
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
186
|
+
for task in pending:
|
|
187
|
+
task.cancel()
|
|
188
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
189
|
+
code = self.connection.close_code if self.connection else None
|
|
190
|
+
if is_normal_close(code):
|
|
191
|
+
logger.info(f"{self.id} Connection closed by server (code={code}), login removed")
|
|
192
|
+
await self._mark_accounts(LoginStatus.OFFLINE, removed=True)
|
|
193
|
+
if not is_server_shutdown(code):
|
|
194
|
+
return
|
|
195
|
+
if connected_at and asyncio.get_running_loop().time() - connected_at >= RECONNECT_STABLE_SECONDS:
|
|
196
|
+
policy.reset()
|
|
197
|
+
await self._mark_accounts(LoginStatus.RECONNECT)
|
|
198
|
+
if not await policy.sleep():
|
|
199
|
+
logger.error(f"{self.id} Reconnect attempts exhausted, marking accounts offline")
|
|
200
|
+
await self._mark_accounts(LoginStatus.OFFLINE)
|
|
201
|
+
return
|
|
202
|
+
logger.info(f"{self.id} Reconnecting...")
|
|
203
|
+
continue
|
|
188
204
|
except Exception as e:
|
|
189
205
|
logger.error(f"{self.id} Error while connecting: {e}")
|
|
190
|
-
await
|
|
206
|
+
await self._mark_accounts(LoginStatus.RECONNECT)
|
|
207
|
+
if not await policy.sleep():
|
|
208
|
+
logger.error(f"{self.id} Reconnect attempts exhausted, marking accounts offline")
|
|
209
|
+
await self._mark_accounts(LoginStatus.OFFLINE)
|
|
210
|
+
return
|
|
191
211
|
logger.info(f"{self.id} Reconnecting...")
|
|
192
212
|
|
|
193
213
|
async def launch(self, manager: Launart):
|
|
@@ -72,16 +72,17 @@ class Element:
|
|
|
72
72
|
args = {}
|
|
73
73
|
convert_fields = cls.__convert_fields__
|
|
74
74
|
names = cls.__unpack_names__
|
|
75
|
-
for
|
|
76
|
-
if
|
|
75
|
+
for k, v in attrs.items():
|
|
76
|
+
if k not in convert_fields:
|
|
77
|
+
data[k] = v
|
|
77
78
|
continue
|
|
78
|
-
convert = convert_fields[
|
|
79
|
+
convert = convert_fields[k]
|
|
79
80
|
if convert is True:
|
|
80
|
-
data[
|
|
81
|
+
data[k] = v
|
|
81
82
|
else:
|
|
82
|
-
data[
|
|
83
|
-
if
|
|
84
|
-
args[
|
|
83
|
+
data[k] = convert(v)
|
|
84
|
+
if k in names:
|
|
85
|
+
args[k] = data[k]
|
|
85
86
|
obj = cls(**args) # type: ignore
|
|
86
87
|
obj._attrs.update(data)
|
|
87
88
|
return obj
|
|
@@ -276,9 +277,10 @@ class Resource(Element):
|
|
|
276
277
|
poster: str | None = None,
|
|
277
278
|
cache: bool | None = None,
|
|
278
279
|
timeout: int | None = None,
|
|
279
|
-
|
|
280
|
+
*,
|
|
281
|
+
extra: dict[str, Any] | None = None,
|
|
280
282
|
) -> Self:
|
|
281
|
-
data: dict[str, Any] = {
|
|
283
|
+
data: dict[str, Any] = {}
|
|
282
284
|
if url is not None:
|
|
283
285
|
data |= {"src": url}
|
|
284
286
|
elif path:
|
|
@@ -308,6 +310,8 @@ class Resource(Element):
|
|
|
308
310
|
data["cache"] = cache
|
|
309
311
|
if timeout is not None:
|
|
310
312
|
data["timeout"] = timeout
|
|
313
|
+
if extra:
|
|
314
|
+
data |= extra
|
|
311
315
|
return cls.unpack(data)
|
|
312
316
|
|
|
313
317
|
|
|
@@ -24,25 +24,34 @@ def unescape(text: str) -> str:
|
|
|
24
24
|
return uc_escape_pat3.sub("&", result)
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
def uncapitalize(source: str) -> str:
|
|
28
|
-
return source[:1].lower() + source[1:]
|
|
29
|
-
|
|
30
|
-
|
|
31
27
|
camel_pat = re.compile(r"[_-][a-z]")
|
|
32
|
-
param_pat = re.compile(r".[A-Z]+")
|
|
33
|
-
snake_pat = re.compile(r".[A-Z]")
|
|
34
28
|
|
|
35
29
|
|
|
36
30
|
def camel_case(source: str) -> str:
|
|
37
31
|
return camel_pat.sub(lambda mat: mat[0][1:].upper(), source)
|
|
38
32
|
|
|
39
33
|
|
|
34
|
+
def convert_case(source: str, delimiter: str) -> str:
|
|
35
|
+
source = re.sub(
|
|
36
|
+
r"([A-Z]+)([A-Z][a-z])",
|
|
37
|
+
rf"\1{delimiter}\2",
|
|
38
|
+
source,
|
|
39
|
+
)
|
|
40
|
+
source = re.sub(
|
|
41
|
+
r"([a-z0-9])([A-Z])",
|
|
42
|
+
rf"\1{delimiter}\2",
|
|
43
|
+
source,
|
|
44
|
+
)
|
|
45
|
+
source = re.sub(r"[-_]+", delimiter, source)
|
|
46
|
+
return source.strip("-_").lower()
|
|
47
|
+
|
|
48
|
+
|
|
40
49
|
def param_case(source: str) -> str:
|
|
41
|
-
return
|
|
50
|
+
return convert_case(source, "-")
|
|
42
51
|
|
|
43
52
|
|
|
44
53
|
def snake_case(source: str) -> str:
|
|
45
|
-
return
|
|
54
|
+
return convert_case(source, "_")
|
|
46
55
|
|
|
47
56
|
|
|
48
57
|
def ensure_list(value: T | list[T] | None) -> list[T]:
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
RECONNECT_DELAYS: tuple[float, ...] = (5.0, 10.0, 20.0, 40.0, 60.0)
|
|
6
|
+
"""断线重连的退避时间(秒)。"""
|
|
7
|
+
|
|
8
|
+
RECONNECT_ATTEMPTS_PER_DELAY = 5
|
|
9
|
+
"""每个退避档位的重试次数。"""
|
|
10
|
+
|
|
11
|
+
MAX_RECONNECT_ATTEMPTS = len(RECONNECT_DELAYS) * RECONNECT_ATTEMPTS_PER_DELAY
|
|
12
|
+
"""连续重连失败的最大次数。"""
|
|
13
|
+
|
|
14
|
+
RECONNECT_STABLE_SECONDS = 60.0
|
|
15
|
+
"""连接稳定超过该时长后,重置重连计数。"""
|
|
16
|
+
|
|
17
|
+
RECONNECT_TOTAL_SECONDS = sum(delay * RECONNECT_ATTEMPTS_PER_DELAY for delay in RECONNECT_DELAYS)
|
|
18
|
+
"""完整走完一轮重连退避所需的总时长(秒)。"""
|
|
19
|
+
|
|
20
|
+
SERVER_SHUTDOWN_CLOSE_CODES = frozenset({1000, 1001, 1012})
|
|
21
|
+
"""服务端主动下线或重启时使用的 WebSocket 关闭码。
|
|
22
|
+
|
|
23
|
+
- ``1000`` Normal Closure:正常的主动关闭。
|
|
24
|
+
- ``1001`` Going Away:服务端或代理准备下线。
|
|
25
|
+
- ``1012`` Service Restart:uvicorn 等服务端优雅关闭时发送的关闭码。
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
AUTH_FAILURE_CLOSE_CODES = frozenset({3000})
|
|
29
|
+
"""Satori 服务端鉴权失败时使用的自定义关闭码。"""
|
|
30
|
+
|
|
31
|
+
NORMAL_CLOSE_CODES = SERVER_SHUTDOWN_CLOSE_CODES | AUTH_FAILURE_CLOSE_CODES
|
|
32
|
+
"""主动关闭的 WebSocket 关闭码。"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_normal_close(code: int | None) -> bool:
|
|
36
|
+
"""判断 WebSocket 是否为主动关闭(服务端关闭或本端主动退出)。"""
|
|
37
|
+
return code in NORMAL_CLOSE_CODES
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_server_shutdown(code: int | None) -> bool:
|
|
41
|
+
"""判断 WebSocket 是否由服务端主动下线或重启导致。"""
|
|
42
|
+
return code in SERVER_SHUTDOWN_CLOSE_CODES
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ReconnectPolicy:
|
|
46
|
+
"""有上限的断线重连策略。
|
|
47
|
+
|
|
48
|
+
连续失败时按 ``RECONNECT_DELAYS`` 的顺序退避,每个档位重试
|
|
49
|
+
``RECONNECT_ATTEMPTS_PER_DELAY`` 次;连接稳定后调用 :meth:`reset`。
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
delays: tuple[float, ...] = RECONNECT_DELAYS,
|
|
55
|
+
attempts_per_delay: int = RECONNECT_ATTEMPTS_PER_DELAY,
|
|
56
|
+
):
|
|
57
|
+
if not delays:
|
|
58
|
+
raise ValueError("delays must not be empty")
|
|
59
|
+
if attempts_per_delay <= 0:
|
|
60
|
+
raise ValueError("attempts_per_delay must be positive")
|
|
61
|
+
self.delays = delays
|
|
62
|
+
self.attempts_per_delay = attempts_per_delay
|
|
63
|
+
self.attempts = 0
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def max_attempts(self) -> int:
|
|
67
|
+
return len(self.delays) * self.attempts_per_delay
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def exhausted(self) -> bool:
|
|
71
|
+
return self.attempts >= self.max_attempts
|
|
72
|
+
|
|
73
|
+
def reset(self) -> None:
|
|
74
|
+
self.attempts = 0
|
|
75
|
+
|
|
76
|
+
def next_delay(self) -> float | None:
|
|
77
|
+
"""返回下一次重连前的等待时间;次数用尽时返回 ``None``。"""
|
|
78
|
+
if self.exhausted:
|
|
79
|
+
return None
|
|
80
|
+
index = min(self.attempts // self.attempts_per_delay, len(self.delays) - 1)
|
|
81
|
+
self.attempts += 1
|
|
82
|
+
return self.delays[index]
|
|
83
|
+
|
|
84
|
+
async def sleep(self) -> bool:
|
|
85
|
+
"""等待下一次重连;次数用尽时返回 ``False``。"""
|
|
86
|
+
delay = self.next_delay()
|
|
87
|
+
if delay is None:
|
|
88
|
+
return False
|
|
89
|
+
await asyncio.sleep(delay)
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
__all__ = [
|
|
94
|
+
"AUTH_FAILURE_CLOSE_CODES",
|
|
95
|
+
"MAX_RECONNECT_ATTEMPTS",
|
|
96
|
+
"NORMAL_CLOSE_CODES",
|
|
97
|
+
"RECONNECT_ATTEMPTS_PER_DELAY",
|
|
98
|
+
"RECONNECT_DELAYS",
|
|
99
|
+
"RECONNECT_STABLE_SECONDS",
|
|
100
|
+
"RECONNECT_TOTAL_SECONDS",
|
|
101
|
+
"SERVER_SHUTDOWN_CLOSE_CODES",
|
|
102
|
+
"ReconnectPolicy",
|
|
103
|
+
"is_normal_close",
|
|
104
|
+
"is_server_shutdown",
|
|
105
|
+
]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|