-
Notifications
You must be signed in to change notification settings - Fork 8
Dev/clientlist #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Dev/clientlist #45
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d32e241
feat: 配置client 池
164108e
feat: format code
f7ca375
feat: close #44
232cb2b
feat: update metric setting
6b12913
feat: update metric setting
64c59e2
feat: update metric setting
62f99d0
feat: add lock
d52bba7
feat: fix bugs
f152b59
feat: update round
441fbd5
feat: update round
698a246
feat: update round
8896845
feat: update round
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
89 changes: 89 additions & 0 deletions
89
packages/sunagent-ext/src/sunagent_ext/tweet/twitter_client_pool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import asyncio | ||
| import logging | ||
| import time | ||
| from dataclasses import dataclass | ||
| from typing import Any, Coroutine, List, Optional | ||
|
|
||
| import tweepy | ||
| from tweepy import Client | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| RETRY_AFTER_SEC = 15 * 60 # 15 分钟 | ||
|
|
||
|
|
||
| @dataclass | ||
| class _PoolItem: # type: ignore[no-any-unimported] | ||
| client: tweepy.Client # type: ignore[no-any-unimported] | ||
| dead_at: Optional[float] = None # None 表示 alive | ||
|
|
||
|
|
||
| class TwitterClientPool: | ||
| """ | ||
| Twitter 客户端专用池:轮询获取、异常熔断、15 min 复活、支持永久摘除 | ||
| """ | ||
|
|
||
| def __init__(self, clients: List[Client], retry_after: float = RETRY_AFTER_SEC): # type: ignore[no-any-unimported] | ||
| self._retry_after = retry_after | ||
| self._pool: List[_PoolItem] = [_PoolItem(c) for c in clients] | ||
| self._lock = asyncio.Lock() | ||
| self._not_empty = asyncio.Event() | ||
| self._rr_idx = 0 | ||
| if self._pool: | ||
| self._not_empty.set() | ||
|
|
||
| # -------------------- 对外 API -------------------- | ||
| async def acquire(self) -> tuple[Client, Any]: # type: ignore[no-any-unimported] | ||
| """轮询获取一个健康 client;池空时阻塞直到有可用实例。""" | ||
| while True: | ||
| async with self._lock: | ||
| now = time.time() | ||
| # 1. 复活 | ||
| for it in self._pool: | ||
| if it.dead_at and now - it.dead_at >= self._retry_after: | ||
| it.dead_at = None | ||
| logger.info("client %s revived", id(it.client)) | ||
|
|
||
| # 2. 留活的 | ||
| alive = [it for it in self._pool if it.dead_at is None] | ||
| if not alive: | ||
| self._not_empty.clear() | ||
| logger.warning("all clients dead, waiting ...") | ||
| await asyncio.wait_for(self._not_empty.wait(), timeout=1) | ||
| continue | ||
|
|
||
| # 3. 轮询 | ||
| idx = self._rr_idx % len(alive) | ||
|
boboliu-1010 marked this conversation as resolved.
Outdated
|
||
| self._rr_idx += 1 | ||
| chosen = alive[idx] | ||
| # 移到尾部,公平 RR | ||
| self._pool.remove(chosen) | ||
| self._pool.append(chosen) | ||
| client = chosen.client | ||
| return client, client.consumer_key | ||
|
|
||
| def remove(self, client: tweepy.Client) -> None: # type: ignore[no-any-unimported] | ||
| """永久摘除某个 client(不再放回池子)。""" | ||
| for it in self._pool: | ||
| if it.client is client: | ||
| self._pool.remove(it) | ||
|
boboliu-1010 marked this conversation as resolved.
Outdated
|
||
| logger.info("client %s removed permanently", id(client)) | ||
| if not any(it.dead_at is None for it in self._pool): | ||
| self._not_empty.clear() | ||
|
boboliu-1010 marked this conversation as resolved.
|
||
| return | ||
|
|
||
| def release(self, client: tweepy.Client, *, failed: bool = False) -> None: # type: ignore[no-any-unimported] | ||
| """归还 client;failed=True 表示请求异常,触发 15 min 熔断。""" | ||
| for it in self._pool: | ||
| if it.client is client: | ||
| if failed: | ||
| it.dead_at = time.time() | ||
| logger.warning("client %s dead, will retry after %s min", id(client), self._retry_after // 60) | ||
| asyncio.create_task(self._notify_maybe_alive()) | ||
| return | ||
|
|
||
| # -------------------- 内部 -------------------- | ||
| async def _notify_maybe_alive(self) -> None: | ||
| async with self._lock: | ||
| if any(it.dead_at is None for it in self._pool): | ||
| self._not_empty.set() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.