crawlo 1.2.3__py3-none-any.whl → 1.2.5__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.
Potentially problematic release.
This version of crawlo might be problematic. Click here for more details.
- crawlo/__init__.py +61 -61
- crawlo/__version__.py +1 -1
- crawlo/cleaners/__init__.py +60 -60
- crawlo/cleaners/data_formatter.py +225 -225
- crawlo/cleaners/encoding_converter.py +125 -125
- crawlo/cleaners/text_cleaner.py +232 -232
- crawlo/cli.py +88 -81
- crawlo/commands/__init__.py +14 -14
- crawlo/commands/check.py +594 -594
- crawlo/commands/genspider.py +151 -151
- crawlo/commands/help.py +144 -142
- crawlo/commands/list.py +155 -155
- crawlo/commands/run.py +323 -292
- crawlo/commands/startproject.py +436 -417
- crawlo/commands/stats.py +187 -187
- crawlo/commands/utils.py +186 -186
- crawlo/config.py +312 -312
- crawlo/config_validator.py +251 -251
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +354 -354
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +143 -143
- crawlo/crawler.py +1110 -1027
- crawlo/data/__init__.py +5 -5
- crawlo/data/user_agents.py +107 -107
- crawlo/downloader/__init__.py +266 -266
- crawlo/downloader/aiohttp_downloader.py +220 -220
- crawlo/downloader/cffi_downloader.py +256 -256
- crawlo/downloader/httpx_downloader.py +259 -259
- crawlo/downloader/hybrid_downloader.py +212 -212
- crawlo/downloader/playwright_downloader.py +402 -402
- crawlo/downloader/selenium_downloader.py +472 -472
- crawlo/event.py +11 -11
- crawlo/exceptions.py +81 -81
- crawlo/extension/__init__.py +37 -37
- crawlo/extension/health_check.py +141 -141
- crawlo/extension/log_interval.py +57 -57
- crawlo/extension/log_stats.py +81 -81
- crawlo/extension/logging_extension.py +43 -43
- crawlo/extension/memory_monitor.py +104 -104
- crawlo/extension/performance_profiler.py +133 -133
- crawlo/extension/request_recorder.py +107 -107
- crawlo/filters/__init__.py +154 -154
- crawlo/filters/aioredis_filter.py +280 -280
- crawlo/filters/memory_filter.py +269 -269
- crawlo/items/__init__.py +23 -23
- crawlo/items/base.py +21 -21
- crawlo/items/fields.py +52 -52
- crawlo/items/items.py +104 -104
- crawlo/middleware/__init__.py +21 -21
- crawlo/middleware/default_header.py +131 -131
- crawlo/middleware/download_delay.py +104 -104
- crawlo/middleware/middleware_manager.py +135 -135
- crawlo/middleware/offsite.py +114 -114
- crawlo/middleware/proxy.py +367 -367
- crawlo/middleware/request_ignore.py +86 -86
- crawlo/middleware/response_code.py +163 -163
- crawlo/middleware/response_filter.py +136 -136
- crawlo/middleware/retry.py +124 -124
- crawlo/mode_manager.py +211 -211
- crawlo/network/__init__.py +21 -21
- crawlo/network/request.py +338 -338
- crawlo/network/response.py +359 -359
- crawlo/pipelines/__init__.py +21 -21
- crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +316 -316
- crawlo/pipelines/database_dedup_pipeline.py +222 -222
- crawlo/pipelines/json_pipeline.py +218 -218
- crawlo/pipelines/memory_dedup_pipeline.py +115 -115
- crawlo/pipelines/mongo_pipeline.py +131 -131
- crawlo/pipelines/mysql_pipeline.py +317 -317
- crawlo/pipelines/pipeline_manager.py +61 -61
- crawlo/pipelines/redis_dedup_pipeline.py +165 -165
- crawlo/project.py +279 -187
- crawlo/queue/pqueue.py +37 -37
- crawlo/queue/queue_manager.py +337 -337
- crawlo/queue/redis_priority_queue.py +298 -298
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +217 -226
- crawlo/settings/setting_manager.py +122 -122
- crawlo/spider/__init__.py +639 -639
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +129 -129
- crawlo/task_manager.py +30 -30
- crawlo/templates/crawlo.cfg.tmpl +10 -10
- crawlo/templates/project/__init__.py.tmpl +3 -3
- crawlo/templates/project/items.py.tmpl +17 -17
- crawlo/templates/project/middlewares.py.tmpl +118 -118
- crawlo/templates/project/pipelines.py.tmpl +96 -96
- crawlo/templates/project/settings.py.tmpl +324 -325
- crawlo/templates/project/settings_distributed.py.tmpl +154 -121
- crawlo/templates/project/settings_gentle.py.tmpl +127 -94
- crawlo/templates/project/settings_high_performance.py.tmpl +149 -151
- crawlo/templates/project/settings_simple.py.tmpl +102 -68
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/{project/run.py.tmpl → run.py.tmpl} +47 -45
- crawlo/templates/spider/spider.py.tmpl +143 -143
- crawlo/tools/__init__.py +182 -182
- crawlo/tools/anti_crawler.py +268 -268
- crawlo/tools/authenticated_proxy.py +240 -240
- crawlo/tools/data_validator.py +180 -180
- crawlo/tools/date_tools.py +35 -35
- crawlo/tools/distributed_coordinator.py +386 -386
- crawlo/tools/retry_mechanism.py +220 -220
- crawlo/tools/scenario_adapter.py +262 -262
- crawlo/utils/__init__.py +35 -35
- crawlo/utils/batch_processor.py +259 -259
- crawlo/utils/controlled_spider_mixin.py +439 -439
- crawlo/utils/date_tools.py +290 -290
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/enhanced_error_handler.py +356 -356
- crawlo/utils/env_config.py +105 -105
- crawlo/utils/error_handler.py +123 -123
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +286 -286
- crawlo/utils/large_scale_helper.py +344 -344
- crawlo/utils/log.py +128 -128
- crawlo/utils/performance_monitor.py +285 -285
- crawlo/utils/queue_helper.py +175 -175
- crawlo/utils/redis_connection_pool.py +334 -334
- crawlo/utils/redis_key_validator.py +198 -198
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +218 -218
- crawlo/utils/spider_loader.py +61 -61
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +4 -4
- crawlo/utils/url.py +39 -39
- {crawlo-1.2.3.dist-info → crawlo-1.2.5.dist-info}/METADATA +764 -692
- crawlo-1.2.5.dist-info/RECORD +206 -0
- examples/__init__.py +7 -7
- tests/DOUBLE_CRAWLO_PREFIX_FIX_REPORT.md +81 -81
- tests/__init__.py +7 -7
- tests/advanced_tools_example.py +275 -275
- tests/authenticated_proxy_example.py +236 -236
- tests/cleaners_example.py +160 -160
- tests/config_validation_demo.py +102 -102
- tests/controlled_spider_example.py +205 -205
- tests/date_tools_example.py +180 -180
- tests/dynamic_loading_example.py +523 -523
- tests/dynamic_loading_test.py +104 -104
- tests/env_config_example.py +133 -133
- tests/error_handling_example.py +171 -171
- tests/redis_key_validation_demo.py +130 -130
- tests/response_improvements_example.py +144 -144
- tests/test_advanced_tools.py +148 -148
- tests/test_all_redis_key_configs.py +145 -145
- tests/test_authenticated_proxy.py +141 -141
- tests/test_cleaners.py +54 -54
- tests/test_comprehensive.py +146 -146
- tests/test_config_validator.py +193 -193
- tests/test_crawlo_proxy_integration.py +172 -172
- tests/test_date_tools.py +123 -123
- tests/test_default_header_middleware.py +158 -158
- tests/test_double_crawlo_fix.py +207 -207
- tests/test_double_crawlo_fix_simple.py +124 -124
- tests/test_download_delay_middleware.py +221 -221
- tests/test_downloader_proxy_compatibility.py +268 -268
- tests/test_dynamic_downloaders_proxy.py +124 -124
- tests/test_dynamic_proxy.py +92 -92
- tests/test_dynamic_proxy_config.py +146 -146
- tests/test_dynamic_proxy_real.py +109 -109
- tests/test_edge_cases.py +303 -303
- tests/test_enhanced_error_handler.py +270 -270
- tests/test_env_config.py +121 -121
- tests/test_error_handler_compatibility.py +112 -112
- tests/test_final_validation.py +153 -153
- tests/test_framework_env_usage.py +103 -103
- tests/test_integration.py +356 -356
- tests/test_item_dedup_redis_key.py +122 -122
- tests/test_offsite_middleware.py +221 -221
- tests/test_parsel.py +29 -29
- tests/test_performance.py +327 -327
- tests/test_proxy_api.py +264 -264
- tests/test_proxy_health_check.py +32 -32
- tests/test_proxy_middleware.py +121 -121
- tests/test_proxy_middleware_enhanced.py +216 -216
- tests/test_proxy_middleware_integration.py +136 -136
- tests/test_proxy_providers.py +56 -56
- tests/test_proxy_stats.py +19 -19
- tests/test_proxy_strategies.py +59 -59
- tests/test_queue_manager_double_crawlo.py +173 -173
- tests/test_queue_manager_redis_key.py +176 -176
- tests/test_real_scenario_proxy.py +195 -195
- tests/test_redis_config.py +28 -28
- tests/test_redis_connection_pool.py +294 -294
- tests/test_redis_key_naming.py +181 -181
- tests/test_redis_key_validator.py +123 -123
- tests/test_redis_queue.py +224 -224
- tests/test_request_ignore_middleware.py +182 -182
- tests/test_request_serialization.py +70 -70
- tests/test_response_code_middleware.py +349 -349
- tests/test_response_filter_middleware.py +427 -427
- tests/test_response_improvements.py +152 -152
- tests/test_retry_middleware.py +241 -241
- tests/test_scheduler.py +241 -241
- tests/test_simple_response.py +61 -61
- tests/test_telecom_spider_redis_key.py +205 -205
- tests/test_template_content.py +87 -87
- tests/test_template_redis_key.py +134 -134
- tests/test_tools.py +153 -153
- tests/tools_example.py +257 -257
- crawlo-1.2.3.dist-info/RECORD +0 -222
- examples/aiohttp_settings.py +0 -42
- examples/curl_cffi_settings.py +0 -41
- examples/default_header_middleware_example.py +0 -107
- examples/default_header_spider_example.py +0 -129
- examples/download_delay_middleware_example.py +0 -160
- examples/httpx_settings.py +0 -42
- examples/multi_downloader_proxy_example.py +0 -81
- examples/offsite_middleware_example.py +0 -55
- examples/offsite_spider_example.py +0 -107
- examples/proxy_spider_example.py +0 -166
- examples/request_ignore_middleware_example.py +0 -51
- examples/request_ignore_spider_example.py +0 -99
- examples/response_code_middleware_example.py +0 -52
- examples/response_filter_middleware_example.py +0 -67
- examples/tong_hua_shun_settings.py +0 -62
- examples/tong_hua_shun_spider.py +0 -170
- {crawlo-1.2.3.dist-info → crawlo-1.2.5.dist-info}/WHEEL +0 -0
- {crawlo-1.2.3.dist-info → crawlo-1.2.5.dist-info}/entry_points.txt +0 -0
- {crawlo-1.2.3.dist-info → crawlo-1.2.5.dist-info}/top_level.txt +0 -0
crawlo/queue/queue_manager.py
CHANGED
|
@@ -1,338 +1,338 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding: UTF-8 -*-
|
|
3
|
-
"""
|
|
4
|
-
统一的队列管理器
|
|
5
|
-
提供简洁、一致的队列接口,自动处理不同队列类型的差异
|
|
6
|
-
"""
|
|
7
|
-
from typing import Optional, Dict, Any, Union
|
|
8
|
-
from enum import Enum
|
|
9
|
-
import asyncio
|
|
10
|
-
import traceback
|
|
11
|
-
import os
|
|
12
|
-
|
|
13
|
-
from crawlo.utils.log import get_logger
|
|
14
|
-
from crawlo.utils.request_serializer import RequestSerializer
|
|
15
|
-
from crawlo.utils.error_handler import ErrorHandler
|
|
16
|
-
from crawlo.queue.pqueue import SpiderPriorityQueue
|
|
17
|
-
from crawlo import Request
|
|
18
|
-
|
|
19
|
-
try:
|
|
20
|
-
from crawlo.queue.redis_priority_queue import RedisPriorityQueue
|
|
21
|
-
REDIS_AVAILABLE = True
|
|
22
|
-
except ImportError:
|
|
23
|
-
RedisPriorityQueue = None
|
|
24
|
-
REDIS_AVAILABLE = False
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class QueueType(Enum):
|
|
28
|
-
"""队列类型枚举"""
|
|
29
|
-
MEMORY = "memory"
|
|
30
|
-
REDIS = "redis"
|
|
31
|
-
AUTO = "auto" # 自动选择
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
class QueueConfig:
|
|
35
|
-
"""队列配置类"""
|
|
36
|
-
|
|
37
|
-
def __init__(
|
|
38
|
-
self,
|
|
39
|
-
queue_type: Union[QueueType, str] = QueueType.AUTO,
|
|
40
|
-
redis_url: Optional[str] = None,
|
|
41
|
-
redis_host: str = "127.0.0.1",
|
|
42
|
-
redis_port: int = 6379,
|
|
43
|
-
redis_password: Optional[str] = None,
|
|
44
|
-
redis_db: int = 0,
|
|
45
|
-
queue_name: str = "crawlo:requests",
|
|
46
|
-
max_queue_size: int = 1000,
|
|
47
|
-
max_retries: int = 3,
|
|
48
|
-
timeout: int = 300,
|
|
49
|
-
**kwargs
|
|
50
|
-
):
|
|
51
|
-
self.queue_type = QueueType(queue_type) if isinstance(queue_type, str) else queue_type
|
|
52
|
-
|
|
53
|
-
# Redis 配置
|
|
54
|
-
if redis_url:
|
|
55
|
-
self.redis_url = redis_url
|
|
56
|
-
else:
|
|
57
|
-
if redis_password:
|
|
58
|
-
self.redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
|
|
59
|
-
else:
|
|
60
|
-
self.redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
|
|
61
|
-
|
|
62
|
-
self.queue_name = queue_name
|
|
63
|
-
self.max_queue_size = max_queue_size
|
|
64
|
-
self.max_retries = max_retries
|
|
65
|
-
self.timeout = timeout
|
|
66
|
-
self.extra_config = kwargs
|
|
67
|
-
|
|
68
|
-
@classmethod
|
|
69
|
-
def from_settings(cls, settings) -> 'QueueConfig':
|
|
70
|
-
"""从 settings 创建配置"""
|
|
71
|
-
return cls(
|
|
72
|
-
queue_type=settings.get('QUEUE_TYPE', QueueType.AUTO),
|
|
73
|
-
redis_url=settings.get('REDIS_URL'),
|
|
74
|
-
redis_host=settings.get('REDIS_HOST', '127.0.0.1'),
|
|
75
|
-
redis_port=settings.get_int('REDIS_PORT', 6379),
|
|
76
|
-
redis_password=settings.get('REDIS_PASSWORD'),
|
|
77
|
-
redis_db=settings.get_int('REDIS_DB', 0),
|
|
78
|
-
queue_name=settings.get('SCHEDULER_QUEUE_NAME', 'crawlo:requests'),
|
|
79
|
-
max_queue_size=settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 1000),
|
|
80
|
-
max_retries=settings.get_int('QUEUE_MAX_RETRIES', 3),
|
|
81
|
-
timeout=settings.get_int('QUEUE_TIMEOUT', 300)
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
class QueueManager:
|
|
86
|
-
"""统一的队列管理器"""
|
|
87
|
-
|
|
88
|
-
def __init__(self, config: QueueConfig):
|
|
89
|
-
self.config = config
|
|
90
|
-
self.logger = get_logger(self.__class__.__name__)
|
|
91
|
-
self.error_handler = ErrorHandler(self.__class__.__name__)
|
|
92
|
-
self.request_serializer = RequestSerializer()
|
|
93
|
-
self._queue = None
|
|
94
|
-
self._queue_semaphore = None
|
|
95
|
-
self._queue_type = None
|
|
96
|
-
self._health_status = "unknown"
|
|
97
|
-
|
|
98
|
-
async def initialize(self) -> bool:
|
|
99
|
-
"""初始化队列"""
|
|
100
|
-
try:
|
|
101
|
-
queue_type = await self._determine_queue_type()
|
|
102
|
-
self._queue = await self._create_queue(queue_type)
|
|
103
|
-
self._queue_type = queue_type
|
|
104
|
-
|
|
105
|
-
# 测试队列健康状态
|
|
106
|
-
await self._health_check()
|
|
107
|
-
|
|
108
|
-
self.logger.info(f"✅ 队列初始化成功: {queue_type.value}")
|
|
109
|
-
self.logger.info(f"📊 队列配置: {self._get_queue_info()}")
|
|
110
|
-
return True
|
|
111
|
-
|
|
112
|
-
except Exception as e:
|
|
113
|
-
# 记录详细的错误信息和堆栈跟踪
|
|
114
|
-
self.logger.error(f"❌ 队列初始化失败: {e}")
|
|
115
|
-
self.logger.debug(f"详细错误信息:\n{traceback.format_exc()}")
|
|
116
|
-
self._health_status = "error"
|
|
117
|
-
return False
|
|
118
|
-
|
|
119
|
-
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
120
|
-
"""统一的入队接口"""
|
|
121
|
-
if not self._queue:
|
|
122
|
-
raise RuntimeError("队列未初始化")
|
|
123
|
-
|
|
124
|
-
try:
|
|
125
|
-
# 序列化处理(仅对 Redis 队列)
|
|
126
|
-
if self._queue_type == QueueType.REDIS:
|
|
127
|
-
request = self.request_serializer.prepare_for_serialization(request)
|
|
128
|
-
|
|
129
|
-
# 背压控制(仅对内存队列)
|
|
130
|
-
if self._queue_semaphore:
|
|
131
|
-
# 对于大量请求,使用非阻塞式检查
|
|
132
|
-
if not self._queue_semaphore.locked():
|
|
133
|
-
await self._queue_semaphore.acquire()
|
|
134
|
-
else:
|
|
135
|
-
# 如果队列已满,返回 False 而不是阻塞
|
|
136
|
-
self.logger.warning("队列已满,跳过当前请求")
|
|
137
|
-
return False
|
|
138
|
-
|
|
139
|
-
# 统一的入队操作
|
|
140
|
-
if hasattr(self._queue, 'put'):
|
|
141
|
-
if self._queue_type == QueueType.REDIS:
|
|
142
|
-
success = await self._queue.put(request, priority)
|
|
143
|
-
else:
|
|
144
|
-
await self._queue.put(request)
|
|
145
|
-
success = True
|
|
146
|
-
else:
|
|
147
|
-
raise RuntimeError(f"队列类型 {self._queue_type} 不支持 put 操作")
|
|
148
|
-
|
|
149
|
-
if success:
|
|
150
|
-
self.logger.debug(f"✅ 请求入队成功: {request.url}")
|
|
151
|
-
|
|
152
|
-
return success
|
|
153
|
-
|
|
154
|
-
except Exception as e:
|
|
155
|
-
self.logger.error(f"❌ 请求入队失败: {e}")
|
|
156
|
-
if self._queue_semaphore:
|
|
157
|
-
self._queue_semaphore.release()
|
|
158
|
-
return False
|
|
159
|
-
|
|
160
|
-
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
161
|
-
"""统一的出队接口"""
|
|
162
|
-
if not self._queue:
|
|
163
|
-
raise RuntimeError("队列未初始化")
|
|
164
|
-
|
|
165
|
-
try:
|
|
166
|
-
request = await self._queue.get(timeout=timeout)
|
|
167
|
-
|
|
168
|
-
# 释放信号量(仅对内存队列)
|
|
169
|
-
if self._queue_semaphore and request:
|
|
170
|
-
self._queue_semaphore.release()
|
|
171
|
-
|
|
172
|
-
# 反序列化处理(仅对 Redis 队列)
|
|
173
|
-
if request and self._queue_type == QueueType.REDIS:
|
|
174
|
-
# 这里需要 spider 实例,暂时返回原始请求
|
|
175
|
-
# 实际的 callback 恢复在 scheduler 中处理
|
|
176
|
-
pass
|
|
177
|
-
|
|
178
|
-
return request
|
|
179
|
-
|
|
180
|
-
except Exception as e:
|
|
181
|
-
self.logger.error(f"❌ 请求出队失败: {e}")
|
|
182
|
-
return None
|
|
183
|
-
|
|
184
|
-
async def size(self) -> int:
|
|
185
|
-
"""获取队列大小"""
|
|
186
|
-
if not self._queue:
|
|
187
|
-
return 0
|
|
188
|
-
|
|
189
|
-
try:
|
|
190
|
-
if hasattr(self._queue, 'qsize'):
|
|
191
|
-
if asyncio.iscoroutinefunction(self._queue.qsize):
|
|
192
|
-
return await self._queue.qsize()
|
|
193
|
-
else:
|
|
194
|
-
return self._queue.qsize()
|
|
195
|
-
return 0
|
|
196
|
-
except Exception as e:
|
|
197
|
-
self.logger.warning(f"获取队列大小失败: {e}")
|
|
198
|
-
return 0
|
|
199
|
-
|
|
200
|
-
def empty(self) -> bool:
|
|
201
|
-
"""检查队列是否为空(同步版本,用于兼容性)"""
|
|
202
|
-
try:
|
|
203
|
-
# 对于内存队列,可以同步检查
|
|
204
|
-
if self._queue_type == QueueType.MEMORY:
|
|
205
|
-
return self._queue.qsize() == 0
|
|
206
|
-
# 对于 Redis 队列,由于需要异步操作,这里返回近似值
|
|
207
|
-
# 为了确保程序能正常退出,我们返回True,让上层通过更精确的异步检查来判断
|
|
208
|
-
return True
|
|
209
|
-
except Exception:
|
|
210
|
-
return True
|
|
211
|
-
|
|
212
|
-
async def async_empty(self) -> bool:
|
|
213
|
-
"""检查队列是否为空(异步版本,更精确)"""
|
|
214
|
-
try:
|
|
215
|
-
# 对于内存队列
|
|
216
|
-
if self._queue_type == QueueType.MEMORY:
|
|
217
|
-
return self._queue.qsize() == 0
|
|
218
|
-
# 对于 Redis 队列,使用异步检查
|
|
219
|
-
elif self._queue_type == QueueType.REDIS:
|
|
220
|
-
size = await self.size()
|
|
221
|
-
return size == 0
|
|
222
|
-
return True
|
|
223
|
-
except Exception:
|
|
224
|
-
return True
|
|
225
|
-
|
|
226
|
-
async def close(self) -> None:
|
|
227
|
-
"""关闭队列"""
|
|
228
|
-
if self._queue and hasattr(self._queue, 'close'):
|
|
229
|
-
try:
|
|
230
|
-
await self._queue.close()
|
|
231
|
-
self.logger.info("✅ 队列已关闭")
|
|
232
|
-
except Exception as e:
|
|
233
|
-
self.logger.warning(f"关闭队列时发生错误: {e}")
|
|
234
|
-
|
|
235
|
-
def get_status(self) -> Dict[str, Any]:
|
|
236
|
-
"""获取队列状态信息"""
|
|
237
|
-
return {
|
|
238
|
-
"type": self._queue_type.value if self._queue_type else "unknown",
|
|
239
|
-
"health": self._health_status,
|
|
240
|
-
"config": self._get_queue_info(),
|
|
241
|
-
"initialized": self._queue is not None
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async def _determine_queue_type(self) -> QueueType:
|
|
245
|
-
"""确定队列类型"""
|
|
246
|
-
if self.config.queue_type == QueueType.AUTO:
|
|
247
|
-
# 自动选择:优先使用 Redis(如果可用)
|
|
248
|
-
if REDIS_AVAILABLE and self.config.redis_url:
|
|
249
|
-
# 测试 Redis 连接
|
|
250
|
-
try:
|
|
251
|
-
test_queue = RedisPriorityQueue(self.config.redis_url)
|
|
252
|
-
await test_queue.connect()
|
|
253
|
-
await test_queue.close()
|
|
254
|
-
self.logger.info("🔍 自动检测: Redis 可用,使用分布式队列")
|
|
255
|
-
return QueueType.REDIS
|
|
256
|
-
except Exception as e:
|
|
257
|
-
self.logger.warning(f"🔍 自动检测: Redis 不可用 ({e}),使用内存队列")
|
|
258
|
-
return QueueType.MEMORY
|
|
259
|
-
else:
|
|
260
|
-
self.logger.info("🔍 自动检测: Redis 未配置,使用内存队列")
|
|
261
|
-
return QueueType.MEMORY
|
|
262
|
-
|
|
263
|
-
elif self.config.queue_type == QueueType.REDIS:
|
|
264
|
-
if not REDIS_AVAILABLE:
|
|
265
|
-
raise RuntimeError("Redis 队列不可用:未安装 redis 依赖")
|
|
266
|
-
if not self.config.redis_url:
|
|
267
|
-
raise RuntimeError("Redis 队列不可用:未配置 REDIS_URL")
|
|
268
|
-
return QueueType.REDIS
|
|
269
|
-
|
|
270
|
-
elif self.config.queue_type == QueueType.MEMORY:
|
|
271
|
-
return QueueType.MEMORY
|
|
272
|
-
|
|
273
|
-
else:
|
|
274
|
-
raise ValueError(f"不支持的队列类型: {self.config.queue_type}")
|
|
275
|
-
|
|
276
|
-
async def _create_queue(self, queue_type: QueueType):
|
|
277
|
-
"""创建队列实例"""
|
|
278
|
-
if queue_type == QueueType.REDIS:
|
|
279
|
-
# 简化项目名称提取逻辑
|
|
280
|
-
project_name = "default"
|
|
281
|
-
if ':' in self.config.queue_name:
|
|
282
|
-
parts = self.config.queue_name.split(':')
|
|
283
|
-
# 跳过所有"crawlo"前缀,取第一个非"crawlo"部分作为项目名称
|
|
284
|
-
for part in parts:
|
|
285
|
-
if part != "crawlo":
|
|
286
|
-
project_name = part
|
|
287
|
-
break
|
|
288
|
-
else:
|
|
289
|
-
project_name = self.config.queue_name or "default"
|
|
290
|
-
|
|
291
|
-
queue = RedisPriorityQueue(
|
|
292
|
-
redis_url=self.config.redis_url,
|
|
293
|
-
queue_name=self.config.queue_name,
|
|
294
|
-
max_retries=self.config.max_retries,
|
|
295
|
-
timeout=self.config.timeout,
|
|
296
|
-
module_name=project_name # 传递项目名称作为module_name
|
|
297
|
-
)
|
|
298
|
-
# 不需要立即连接,使用 lazy connect
|
|
299
|
-
return queue
|
|
300
|
-
|
|
301
|
-
elif queue_type == QueueType.MEMORY:
|
|
302
|
-
queue = SpiderPriorityQueue()
|
|
303
|
-
# 为内存队列设置背压控制
|
|
304
|
-
self._queue_semaphore = asyncio.Semaphore(self.config.max_queue_size)
|
|
305
|
-
return queue
|
|
306
|
-
|
|
307
|
-
else:
|
|
308
|
-
raise ValueError(f"不支持的队列类型: {queue_type}")
|
|
309
|
-
|
|
310
|
-
async def _health_check(self) -> None:
|
|
311
|
-
"""健康检查"""
|
|
312
|
-
try:
|
|
313
|
-
if self._queue_type == QueueType.REDIS:
|
|
314
|
-
# 测试 Redis 连接
|
|
315
|
-
await self._queue.connect()
|
|
316
|
-
self._health_status = "healthy"
|
|
317
|
-
else:
|
|
318
|
-
# 内存队列总是健康的
|
|
319
|
-
self._health_status = "healthy"
|
|
320
|
-
except Exception as e:
|
|
321
|
-
self.logger.warning(f"队列健康检查失败: {e}")
|
|
322
|
-
self._health_status = "unhealthy"
|
|
323
|
-
|
|
324
|
-
def _get_queue_info(self) -> Dict[str, Any]:
|
|
325
|
-
"""获取队列配置信息"""
|
|
326
|
-
info = {
|
|
327
|
-
"queue_name": self.config.queue_name,
|
|
328
|
-
"max_queue_size": self.config.max_queue_size
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
if self._queue_type == QueueType.REDIS:
|
|
332
|
-
info.update({
|
|
333
|
-
"redis_url": self.config.redis_url,
|
|
334
|
-
"max_retries": self.config.max_retries,
|
|
335
|
-
"timeout": self.config.timeout
|
|
336
|
-
})
|
|
337
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
统一的队列管理器
|
|
5
|
+
提供简洁、一致的队列接口,自动处理不同队列类型的差异
|
|
6
|
+
"""
|
|
7
|
+
from typing import Optional, Dict, Any, Union
|
|
8
|
+
from enum import Enum
|
|
9
|
+
import asyncio
|
|
10
|
+
import traceback
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
from crawlo.utils.log import get_logger
|
|
14
|
+
from crawlo.utils.request_serializer import RequestSerializer
|
|
15
|
+
from crawlo.utils.error_handler import ErrorHandler
|
|
16
|
+
from crawlo.queue.pqueue import SpiderPriorityQueue
|
|
17
|
+
from crawlo import Request
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from crawlo.queue.redis_priority_queue import RedisPriorityQueue
|
|
21
|
+
REDIS_AVAILABLE = True
|
|
22
|
+
except ImportError:
|
|
23
|
+
RedisPriorityQueue = None
|
|
24
|
+
REDIS_AVAILABLE = False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class QueueType(Enum):
|
|
28
|
+
"""队列类型枚举"""
|
|
29
|
+
MEMORY = "memory"
|
|
30
|
+
REDIS = "redis"
|
|
31
|
+
AUTO = "auto" # 自动选择
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class QueueConfig:
|
|
35
|
+
"""队列配置类"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
queue_type: Union[QueueType, str] = QueueType.AUTO,
|
|
40
|
+
redis_url: Optional[str] = None,
|
|
41
|
+
redis_host: str = "127.0.0.1",
|
|
42
|
+
redis_port: int = 6379,
|
|
43
|
+
redis_password: Optional[str] = None,
|
|
44
|
+
redis_db: int = 0,
|
|
45
|
+
queue_name: str = "crawlo:requests",
|
|
46
|
+
max_queue_size: int = 1000,
|
|
47
|
+
max_retries: int = 3,
|
|
48
|
+
timeout: int = 300,
|
|
49
|
+
**kwargs
|
|
50
|
+
):
|
|
51
|
+
self.queue_type = QueueType(queue_type) if isinstance(queue_type, str) else queue_type
|
|
52
|
+
|
|
53
|
+
# Redis 配置
|
|
54
|
+
if redis_url:
|
|
55
|
+
self.redis_url = redis_url
|
|
56
|
+
else:
|
|
57
|
+
if redis_password:
|
|
58
|
+
self.redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
|
|
59
|
+
else:
|
|
60
|
+
self.redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
|
|
61
|
+
|
|
62
|
+
self.queue_name = queue_name
|
|
63
|
+
self.max_queue_size = max_queue_size
|
|
64
|
+
self.max_retries = max_retries
|
|
65
|
+
self.timeout = timeout
|
|
66
|
+
self.extra_config = kwargs
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_settings(cls, settings) -> 'QueueConfig':
|
|
70
|
+
"""从 settings 创建配置"""
|
|
71
|
+
return cls(
|
|
72
|
+
queue_type=settings.get('QUEUE_TYPE', QueueType.AUTO),
|
|
73
|
+
redis_url=settings.get('REDIS_URL'),
|
|
74
|
+
redis_host=settings.get('REDIS_HOST', '127.0.0.1'),
|
|
75
|
+
redis_port=settings.get_int('REDIS_PORT', 6379),
|
|
76
|
+
redis_password=settings.get('REDIS_PASSWORD'),
|
|
77
|
+
redis_db=settings.get_int('REDIS_DB', 0),
|
|
78
|
+
queue_name=settings.get('SCHEDULER_QUEUE_NAME', 'crawlo:requests'),
|
|
79
|
+
max_queue_size=settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 1000),
|
|
80
|
+
max_retries=settings.get_int('QUEUE_MAX_RETRIES', 3),
|
|
81
|
+
timeout=settings.get_int('QUEUE_TIMEOUT', 300)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class QueueManager:
|
|
86
|
+
"""统一的队列管理器"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, config: QueueConfig):
|
|
89
|
+
self.config = config
|
|
90
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
91
|
+
self.error_handler = ErrorHandler(self.__class__.__name__)
|
|
92
|
+
self.request_serializer = RequestSerializer()
|
|
93
|
+
self._queue = None
|
|
94
|
+
self._queue_semaphore = None
|
|
95
|
+
self._queue_type = None
|
|
96
|
+
self._health_status = "unknown"
|
|
97
|
+
|
|
98
|
+
async def initialize(self) -> bool:
|
|
99
|
+
"""初始化队列"""
|
|
100
|
+
try:
|
|
101
|
+
queue_type = await self._determine_queue_type()
|
|
102
|
+
self._queue = await self._create_queue(queue_type)
|
|
103
|
+
self._queue_type = queue_type
|
|
104
|
+
|
|
105
|
+
# 测试队列健康状态
|
|
106
|
+
await self._health_check()
|
|
107
|
+
|
|
108
|
+
self.logger.info(f"✅ 队列初始化成功: {queue_type.value}")
|
|
109
|
+
self.logger.info(f"📊 队列配置: {self._get_queue_info()}")
|
|
110
|
+
return True
|
|
111
|
+
|
|
112
|
+
except Exception as e:
|
|
113
|
+
# 记录详细的错误信息和堆栈跟踪
|
|
114
|
+
self.logger.error(f"❌ 队列初始化失败: {e}")
|
|
115
|
+
self.logger.debug(f"详细错误信息:\n{traceback.format_exc()}")
|
|
116
|
+
self._health_status = "error"
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
120
|
+
"""统一的入队接口"""
|
|
121
|
+
if not self._queue:
|
|
122
|
+
raise RuntimeError("队列未初始化")
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
# 序列化处理(仅对 Redis 队列)
|
|
126
|
+
if self._queue_type == QueueType.REDIS:
|
|
127
|
+
request = self.request_serializer.prepare_for_serialization(request)
|
|
128
|
+
|
|
129
|
+
# 背压控制(仅对内存队列)
|
|
130
|
+
if self._queue_semaphore:
|
|
131
|
+
# 对于大量请求,使用非阻塞式检查
|
|
132
|
+
if not self._queue_semaphore.locked():
|
|
133
|
+
await self._queue_semaphore.acquire()
|
|
134
|
+
else:
|
|
135
|
+
# 如果队列已满,返回 False 而不是阻塞
|
|
136
|
+
self.logger.warning("队列已满,跳过当前请求")
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
# 统一的入队操作
|
|
140
|
+
if hasattr(self._queue, 'put'):
|
|
141
|
+
if self._queue_type == QueueType.REDIS:
|
|
142
|
+
success = await self._queue.put(request, priority)
|
|
143
|
+
else:
|
|
144
|
+
await self._queue.put(request)
|
|
145
|
+
success = True
|
|
146
|
+
else:
|
|
147
|
+
raise RuntimeError(f"队列类型 {self._queue_type} 不支持 put 操作")
|
|
148
|
+
|
|
149
|
+
if success:
|
|
150
|
+
self.logger.debug(f"✅ 请求入队成功: {request.url}")
|
|
151
|
+
|
|
152
|
+
return success
|
|
153
|
+
|
|
154
|
+
except Exception as e:
|
|
155
|
+
self.logger.error(f"❌ 请求入队失败: {e}")
|
|
156
|
+
if self._queue_semaphore:
|
|
157
|
+
self._queue_semaphore.release()
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
161
|
+
"""统一的出队接口"""
|
|
162
|
+
if not self._queue:
|
|
163
|
+
raise RuntimeError("队列未初始化")
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
request = await self._queue.get(timeout=timeout)
|
|
167
|
+
|
|
168
|
+
# 释放信号量(仅对内存队列)
|
|
169
|
+
if self._queue_semaphore and request:
|
|
170
|
+
self._queue_semaphore.release()
|
|
171
|
+
|
|
172
|
+
# 反序列化处理(仅对 Redis 队列)
|
|
173
|
+
if request and self._queue_type == QueueType.REDIS:
|
|
174
|
+
# 这里需要 spider 实例,暂时返回原始请求
|
|
175
|
+
# 实际的 callback 恢复在 scheduler 中处理
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
return request
|
|
179
|
+
|
|
180
|
+
except Exception as e:
|
|
181
|
+
self.logger.error(f"❌ 请求出队失败: {e}")
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
async def size(self) -> int:
|
|
185
|
+
"""获取队列大小"""
|
|
186
|
+
if not self._queue:
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
try:
|
|
190
|
+
if hasattr(self._queue, 'qsize'):
|
|
191
|
+
if asyncio.iscoroutinefunction(self._queue.qsize):
|
|
192
|
+
return await self._queue.qsize()
|
|
193
|
+
else:
|
|
194
|
+
return self._queue.qsize()
|
|
195
|
+
return 0
|
|
196
|
+
except Exception as e:
|
|
197
|
+
self.logger.warning(f"获取队列大小失败: {e}")
|
|
198
|
+
return 0
|
|
199
|
+
|
|
200
|
+
def empty(self) -> bool:
|
|
201
|
+
"""检查队列是否为空(同步版本,用于兼容性)"""
|
|
202
|
+
try:
|
|
203
|
+
# 对于内存队列,可以同步检查
|
|
204
|
+
if self._queue_type == QueueType.MEMORY:
|
|
205
|
+
return self._queue.qsize() == 0
|
|
206
|
+
# 对于 Redis 队列,由于需要异步操作,这里返回近似值
|
|
207
|
+
# 为了确保程序能正常退出,我们返回True,让上层通过更精确的异步检查来判断
|
|
208
|
+
return True
|
|
209
|
+
except Exception:
|
|
210
|
+
return True
|
|
211
|
+
|
|
212
|
+
async def async_empty(self) -> bool:
|
|
213
|
+
"""检查队列是否为空(异步版本,更精确)"""
|
|
214
|
+
try:
|
|
215
|
+
# 对于内存队列
|
|
216
|
+
if self._queue_type == QueueType.MEMORY:
|
|
217
|
+
return self._queue.qsize() == 0
|
|
218
|
+
# 对于 Redis 队列,使用异步检查
|
|
219
|
+
elif self._queue_type == QueueType.REDIS:
|
|
220
|
+
size = await self.size()
|
|
221
|
+
return size == 0
|
|
222
|
+
return True
|
|
223
|
+
except Exception:
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
async def close(self) -> None:
|
|
227
|
+
"""关闭队列"""
|
|
228
|
+
if self._queue and hasattr(self._queue, 'close'):
|
|
229
|
+
try:
|
|
230
|
+
await self._queue.close()
|
|
231
|
+
self.logger.info("✅ 队列已关闭")
|
|
232
|
+
except Exception as e:
|
|
233
|
+
self.logger.warning(f"关闭队列时发生错误: {e}")
|
|
234
|
+
|
|
235
|
+
def get_status(self) -> Dict[str, Any]:
|
|
236
|
+
"""获取队列状态信息"""
|
|
237
|
+
return {
|
|
238
|
+
"type": self._queue_type.value if self._queue_type else "unknown",
|
|
239
|
+
"health": self._health_status,
|
|
240
|
+
"config": self._get_queue_info(),
|
|
241
|
+
"initialized": self._queue is not None
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async def _determine_queue_type(self) -> QueueType:
|
|
245
|
+
"""确定队列类型"""
|
|
246
|
+
if self.config.queue_type == QueueType.AUTO:
|
|
247
|
+
# 自动选择:优先使用 Redis(如果可用)
|
|
248
|
+
if REDIS_AVAILABLE and self.config.redis_url:
|
|
249
|
+
# 测试 Redis 连接
|
|
250
|
+
try:
|
|
251
|
+
test_queue = RedisPriorityQueue(self.config.redis_url)
|
|
252
|
+
await test_queue.connect()
|
|
253
|
+
await test_queue.close()
|
|
254
|
+
self.logger.info("🔍 自动检测: Redis 可用,使用分布式队列")
|
|
255
|
+
return QueueType.REDIS
|
|
256
|
+
except Exception as e:
|
|
257
|
+
self.logger.warning(f"🔍 自动检测: Redis 不可用 ({e}),使用内存队列")
|
|
258
|
+
return QueueType.MEMORY
|
|
259
|
+
else:
|
|
260
|
+
self.logger.info("🔍 自动检测: Redis 未配置,使用内存队列")
|
|
261
|
+
return QueueType.MEMORY
|
|
262
|
+
|
|
263
|
+
elif self.config.queue_type == QueueType.REDIS:
|
|
264
|
+
if not REDIS_AVAILABLE:
|
|
265
|
+
raise RuntimeError("Redis 队列不可用:未安装 redis 依赖")
|
|
266
|
+
if not self.config.redis_url:
|
|
267
|
+
raise RuntimeError("Redis 队列不可用:未配置 REDIS_URL")
|
|
268
|
+
return QueueType.REDIS
|
|
269
|
+
|
|
270
|
+
elif self.config.queue_type == QueueType.MEMORY:
|
|
271
|
+
return QueueType.MEMORY
|
|
272
|
+
|
|
273
|
+
else:
|
|
274
|
+
raise ValueError(f"不支持的队列类型: {self.config.queue_type}")
|
|
275
|
+
|
|
276
|
+
async def _create_queue(self, queue_type: QueueType):
|
|
277
|
+
"""创建队列实例"""
|
|
278
|
+
if queue_type == QueueType.REDIS:
|
|
279
|
+
# 简化项目名称提取逻辑
|
|
280
|
+
project_name = "default"
|
|
281
|
+
if ':' in self.config.queue_name:
|
|
282
|
+
parts = self.config.queue_name.split(':')
|
|
283
|
+
# 跳过所有"crawlo"前缀,取第一个非"crawlo"部分作为项目名称
|
|
284
|
+
for part in parts:
|
|
285
|
+
if part != "crawlo":
|
|
286
|
+
project_name = part
|
|
287
|
+
break
|
|
288
|
+
else:
|
|
289
|
+
project_name = self.config.queue_name or "default"
|
|
290
|
+
|
|
291
|
+
queue = RedisPriorityQueue(
|
|
292
|
+
redis_url=self.config.redis_url,
|
|
293
|
+
queue_name=self.config.queue_name,
|
|
294
|
+
max_retries=self.config.max_retries,
|
|
295
|
+
timeout=self.config.timeout,
|
|
296
|
+
module_name=project_name # 传递项目名称作为module_name
|
|
297
|
+
)
|
|
298
|
+
# 不需要立即连接,使用 lazy connect
|
|
299
|
+
return queue
|
|
300
|
+
|
|
301
|
+
elif queue_type == QueueType.MEMORY:
|
|
302
|
+
queue = SpiderPriorityQueue()
|
|
303
|
+
# 为内存队列设置背压控制
|
|
304
|
+
self._queue_semaphore = asyncio.Semaphore(self.config.max_queue_size)
|
|
305
|
+
return queue
|
|
306
|
+
|
|
307
|
+
else:
|
|
308
|
+
raise ValueError(f"不支持的队列类型: {queue_type}")
|
|
309
|
+
|
|
310
|
+
async def _health_check(self) -> None:
|
|
311
|
+
"""健康检查"""
|
|
312
|
+
try:
|
|
313
|
+
if self._queue_type == QueueType.REDIS:
|
|
314
|
+
# 测试 Redis 连接
|
|
315
|
+
await self._queue.connect()
|
|
316
|
+
self._health_status = "healthy"
|
|
317
|
+
else:
|
|
318
|
+
# 内存队列总是健康的
|
|
319
|
+
self._health_status = "healthy"
|
|
320
|
+
except Exception as e:
|
|
321
|
+
self.logger.warning(f"队列健康检查失败: {e}")
|
|
322
|
+
self._health_status = "unhealthy"
|
|
323
|
+
|
|
324
|
+
def _get_queue_info(self) -> Dict[str, Any]:
|
|
325
|
+
"""获取队列配置信息"""
|
|
326
|
+
info = {
|
|
327
|
+
"queue_name": self.config.queue_name,
|
|
328
|
+
"max_queue_size": self.config.max_queue_size
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if self._queue_type == QueueType.REDIS:
|
|
332
|
+
info.update({
|
|
333
|
+
"redis_url": self.config.redis_url,
|
|
334
|
+
"max_retries": self.config.max_retries,
|
|
335
|
+
"timeout": self.config.timeout
|
|
336
|
+
})
|
|
337
|
+
|
|
338
338
|
return info
|