sycommon-python-lib 0.1.16__py3-none-any.whl → 0.1.56b1__py3-none-any.whl

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.
Files changed (36) hide show
  1. sycommon/config/Config.py +6 -2
  2. sycommon/config/RerankerConfig.py +1 -0
  3. sycommon/database/async_base_db_service.py +36 -0
  4. sycommon/database/async_database_service.py +96 -0
  5. sycommon/database/database_service.py +6 -1
  6. sycommon/health/metrics.py +13 -0
  7. sycommon/llm/__init__.py +0 -0
  8. sycommon/llm/embedding.py +149 -0
  9. sycommon/llm/get_llm.py +177 -0
  10. sycommon/llm/llm_logger.py +126 -0
  11. sycommon/logging/async_sql_logger.py +65 -0
  12. sycommon/logging/kafka_log.py +36 -14
  13. sycommon/logging/logger_levels.py +23 -0
  14. sycommon/logging/sql_logger.py +53 -0
  15. sycommon/middleware/context.py +2 -0
  16. sycommon/middleware/middleware.py +4 -0
  17. sycommon/middleware/traceid.py +155 -32
  18. sycommon/models/mqlistener_config.py +1 -0
  19. sycommon/rabbitmq/rabbitmq_client.py +377 -821
  20. sycommon/rabbitmq/rabbitmq_pool.py +338 -0
  21. sycommon/rabbitmq/rabbitmq_service.py +411 -229
  22. sycommon/services.py +116 -61
  23. sycommon/synacos/example.py +153 -0
  24. sycommon/synacos/example2.py +129 -0
  25. sycommon/synacos/feign.py +90 -413
  26. sycommon/synacos/feign_client.py +335 -0
  27. sycommon/synacos/nacos_service.py +159 -106
  28. sycommon/synacos/param.py +75 -0
  29. sycommon/tools/merge_headers.py +97 -0
  30. sycommon/tools/snowflake.py +296 -7
  31. {sycommon_python_lib-0.1.16.dist-info → sycommon_python_lib-0.1.56b1.dist-info}/METADATA +19 -13
  32. sycommon_python_lib-0.1.56b1.dist-info/RECORD +68 -0
  33. sycommon_python_lib-0.1.16.dist-info/RECORD +0 -52
  34. {sycommon_python_lib-0.1.16.dist-info → sycommon_python_lib-0.1.56b1.dist-info}/WHEEL +0 -0
  35. {sycommon_python_lib-0.1.16.dist-info → sycommon_python_lib-0.1.56b1.dist-info}/entry_points.txt +0 -0
  36. {sycommon_python_lib-0.1.16.dist-info → sycommon_python_lib-0.1.56b1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,338 @@
1
+ import asyncio
2
+ import random
3
+ from typing import Optional, List, Dict, Callable, Tuple
4
+ from aio_pika import connect_robust, RobustChannel, Message
5
+ from aio_pika.abc import (
6
+ AbstractRobustConnection, AbstractQueue, AbstractExchange, AbstractMessage
7
+ )
8
+ from aio_pika.exceptions import ChannelClosed
9
+ import aiormq.exceptions
10
+
11
+ from sycommon.logging.kafka_log import SYLogger
12
+
13
+ logger = SYLogger
14
+
15
+
16
+ class RabbitMQConnectionPool:
17
+ """单连接单通道RabbitMQ客户端(核心特性:依赖connect_robust原生自动重连/恢复 + 仅关闭时释放资源)"""
18
+
19
+ def __init__(
20
+ self,
21
+ hosts: List[str],
22
+ port: int,
23
+ username: str,
24
+ password: str,
25
+ virtualhost: str = "/",
26
+ heartbeat: int = 30,
27
+ app_name: str = "",
28
+ connection_timeout: int = 30,
29
+ reconnect_interval: int = 5,
30
+ prefetch_count: int = 2,
31
+ ):
32
+ # 基础配置校验与初始化
33
+ self.hosts = [host.strip() for host in hosts if host.strip()]
34
+ if not self.hosts:
35
+ raise ValueError("至少需要提供一个RabbitMQ主机地址")
36
+
37
+ self.port = port
38
+ self.username = username
39
+ self.password = password
40
+ self.virtualhost = virtualhost
41
+ self.app_name = app_name or "rabbitmq-client"
42
+ self.heartbeat = heartbeat
43
+ self.connection_timeout = connection_timeout
44
+ self.reconnect_interval = reconnect_interval
45
+ self.prefetch_count = prefetch_count
46
+
47
+ # 初始化时随机选择一个主机地址(固定使用,依赖原生重连)
48
+ self._current_host: str = random.choice(self.hosts)
49
+ logger.info(
50
+ f"随机选择RabbitMQ主机: {self._current_host}(依赖connect_robust原生自动重连/恢复)")
51
+
52
+ # 核心资源(单连接+单通道,基于原生自动重连)
53
+ self._connection: Optional[AbstractRobustConnection] = None # 原生自动重连连接
54
+ self._channel: Optional[RobustChannel] = None # 单通道(原生自动恢复)
55
+ # 消费者通道跟踪(独立于主通道)
56
+ self._consumer_channels: Dict[str,
57
+ Tuple[RobustChannel, Callable, bool, dict]] = {}
58
+
59
+ # 状态控制(并发安全+生命周期管理)
60
+ self._lock = asyncio.Lock()
61
+ self._initialized = False
62
+ self._is_shutdown = False
63
+
64
+ async def _is_connection_valid(self) -> bool:
65
+ """原子化检查连接有效性(所有状态判断均加锁,确保原子性)"""
66
+ async with self._lock:
67
+ # 优先级:先判断是否关闭,再判断是否初始化,最后判断连接状态
68
+ return not self._is_shutdown and self._initialized and self._connection is not None and not self._connection.is_closed
69
+
70
+ @property
71
+ async def is_alive(self) -> bool:
72
+ """对外暴露的连接存活状态(原子化判断)"""
73
+ async with self._lock:
74
+ if self._is_shutdown:
75
+ return False
76
+ # 存活条件:未关闭 + 已初始化 + 连接有效 + 主通道有效
77
+ return self._initialized and self._connection is not None and not self._connection.is_closed and self._channel is not None and not self._channel.is_closed
78
+
79
+ async def _create_connection(self) -> AbstractRobustConnection:
80
+ """创建原生自动重连连接(仅创建一次,内部自动重试)"""
81
+ async with self._lock:
82
+ if self._is_shutdown:
83
+ raise RuntimeError("客户端已关闭,无法创建连接")
84
+
85
+ conn_url = f"amqp://{self.username}:{self.password}@{self._current_host}:{self.port}/{self.virtualhost}?name={self.app_name}&heartbeat={self.heartbeat}&reconnect_interval={self.reconnect_interval}&fail_fast=1"
86
+ logger.info(f"尝试创建原生自动重连连接: {self._current_host}:{self.port}")
87
+
88
+ try:
89
+ conn = await connect_robust(
90
+ conn_url,
91
+ timeout=self.connection_timeout,
92
+ )
93
+ logger.info(f"连接创建成功: {self._current_host}:{self.port}(原生自动重连已启用)")
94
+ return conn
95
+ except Exception as e:
96
+ logger.error(f"连接创建失败: {str(e)}", exc_info=True)
97
+ raise ConnectionError(
98
+ f"无法连接RabbitMQ主机 {self._current_host}:{self.port}") from e
99
+
100
+ async def _init_single_channel(self):
101
+ """初始化单通道(通道自带原生自动恢复)"""
102
+ async with self._lock:
103
+ # 先判断是否关闭(优先级最高)
104
+ if self._is_shutdown:
105
+ raise RuntimeError("客户端已关闭,无法初始化通道")
106
+ # 再判断连接是否有效
107
+ if not self._connection or self._connection.is_closed:
108
+ raise RuntimeError("无有效连接,无法初始化通道")
109
+
110
+ # 清理旧通道(如果存在)
111
+ if self._channel and not self._channel.is_closed:
112
+ await self._channel.close()
113
+
114
+ # 创建单通道并设置QOS
115
+ try:
116
+ self._channel = await self._connection.channel()
117
+ await self._channel.set_qos(prefetch_count=self.prefetch_count)
118
+ logger.info(f"单通道初始化完成(带原生自动恢复)")
119
+ except Exception as e:
120
+ logger.error(f"创建单通道失败: {str(e)}", exc_info=True)
121
+ raise
122
+
123
+ async def _check_and_recover_channel(self) -> RobustChannel:
124
+ """检查并恢复通道(确保通道有效,所有状态判断加锁)"""
125
+ async with self._lock:
126
+ # 1. 先判断是否关闭(优先级最高)
127
+ if self._is_shutdown:
128
+ raise RuntimeError("客户端已关闭,无法获取通道")
129
+ # 2. 检查连接状态
130
+ if not self._connection or self._connection.is_closed:
131
+ raise RuntimeError("连接已关闭(等待原生重连)")
132
+ # 3. 通道失效时重新创建
133
+ if not self._channel or self._channel.is_closed:
134
+ logger.warning("通道失效,重新创建(依赖原生自动恢复)")
135
+ await self._init_single_channel()
136
+
137
+ return self._channel
138
+
139
+ async def init_pools(self):
140
+ """初始化客户端(仅执行一次)"""
141
+ async with self._lock:
142
+ # 原子化判断:是否已关闭/已初始化
143
+ if self._is_shutdown:
144
+ raise RuntimeError("客户端已关闭,无法初始化")
145
+ if self._initialized:
146
+ logger.warning("客户端已初始化,无需重复调用")
147
+ return
148
+
149
+ try:
150
+ # 1. 创建原生自动重连连接
151
+ self._connection = await self._create_connection()
152
+
153
+ # 2. 初始化单通道
154
+ await self._init_single_channel()
155
+
156
+ # 3. 标记为已初始化(加锁保护)
157
+ async with self._lock:
158
+ self._initialized = True
159
+
160
+ logger.info("RabbitMQ单通道客户端初始化完成(原生自动重连/恢复已启用)")
161
+ except Exception as e:
162
+ logger.error(f"初始化失败: {str(e)}", exc_info=True)
163
+ await self.close() # 初始化失败直接关闭
164
+ raise
165
+
166
+ async def acquire_channel(self) -> Tuple[RobustChannel, AbstractRobustConnection]:
167
+ """获取单通道(返回 (通道, 连接) 元组,保持API兼容)"""
168
+ async with self._lock:
169
+ # 原子化状态校验
170
+ if self._is_shutdown:
171
+ raise RuntimeError("客户端已关闭,无法获取通道")
172
+ if not self._initialized:
173
+ raise RuntimeError("客户端未初始化,请先调用init_pools()")
174
+
175
+ # 检查并恢复通道
176
+ channel = await self._check_and_recover_channel()
177
+ return channel, self._connection # 单通道无需管理"使用中/空闲"状态
178
+
179
+ async def declare_queue(self, queue_name: str, **kwargs) -> AbstractQueue:
180
+ """声明队列(使用单通道)"""
181
+ channel, _ = await self.acquire_channel()
182
+ return await channel.declare_queue(queue_name, **kwargs)
183
+
184
+ async def declare_exchange(self, exchange_name: str, exchange_type: str = "direct", **kwargs) -> AbstractExchange:
185
+ """声明交换机(使用单通道)"""
186
+ channel, _ = await self.acquire_channel()
187
+ return await channel.declare_exchange(exchange_name, exchange_type, **kwargs)
188
+
189
+ async def publish_message(self, routing_key: str, message_body: bytes, exchange_name: str = "", **kwargs):
190
+ """发布消息(依赖原生自动重连/恢复)"""
191
+ channel, _ = await self.acquire_channel()
192
+ try:
193
+ exchange = channel.default_exchange if not exchange_name else await channel.get_exchange(exchange_name)
194
+ message = Message(body=message_body, **kwargs)
195
+ await exchange.publish(message, routing_key=routing_key)
196
+ logger.debug(
197
+ f"消息发布成功 - 交换机: {exchange.name}, 路由键: {routing_key}"
198
+ )
199
+ except Exception as e:
200
+ logger.error(f"发布消息失败: {str(e)}", exc_info=True)
201
+ raise # 原生会自动重连,无需手动处理
202
+
203
+ async def consume_queue(self, queue_name: str, callback: Callable[[AbstractMessage], asyncio.Future], auto_ack: bool = False, **kwargs):
204
+ """消费队列(独立通道,带原生自动恢复)"""
205
+ async with self._lock:
206
+ # 原子化状态校验
207
+ if self._is_shutdown:
208
+ raise RuntimeError("客户端已关闭,无法启动消费")
209
+ if not self._initialized:
210
+ raise RuntimeError("客户端未初始化,请先调用init_pools()")
211
+ if queue_name in self._consumer_channels:
212
+ logger.warning(f"队列 {queue_name} 已在消费中,无需重复启动")
213
+ return
214
+
215
+ # 先声明队列(确保队列存在)
216
+ await self.declare_queue(queue_name, **kwargs)
217
+
218
+ # 创建独立的消费者通道(不使用主单通道,避免消费阻塞发布)
219
+ async with self._lock:
220
+ if self._is_shutdown: # 二次校验:防止创建通道前客户端被关闭
221
+ raise RuntimeError("客户端已关闭,无法创建消费者通道")
222
+ if not self._connection or self._connection.is_closed:
223
+ raise RuntimeError("无有效连接,无法创建消费者通道")
224
+ channel = await self._connection.channel()
225
+ await channel.set_qos(prefetch_count=self.prefetch_count)
226
+
227
+ # 注册消费者通道
228
+ self._consumer_channels[queue_name] = (
229
+ channel, callback, auto_ack, kwargs)
230
+
231
+ async def consume_callback_wrapper(message: AbstractMessage):
232
+ """消费回调包装(处理通道失效,依赖原生恢复)"""
233
+ try:
234
+ async with self._lock:
235
+ # 原子化校验状态:客户端是否关闭 + 通道是否有效 + 连接是否有效
236
+ if self._is_shutdown:
237
+ logger.warning(f"客户端已关闭,拒绝处理消息(队列: {queue_name})")
238
+ if not auto_ack:
239
+ await message.nack(requeue=True)
240
+ return
241
+ channel_valid = not channel.is_closed
242
+ conn_valid = self._connection and not self._connection.is_closed
243
+
244
+ if not channel_valid or not conn_valid:
245
+ logger.warning(f"消费者通道 {queue_name} 失效(等待原生自动恢复)")
246
+ if not auto_ack:
247
+ await message.nack(requeue=True)
248
+ return
249
+
250
+ # 执行业务回调
251
+ await callback(message)
252
+ if not auto_ack:
253
+ await message.ack()
254
+ except ChannelClosed as e:
255
+ logger.error(f"消费者通道 {queue_name} 关闭: {str(e)}", exc_info=True)
256
+ if not auto_ack:
257
+ await message.nack(requeue=True)
258
+ except aiormq.exceptions.ChannelInvalidStateError as e:
259
+ logger.error(
260
+ f"消费者通道 {queue_name} 状态异常: {str(e)}", exc_info=True)
261
+ if not auto_ack:
262
+ await message.nack(requeue=True)
263
+ except Exception as e:
264
+ logger.error(
265
+ f"消费消息失败(队列: {queue_name}): {str(e)}", exc_info=True)
266
+ if not auto_ack:
267
+ await message.nack(requeue=True)
268
+
269
+ logger.info(f"开始消费队列: {queue_name}(通道带原生自动恢复)")
270
+
271
+ try:
272
+ await channel.basic_consume(
273
+ queue_name,
274
+ consumer_callback=consume_callback_wrapper,
275
+ auto_ack=auto_ack,
276
+ **kwargs
277
+ )
278
+ except Exception as e:
279
+ logger.error(f"启动消费失败(队列: {queue_name}): {str(e)}", exc_info=True)
280
+ # 清理异常资源
281
+ try:
282
+ async with self._lock:
283
+ if not channel.is_closed:
284
+ await channel.close()
285
+ # 移除无效的消费者通道注册
286
+ if queue_name in self._consumer_channels:
287
+ del self._consumer_channels[queue_name]
288
+ except Exception as close_e:
289
+ logger.warning(f"关闭消费者通道失败: {str(close_e)}")
290
+ raise
291
+
292
+ async def close(self):
293
+ """关闭客户端(释放所有资源,原子化状态管理)"""
294
+ async with self._lock:
295
+ if self._is_shutdown:
296
+ logger.warning("客户端已关闭,无需重复操作")
297
+ return
298
+ # 先标记为关闭,阻止后续所有操作(原子化修改)
299
+ self._is_shutdown = True
300
+ self._initialized = False
301
+
302
+ logger.info("开始关闭RabbitMQ单通道客户端(释放所有资源)...")
303
+
304
+ # 1. 关闭所有消费者通道
305
+ consumer_channels = []
306
+ async with self._lock:
307
+ consumer_channels = list(self._consumer_channels.values())
308
+ self._consumer_channels.clear()
309
+ for channel, _, _, _ in consumer_channels:
310
+ try:
311
+ if not channel.is_closed:
312
+ await channel.close()
313
+ except Exception as e:
314
+ logger.warning(f"关闭消费者通道失败: {str(e)}")
315
+
316
+ # 2. 关闭主单通道
317
+ if self._channel:
318
+ try:
319
+ async with self._lock:
320
+ if not self._channel.is_closed:
321
+ await self._channel.close()
322
+ except Exception as e:
323
+ logger.warning(f"关闭主通道失败: {str(e)}")
324
+ self._channel = None
325
+
326
+ # 3. 关闭连接(终止原生自动重连)
327
+ if self._connection:
328
+ try:
329
+ async with self._lock:
330
+ if not self._connection.is_closed:
331
+ await self._connection.close()
332
+ logger.info(
333
+ f"已关闭连接: {self._current_host}:{self.port}(终止原生自动重连)")
334
+ except Exception as e:
335
+ logger.warning(f"关闭连接失败: {str(e)}")
336
+ self._connection = None
337
+
338
+ logger.info("RabbitMQ单通道客户端已完全关闭")