fix: make every client close what it built and nothing else

A client used to close whatever transport, recorder or cache it happened
to hold, injected or not, so the first client to shut down killed the
backend its siblings were still using. That is why the explicit-sharing
path the architecture prescribes was unusable in practice and downstream
projects fell back to one private instance per client. The mirror image
of the same gap: the redis clients the factories build for the limiter
and the breaker were never closed at all, because nobody kept a
reference to them once they were handed to the retry middleware.

Ownership is now stated once, the way RedisLimiter already stated it:
whoever builds a resource closes it, injected ones are left alone. The
constructor is the full-injection path, so it owns nothing by default
and only the factories mark what they built. RedisCache gains the same
rule for its own client, and the three copies of the "probe for aclose,
fall back to close" dance collapse into a single helper so the next
correction cannot land in only one of them.
This commit is contained in:
2026-08-24 08:34:06 -04:00
parent e7caa500e2
commit e69ca4c82c
5 changed files with 423 additions and 61 deletions
+11 -2
View File
@@ -25,14 +25,20 @@ class RedisCache:
"Redis 缓存后端需要 redis 包: pip install 'polygateway[redis]'"
) from _IMPORT_ERROR
self._client = client
# 注入的客户端归注入方管理: 关掉它会弄死共享同一连接的其他组件
# (与 RedisLimiter/RedisGate 同一纪律)
self._owns_client = False
@classmethod
def from_url(cls, url: str) -> RedisCache:
"""自建并持有 Redis 客户端(aclose 时代关);共享后端请直接注入 client。"""
if aioredis is None:
raise ImportError(
"Redis 缓存后端需要 redis 包: pip install 'polygateway[redis]'"
) from _IMPORT_ERROR
return cls(aioredis.from_url(url, decode_responses=True))
cache = cls(aioredis.from_url(url, decode_responses=True))
cache._owns_client = True
return cache
async def get(self, key: str) -> str | None:
return await self._client.get(key)
@@ -41,4 +47,7 @@ class RedisCache:
await self._client.set(key, value, ex=ttl_s)
async def aclose(self) -> None:
await self._client.aclose()
"""幂等释放自建客户端;注入的客户端归注入方管理。"""
if self._owns_client:
self._owns_client = False
await self._client.aclose()