# Generated by scripts/build_single_file.py; edit source_sections for repository changes. # ================ imports ================ #!/usr/bin/env python3 """Ctrip flight collector — standalone source distribution. Python 3.12+. Install the exact supported runtime (no repository required): python -m pip install camoufox==0.5.8 playwright==1.60.0 fpgen==1.3.0 filelock==4.2.6 psutil==7.2.2 tzdata==2026.6 python -m camoufox fetch official/152.0.4-beta.29 python -c "from camoufox.fpgen_model import ensure_fpgen_model; ensure_fpgen_model()" python ctrip_flights_scraper.py --help Authentication files contain private session data. Do not publish the data directory. Generated from source_sections; all application code is contained in this file. """ from __future__ import annotations import argparse import asyncio import contextlib import copy import csv import hashlib import importlib.metadata import importlib.util import io import json import logging import logging.handlers import math import multiprocessing import os import platform import queue import random import re import shutil import signal import sys import threading import time import traceback import uuid from dataclasses import dataclass, field from datetime import date, datetime, timedelta, timezone from decimal import Decimal, InvalidOperation from pathlib import Path from urllib.parse import urlparse, urlencode from zoneinfo import ZoneInfo SCHEMA_VERSION = 1 VERSION = '4.1.2' BROWSER_BUILD = 'official/152.0.4-beta.29' RUNTIME_REQUIREMENTS = { 'camoufox': '0.5.8', 'playwright': '1.60.0', 'fpgen': '1.3.0', 'filelock': '4.2.6', 'psutil': '7.2.2', 'tzdata': '2026.6', } DIAGNOSTIC_MAX_BYTES = 8192 class CrawlerError(Exception): """A boundary failure with an actionable, stable category.""" def __init__(self, code, message, *, retry_after=None, diagnostic=None): super().__init__(message) self.code = code self.retry_after = retry_after self.diagnostic = dict(diagnostic or {}) def utc_now(): return datetime.now(timezone.utc).isoformat() def parse_utc(value): value = datetime.fromisoformat(value.replace('Z', '+00:00')) if value.tzinfo is None: raise CrawlerError('state_invalid', '时间戳必须包含时区') return value.astimezone(timezone.utc) def stable_hash(value): return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8')).hexdigest() def _diagnostic_secrets(config, command): values = set() def visit(value): if isinstance(value, dict): for key, item in value.items(): if key in ('username', 'password', 'token', 'access_token', 'refresh_token', 'cookie', 'authorization'): if isinstance(item, str) and item: values.add(item) elif isinstance(item, (dict, list, tuple)): visit(item) elif isinstance(value, (list, tuple)): for item in value: visit(item) visit(config) visit(command) return sorted(values, key=len, reverse=True) def _diagnostic_text(value, secrets, limit=1024): text = str(value) def origin(match): try: parsed = urlparse(match.group()) host = parsed.hostname if not host: return '[url omitted]' port = ':' + str(parsed.port) if parsed.port is not None else '' return '[url ' + parsed.scheme + '://' + host + port + ']' except ValueError: return '[url omitted]' text = re.sub(r'(?i)\b[a-z][a-z0-9+.-]*://[^\s<>"\']+', origin, text) for secret in secrets: text = text.replace(secret, '[redacted]') escaped = json.dumps(secret, ensure_ascii=False)[1:-1] if escaped != secret: text = text.replace(escaped, '[redacted]') text = re.sub(r'(?im)\b(?:authorization|cookie|set-cookie)\s*:[^\r\n]*', '[private header omitted]', text) text = re.sub(r'(?i)\b(?:password|passwd|pwd|username|account|token|secret)\s*[:=]\s*(?:"[^"\r\n]*"|\'[^\'\r\n]*\'|[^\s,;]+)', '[private value omitted]', text) text = re.sub(r'(?is)\b(?:payload|response|body)\s*[:=]\s*[\[{].*', '[structured data omitted]', text) text = re.sub(r'(?s)\{.*(?:\}|$)', '[structured data omitted]', text) text = re.sub(r'(["\'])(?:[A-Za-z]:[\\/]|\\\\|/).*?\1', '[path omitted]', text) text = re.sub(r'(?]*|(?]+)|\\\\[^\s"\'<>]+', '[path omitted]', text) return ' '.join(text.split())[:limit] def safe_message(error, config=None, command=None): """Keep the useful failure text while removing private inputs and paths.""" return _diagnostic_text(error, _diagnostic_secrets(config, command)) def firefox_error_code(error): """Read Firefox's error symbol, never infer it from prose or a URL.""" first_line = str(error).split('\n', 1)[0] match = re.match(r'^\s*(?:[A-Za-z_][A-Za-z0-9_.]*:\s*)?(NS_ERROR_[A-Z0-9_]{1,64})(?:\s|$)', first_line) return match.group(1) if match else None def make_diagnostic(error, *, stage=None, config=None, command=None): """One bounded diagnostic schema for local errors and worker failures.""" secrets = _diagnostic_secrets(config, command) supplied = getattr(error, 'diagnostic', {}) or {} name = supplied.get('exception_type', type(error).__name__) if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,79}', name): name = type(error).__name__ result = {'exception_type': name, 'message': _diagnostic_text(supplied.get('message', str(error)), secrets), 'stage': _diagnostic_text(supplied.get('stage') or stage or 'unknown', secrets, 80), 'frames': []} frames = supplied.get('frames') if not isinstance(frames, list): frames = [{'file': frame.filename, 'line': frame.lineno, 'function': frame.name} for frame in traceback.extract_tb(error.__traceback__, limit=8)] for frame in frames[-8:]: if isinstance(frame, dict) and type(frame.get('line')) is int: filename = str(frame.get('file', '')).replace('\\', '/').rsplit('/', 1)[-1] result['frames'].append({'file': _diagnostic_text(filename, secrets, 120), 'line': frame['line'], 'function': _diagnostic_text(frame.get('function', ''), secrets, 120)}) protocol = supplied.get('protocol') if isinstance(protocol, dict): summary = {} for key in ('http_status', 'business_status', 'list_count'): value = protocol.get(key) if value is None or (type(value) is int and abs(value) < 10 ** 12): if key in protocol: summary[key] = value for key in ('finished', 'list_present', 'known_snapshot', 'request_matches', 'transaction_present', 'transaction_matches', 'search_id_present', 'search_id_matches'): if key in protocol and (protocol[key] is None or type(protocol[key]) is bool): summary[key] = protocol[key] for key in ('finished_type', 'list_type'): if protocol.get(key) in ('missing', 'NoneType', 'bool', 'dict', 'list', 'int', 'str', 'float'): summary[key] = protocol[key] result['protocol'] = summary network = supplied.get('network') network = network if isinstance(network, dict) else {} summary = {} symbol = network.get('browser_error_code') or firefox_error_code(error) if isinstance(symbol, str) and firefox_error_code(symbol) == symbol: summary['browser_error_code'] = _diagnostic_text(symbol, secrets, 80) if network.get('response_kind') in ('navigation', 'search', 'comfort', 'resolve', 'auth'): summary['response_kind'] = network['response_kind'] if network.get('method') in ('GET', 'POST'): summary['method'] = network['method'] for key in ('http_status', 'failed_request_count', 'search_responses_received'): value = network.get(key) if type(value) is int and 0 <= value < 10 ** 12: summary[key] = value elif key == 'http_status' and key in network and value is None: summary[key] = None for key in ('request_failed', 'response_body_failed', 'response_request_failed'): if type(network.get(key)) is bool: summary[key] = network[key] response_symbol = network.get('response_request_error_code') if isinstance(response_symbol, str) and firefox_error_code(response_symbol) == response_symbol: summary['response_request_error_code'] = response_symbol if summary: result['network'] = summary causes = [] if isinstance(supplied.get('causes'), list): for cause in supplied['causes'][:3]: if (isinstance(cause, dict) and isinstance(cause.get('exception_type'), str) and re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,79}', cause['exception_type'])): causes.append({'exception_type': cause['exception_type'], 'message': _diagnostic_text(cause.get('message', ''), secrets, 256)}) else: cause = error.__cause__ while cause is not None and len(causes) < 3: causes.append({'exception_type': type(cause).__name__, 'message': _diagnostic_text(cause, secrets, 256)}) cause = cause.__cause__ if causes: result['causes'] = causes while len(json.dumps(result, ensure_ascii=False).encode('utf-8')) > DIAGNOSTIC_MAX_BYTES: result['truncated'] = True if result['frames']: result['frames'].pop(0) elif result.get('causes'): result['causes'].pop() else: result['message'] = result['message'][:len(result['message']) // 2] return result # ================ config ================ # Edit this block when using the downloaded standalone script. DEFAULT_CONFIG = { 'crawl_citys': ['上海', '香港', '东京'], 'begin_date': None, 'end_date': None, 'start_interval': 1, 'crawl_days': 60, 'days_interval': 1, 'direct_flight': True, 'comft_flight': False, 'rename_col': True, 'login_allowed': True, 'accounts': [], # {'alias': 'account_1', 'username': '你的账号', 'password': '你的密码', 'enabled': True} 'challenge_policy': 'switch', # switch or wait_then_switch 'headless': True, 'proxy': None, # {'server': 'socks5://host:port', 'username': '...', 'password': '...'} 'output': None, # defaults to ./data next to this file 'timezone': 'Asia/Shanghai', 'browser_build': BROWSER_BUILD, 'action_timeout': 10.0, 'navigation_timeout': 30.0, 'attempt_timeout': 90.0, 'comfort_timeout': 15.0, 'task_budget': 300.0, 'auto_recovery_rounds': 12, # finite cooldown rounds per task; 0 disables automatic recovery 'auto_recovery_cooldown': 300.0, 'auth_budget': 600.0, 'login_timeout': 60.0, 'challenge_timeout': 120.0, 'standalone_auth_timeout': 900.0, 'startup_timeout': 60.0, 'close_timeout': 10.0, 'crawl_interval': 2.0, 'cooldown_seconds': 1800.0, 'recycle_tasks': 100, 'memory_limit_mb': 2048, 'disk_reserve_mb': 256, 'max_response_bytes': 32 * 1024 * 1024, 'max_result_bytes': 16 * 1024 * 1024, 'max_candidates': 64, 'max_rows': 20000, } def flight_dates(config, today=None): today = today or datetime.now(ZoneInfo(config['timezone'])).date() try: start = date.fromisoformat(config['begin_date']) if config['begin_date'] else today + timedelta(days=config['start_interval']) end = date.fromisoformat(config['end_date']) if config['end_date'] else start + timedelta(days=config['crawl_days'] - 1) except (TypeError, ValueError, OverflowError) as exc: raise CrawlerError('config_invalid', '日期配置无效') from exc if config['days_interval'] <= 0 or config['crawl_days'] <= 0: raise CrawlerError('config_invalid', '天数和日间隔必须大于零') if end < start: raise CrawlerError('config_invalid', '结束日期不能早于起始日期') return [(start + timedelta(days=i)).isoformat() for i in range(0, (end - start).days + 1, config['days_interval'])] def validate_config(config): config = copy.deepcopy(config) integer_minima = { 'start_interval': None, 'crawl_days': 1, 'days_interval': 1, 'recycle_tasks': 1, 'memory_limit_mb': 1, 'disk_reserve_mb': 0, 'max_response_bytes': 1, 'max_result_bytes': 1, 'max_candidates': 1, 'max_rows': 1, 'auto_recovery_rounds': 0, } for key, minimum in integer_minima.items(): value = config[key] if isinstance(value, bool) or not isinstance(value, int) or (minimum is not None and value < minimum): raise CrawlerError('config_invalid', key + ' 必须为有效整数') if not isinstance(config['crawl_citys'], list) or any(not isinstance(c, str) or not c.strip() for c in config['crawl_citys']): raise CrawlerError('config_invalid', 'crawl_citys 必须是非空城市名称列表') config['crawl_citys'] = list(dict.fromkeys(c.strip() for c in config['crawl_citys'])) if len(config['crawl_citys']) < 2: raise CrawlerError('config_invalid', '至少需要两个不同城市') if not config['direct_flight']: raise CrawlerError('unsupported_mode', '当前 CSV 合同仅支持直飞;不将转机行程截成第一段') if config['challenge_policy'] not in ('switch', 'wait_then_switch'): raise CrawlerError('config_invalid', 'challenge_policy 必须为 switch 或 wait_then_switch') if config['challenge_policy'] == 'wait_then_switch' and config['headless']: raise CrawlerError('config_invalid', '人工验证等待需要 --headed') if config['browser_build'] != BROWSER_BUILD: raise CrawlerError('config_invalid', '浏览器构建与此脚本锁定版本不一致') aliases, principals = set(), set() enabled = [] for account in config['accounts']: if not isinstance(account, dict): raise CrawlerError('config_invalid', 'accounts 项必须包含 alias、username 与凭据来源') alias, username = account.get('alias', ''), account.get('username', '') if not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', alias) or not isinstance(username, str) or not username.strip(): raise CrawlerError('config_invalid', '账号别名或登录标识无效') if alias in aliases or username.strip().casefold() in principals: raise CrawlerError('config_invalid', '账号别名和登录标识不能重复') aliases.add(alias) principals.add(username.strip().casefold()) if account.get('enabled', True): enabled.append(account) config['accounts'] = enabled if config['login_allowed'] and not enabled: raise CrawlerError('config_invalid', '请在顶部 accounts 配置账号池,或明确使用 --anonymous') if not config['login_allowed'] and enabled: raise CrawlerError('config_invalid', '匿名模式不能同时配置启用账号') nonnegative_times = {'crawl_interval', 'cooldown_seconds', 'comfort_timeout'} for key in ('attempt_timeout', 'task_budget', 'auth_budget', 'startup_timeout', 'close_timeout', 'action_timeout', 'navigation_timeout', 'login_timeout', 'challenge_timeout', 'standalone_auth_timeout', 'crawl_interval', 'cooldown_seconds', 'comfort_timeout', 'auto_recovery_cooldown'): value = config[key] if (isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or (value < 0 if key in nonnegative_times else value <= 0)): raise CrawlerError('config_invalid', key + ' 必须为有限的有效时间值') try: ZoneInfo(config['timezone']) except (KeyError, ValueError) as exc: raise CrawlerError('config_invalid', '时区不可用,请检查 tzdata 安装和时区名称') from exc proxy = config['proxy'] if proxy is not None: try: if not isinstance(proxy, dict) or not isinstance(proxy.get('server'), str): raise ValueError('proxy') parsed = urlparse(proxy['server']) if parsed.username is not None or parsed.password is not None: raise CrawlerError('config_invalid', '代理凭据必须放在独立的 username/password 字段中') if (parsed.scheme not in ('http', 'https', 'socks5') or not parsed.hostname or any(character.isspace() for character in parsed.hostname) or (parsed.port is not None and not 1 <= parsed.port <= 65535)): raise ValueError('proxy') except (TypeError, ValueError) as exc: raise CrawlerError('config_invalid', 'proxy 必须包含有效 HTTP/HTTPS/SOCKS5 主机和端口') from exc flight_dates(config) return config def proxy_identity(proxy): """Bind connection settings; authentication material may be refreshed.""" if proxy is None: return None return stable_hash({key: value for key, value in proxy.items() if key not in ('username', 'password')}) def validate_proxy_binding(saved_config, proxy, override=None, *, refresh=False, reason=None): """Validate v2 connections or explicitly migrate a legacy full-config hash. A legacy hash cannot prove its original endpoint. The explicit migration records the operator's confirmation; an existing migration cannot rebind. The caller alone publishes a newly returned override to its control file. """ if not isinstance(saved_config, dict) or 'proxy_id' not in saved_config: raise CrawlerError('state_invalid', '恢复记录缺少代理身份') version = saved_config.get('proxy_identity_version', 1) if type(version) is not int or version not in (1, 2): raise CrawlerError('state_invalid', '代理身份版本不兼容') connection_id = proxy_identity(proxy) frozen_id = saved_config['proxy_id'] if version == 2: if override is not None: raise CrawlerError('state_invalid', '新版代理身份不能附加旧版迁移记录') if connection_id != frozen_id: raise CrawlerError('config_invalid', '恢复时代理连接配置不能静默改变') return None if override is not None: if (not isinstance(override, dict) or override.get('proxy_identity_version') != 2 or frozen_id is None or override.get('legacy_proxy_id') != frozen_id or not isinstance(override.get('proxy_id'), str) or not override['proxy_id']): raise CrawlerError('state_invalid', '代理迁移凭据与原始固定计划不符') try: parse_utc(override['migrated_at']) except (KeyError, AttributeError, TypeError, ValueError, CrawlerError) as error: raise CrawlerError('state_invalid', '代理迁移凭据缺少有效确认时间') from error if override.get('proxy_id') != connection_id: raise CrawlerError('config_invalid', '恢复时代理连接配置不能静默改变') return override if refresh: if frozen_id is None or proxy is None: raise CrawlerError('config_invalid', '刷新代理凭据不能添加或移除代理连接') return {'proxy_identity_version': 2, 'proxy_id': connection_id, 'legacy_proxy_id': frozen_id, 'migrated_at': utc_now(), 'reason': reason} legacy_id = stable_hash(proxy) if proxy else None if legacy_id != frozen_id: raise CrawlerError('config_invalid', '旧批次代理认证已变化;确认连接相同时请显式刷新代理凭据') return None def public_config(config): excluded = {'accounts', 'proxy', 'output'} value = {key: copy.deepcopy(item) for key, item in config.items() if key not in excluded and key not in ('envelope',)} value['account_aliases'] = [a['alias'] for a in config['accounts']] value['proxy_identity_version'] = 2 value['proxy_id'] = proxy_identity(config['proxy']) return value def account_credentials(account): if account is None: return None return dict(account) def iter_tasks(plan): index = 0 for origin in plan['cities']: for destination in reversed(plan['cities']): if origin['code'] == destination['code']: continue for day in plan['dates']: identity = {'origin': origin['code'], 'destination': destination['code'], 'departure_date': day, 'options': plan['options']} yield {'index': index, 'key': stable_hash(identity), 'run_id': plan['run_id'], 'origin': origin, 'destination': destination, 'departure_date': day} index += 1 def new_task_control(index, account_count): return {'cursor': index, 'current': {'index': index, 'attempt_count': 0, 'max_attempts': max(3, account_count), 'work_used': 0.0, 'reserved': 0.0, 'auth_used': 0.0, 'auth_reserved': 0.0, 'auth_used_aliases': []}, 'blocked_accounts': {}, 'auth_used_aliases': [], 'state': 'idle'} def reserve_attempt(progress, alias, generation, timeout, total_budget=300): current = progress['current'] if current['attempt_count'] >= current['max_attempts'] or current['work_used'] >= total_budget: raise CrawlerError('task_exhausted', '当前任务自动恢复预算已耗尽') current.update(attempt_id=uuid.uuid4().hex, account_alias=alias, worker_generation=generation, reserved=min(timeout, total_budget - current['work_used']), started_at=utc_now()) current['attempt_count'] += 1 progress['state'] = 'running' return current def settle_attempt(progress, elapsed): current = progress['current'] current['work_used'] += min(max(0, elapsed), current.get('reserved', 0)) current['reserved'] = 0.0 progress['state'] = 'idle' def recover_attempt_budget(progress): current = progress.get('current') if current: current['work_used'] += current.pop('reserved', 0.0) current['reserved'] = 0.0 current['auth_used'] = current.get('auth_used', 0.0) + current.pop('auth_reserved', 0.0) current['auth_reserved'] = 0.0 progress['state'] = 'interrupted' def check_environment(): failures = [] if sys.version_info < (3, 12): failures.append('需要 Python 3.12 或以上') for package, expected in RUNTIME_REQUIREMENTS.items(): try: actual = importlib.metadata.version(package) if actual != expected: failures.append(f'{package}: 需要 {expected},当前 {actual}') except importlib.metadata.PackageNotFoundError: failures.append(f'{package}=={expected}: 未安装') if failures: raise CrawlerError('environment_invalid', '\n'.join(failures) + '\n安装命令见脚本顶部或 --help。') check_process_environment() # ================ files ================ # File publication and finite account-pool persistence. import copy as _files_copy import csv as _files_csv import hashlib as _files_hashlib import json as _files_json import os as _files_os import re as _files_re import uuid as _files_uuid from datetime import datetime as _files_datetime, timezone as _files_timezone from pathlib import Path as _FilesPath from zoneinfo import ZoneInfo as _FilesZoneInfo def _files_fail(message): raise CrawlerError('storage_error', message) def _files_sync_directory(path): if _files_os.name == 'nt': return descriptor = _files_os.open(str(path), _files_os.O_RDONLY | getattr(_files_os, 'O_DIRECTORY', 0)) try: _files_os.fsync(descriptor) finally: _files_os.close(descriptor) def read_json(path): try: value = _files_json.loads(_FilesPath(path).read_text(encoding='utf-8')) if not isinstance(value, dict): _files_fail(f'Expected a JSON object: {path}') return value except (OSError, ValueError) as exc: raise CrawlerError('storage_error', f'Cannot read JSON {path}: {exc}') from exc def atomic_json(path, data): path = _FilesPath(path) temporary = path.with_name(f'.{path.name}.{_files_uuid.uuid4().hex}.tmp') try: path.parent.mkdir(parents=True, exist_ok=True) with temporary.open('x', encoding='utf-8', newline='\n') as handle: _files_json.dump(data, handle, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False) handle.write('\n') handle.flush() _files_os.fsync(handle.fileno()) _files_os.replace(temporary, path) _files_sync_directory(path.parent) except (OSError, TypeError, ValueError) as exc: raise CrawlerError('storage_error', f'Cannot atomically write {path}: {exc}') from exc finally: if temporary.exists(): temporary.unlink() def safe_path(root, relative): root = _FilesPath(root).resolve() raw = str(relative).replace('\\', '/') if not raw or raw.startswith('/') or ':' in raw or '..' in raw.split('/'): _files_fail(f'Unsafe relative path: {relative}') path = (root / raw).resolve() if path == root or not path.is_relative_to(root): _files_fail(f'Path outside output directory: {relative}') return path def _files_digest(path): digest = _files_hashlib.sha256() try: with _FilesPath(path).open('rb') as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b''): digest.update(chunk) except OSError as exc: raise CrawlerError('storage_error', f'Cannot read result {path}: {exc}') from exc return digest.hexdigest() def _files_safe_name(value): if not isinstance(value, str) or not value or value in ('.', '..'): _files_fail('Missing safe result name') if _files_re.search(r'[<>:"/\\|?*\x00-\x1f]', value) or value.endswith((' ', '.')): _files_fail(f'Unsafe result name: {value}') return value def _files_initial_progress(run_id, initialization=None): initialization = initialization or {} recoveries = initialization.get('rate_limit_recoveries', 0) if type(recoveries) is not int or recoveries not in (0, 1): _files_fail('Invalid initialization site recovery budget') not_before = initialization.get('server_not_before') if not_before is not None: try: parse_utc(not_before) except (AttributeError, TypeError, ValueError) as exc: raise CrawlerError('storage_error', 'Invalid initialization site waiting time') from exc return { 'schema_version': SCHEMA_VERSION, 'run_id': run_id, 'cursor': 0, 'current': None, 'staging': None, 'publish_intent': None, 'stats': {'succeeded': 0, 'empty': 0, 'price_partial': 0, 'comfort_partial': 0, 'comfort_unavailable': 0}, 'status': 'pending', 'blocked_accounts': {}, 'auth_used_aliases': [], 'account_ack': {}, 'rate_limit_recoveries': recoveries, 'server_not_before': not_before, } def _files_check_price_quality(record, error_code): status, reason = record.get('price_status'), record.get('price_reason') allowed = ('not_applicable',) if record.get('status') == 'empty' else ('complete', 'partial') valid_reason = (isinstance(reason, list) and all(isinstance(item, str) and item for item in reason) and reason == sorted(set(reason))) if status not in allowed or not valid_reason or bool(reason) != (status == 'partial'): raise CrawlerError(error_code, 'Missing or inconsistent price quality metadata') class FileStore: def __init__(self, output, run_id): self.output = _FilesPath(output).resolve() if not isinstance(run_id, str) or not _files_re.fullmatch(r'[A-Za-z0-9_-]+', run_id): _files_fail('Invalid run identifier') self.run_id = run_id self.run_dir = safe_path(self.output, f'.runs/{run_id}') self.plan_path = self.run_dir / 'run.json' self.progress_path = self.run_dir / 'progress.json' self.initialization_path = self.run_dir / 'initialization.json' def create(self, plan): if self.plan_path.exists() or self.progress_path.exists(): _files_fail('Run already exists; use resume') if plan.get('run_id') != self.run_id: _files_fail('Plan run identifier differs') saved = _files_copy.deepcopy(plan) saved['schema_version'] = SCHEMA_VERSION saved.pop('plan_hash', None) saved['plan_hash'] = stable_hash(saved) initialization = read_json(self.initialization_path) if self.initialization_path.exists() else {} initialization.update(phase='plan_complete', progress_initialized=False, resolved_plan_hash=saved['plan_hash']) atomic_json(self.initialization_path, initialization) atomic_json(self.plan_path, saved) progress = _files_initial_progress(self.run_id, initialization) self.save_progress(progress) initialization['progress_initialized'] = True atomic_json(self.initialization_path, initialization) return progress def load(self): plan = read_json(self.plan_path) check = dict(plan) expected = check.pop('plan_hash', None) if plan.get('run_id') != self.run_id or plan.get('schema_version') != SCHEMA_VERSION or expected != stable_hash(check): _files_fail('Plan schema, identity or checksum differs') if not self.progress_path.exists(): initialization = read_json(self.initialization_path) if initialization.get('phase') != 'plan_complete' or initialization.get('progress_initialized') is not False or initialization.get('resolved_plan_hash') != expected: _files_fail('Missing progress cannot be recreated after task initialization') progress = _files_initial_progress(self.run_id, initialization) self.save_progress(progress) else: progress = read_json(self.progress_path) if progress.get('run_id') != self.run_id or progress.get('schema_version') != SCHEMA_VERSION: _files_fail('Progress schema or identity differs') if not isinstance(progress.get('cursor'), int) or progress['cursor'] < 0: _files_fail('Invalid progress cursor') if self.initialization_path.exists(): initialization = read_json(self.initialization_path) if initialization.get('progress_initialized') is False: initialization['progress_initialized'] = True atomic_json(self.initialization_path, initialization) return plan, progress def save_progress(self, progress): if progress.get('run_id') != self.run_id: _files_fail('Progress belongs to another run') atomic_json(self.progress_path, progress) def _relative(self, path): return path.relative_to(self.output).as_posix() def _check_stage(self, record, progress): current = progress.get('current') or {} if record.get('run_id') != self.run_id or record.get('task_index') != progress['cursor'] or record.get('attempt_id') != current.get('attempt_id'): _files_fail('Publication does not belong to current attempt') temporary = safe_path(self.output, record['temp_path']) target = safe_path(self.output, record['target_path']) if temporary.parent != target.parent or not temporary.name.startswith('.') or not temporary.name.endswith('.partial.csv'): _files_fail('Invalid owned staging path') return temporary, target def publish(self, task, observation, progress): try: if task.get('run_id') != self.run_id or task.get('index') != progress['cursor']: _files_fail('Result task does not match current cursor') current = progress.get('current') or {} attempt_id = current.get('attempt_id') if not attempt_id: _files_fail('Cannot publish without registered attempt') if progress.get('staging') or progress.get('publish_intent'): _files_fail('Recover outstanding publication before another result') if observation.get('status') not in ('succeeded', 'empty'): _files_fail('Only successful or verified empty observations can publish') rows, columns = observation.get('rows'), observation.get('columns') if not isinstance(rows, list) or not isinstance(columns, list) or not columns or len(columns) != len(set(columns)): _files_fail('Result rows or CSV columns missing') if observation['status'] == 'empty' and rows: _files_fail('Empty result contains rows') if observation['status'] == 'succeeded' and not rows: _files_fail('Successful result must contain rows') _files_check_price_quality(observation, 'data_invalid') plan = read_json(self.plan_path) timezone_name = plan.get('config', {}).get('timezone', 'Asia/Shanghai') observed = parse_utc(observation['observed_at']) if observed.tzinfo is None: _files_fail('Observation time must include timezone') day = observed.astimezone(_FilesZoneInfo(timezone_name)).date().isoformat() departure = _files_datetime.strptime(task['departure_date'], '%Y-%m-%d').date().isoformat() name = f"{_files_safe_name(task['origin']['name'])}-{_files_safe_name(task['destination']['name'])}.csv" target = safe_path(self.output, f'{departure}/{day}/{name}') receipt_path = target.with_suffix('.meta.json') if target.exists() or receipt_path.exists(): _files_fail(f'Result path already exists: {target}') result_id = _files_uuid.uuid4().hex temporary = target.with_name(f'.{self.run_id}.{attempt_id}.{result_id}.partial.csv') stage = { 'run_id': self.run_id, 'task_index': task['index'], 'task_key': task['key'], 'attempt_id': attempt_id, 'result_id': result_id, 'observed_at': observation['observed_at'], 'temp_path': self._relative(temporary), 'target_path': self._relative(target), } progress['staging'] = stage self.save_progress(progress) target.parent.mkdir(parents=True, exist_ok=True) with temporary.open('x', encoding='utf-8', newline='') as handle: writer = _files_csv.DictWriter(handle, fieldnames=columns, extrasaction='raise', lineterminator='\n') writer.writeheader() writer.writerows(rows) handle.flush() _files_os.fsync(handle.fileno()) if target.exists() or receipt_path.exists(): _files_fail('Output changed during publication') intent = dict(stage, schema_version=SCHEMA_VERSION, sha256=_files_digest(temporary), row_count=len(rows), status=observation['status'], columns=columns, comfort_status=observation.get('comfort_status', 'disabled'), comfort_reason=observation.get('comfort_reason'), price_status=observation['price_status'], price_reason=observation['price_reason'], manual_recoveries=_files_copy.deepcopy(current.get('manual_recoveries')), automatic_recoveries=_files_copy.deepcopy(current.get('automatic_recoveries')), comfort_summary=_files_copy.deepcopy(observation.get('comfort_summary')), account_alias=task.get('account_alias'), binding_epoch=task.get('binding_epoch')) progress['publish_intent'] = intent self.save_progress(progress) self._finish_publication(progress) return progress except CrawlerError: raise except (OSError, ValueError, KeyError, TypeError) as exc: raise CrawlerError('storage_error', f'Cannot publish result: {exc}') from exc def _finish_publication(self, progress): intent = progress['publish_intent'] for key in ('manual_recoveries', 'automatic_recoveries'): if intent.get(key) != (progress.get('current') or {}).get(key): _files_fail('Recovery evidence differs from the current task') temporary, target = self._check_stage(intent, progress) meta_path = target.with_suffix('.meta.json') if target.exists(): if _files_digest(target) != intent['sha256']: _files_fail('Published CSV differs from recorded intent') else: if meta_path.exists(): _files_fail('Receipt exists without its CSV') if not temporary.exists() or _files_digest(temporary) != intent['sha256']: _files_fail('Staging CSV cannot complete publication') _files_os.replace(temporary, target) _files_sync_directory(target.parent) if meta_path.exists(): receipt = read_json(meta_path) for key in ('run_id', 'task_index', 'task_key', 'attempt_id', 'result_id', 'sha256', 'row_count', 'target_path', 'comfort_status', 'comfort_reason', 'price_status', 'price_reason', 'manual_recoveries', 'automatic_recoveries', 'comfort_summary'): if receipt.get(key) != intent.get(key): _files_fail('Receipt differs from current publication') else: atomic_json(meta_path, dict(intent, committed_at=utc_now())) candidate = _files_copy.deepcopy(progress) candidate['cursor'] += 1 stats = candidate.setdefault('stats', {}) stats[intent['status']] = stats.get(intent['status'], 0) + 1 if intent['price_status'] == 'partial': stats['price_partial'] = stats.get('price_partial', 0) + 1 if intent['status'] == 'succeeded' and intent.get('comfort_status') in ('partial', 'unavailable'): key = 'comfort_' + intent['comfort_status'] stats[key] = stats.get(key, 0) + 1 candidate.update(current=None, staging=None, publish_intent=None, blocked_accounts={}, auth_used_aliases=[], status='pending') for key in ('attempt_count', 'spent_seconds', 'reserved_seconds', 'auth_spent_seconds', 'auth_reserved_seconds'): candidate[key] = 0 self.save_progress(candidate) progress.clear() progress.update(candidate) if temporary.exists(): temporary.unlink() def recover(self, progress): try: intent = progress.get('publish_intent') if intent: _files_check_price_quality(intent, 'state_invalid') temporary, target = self._check_stage(intent, progress) if target.exists(): self._finish_publication(progress) return True if target.with_suffix('.meta.json').exists(): _files_fail('Receipt exists but its CSV is missing') if temporary.exists() and _files_digest(temporary) == intent.get('sha256'): self._finish_publication(progress) return True if temporary.exists(): temporary.unlink() progress.update(staging=None, publish_intent=None) self.save_progress(progress) return False stage = progress.get('staging') if stage: temporary, target = self._check_stage(stage, progress) if target.exists() or target.with_suffix('.meta.json').exists(): _files_fail('Unexpected result beside unfinished staging') if temporary.exists(): temporary.unlink() progress['staging'] = None self.save_progress(progress) return False except CrawlerError: raise except (OSError, ValueError, KeyError, TypeError) as exc: raise CrawlerError('storage_error', f'Cannot recover publication: {exc}') from exc class AccountPool: def __init__(self, output, accounts): self.output = _FilesPath(output).resolve() self.path = self.output / 'accounts.json' self.config = {} identifiers = set() for account in accounts: alias = account.get('alias') if not isinstance(alias, str) or not _files_re.fullmatch(r'[A-Za-z0-9_-]+', alias): raise CrawlerError('config_error', 'Invalid account alias') login = str(account.get('username', '')).strip() identity_hash = stable_hash(login) if alias in self.config or identity_hash in identifiers: raise CrawlerError('config_error', 'Duplicate account alias or login') identifiers.add(identity_hash) self.config[alias] = dict(account) self.data = read_json(self.path) if self.path.exists() else {'schema_version': SCHEMA_VERSION, 'accounts': {}} if self.data.get('schema_version') != SCHEMA_VERSION or not isinstance(self.data.get('accounts'), dict): _files_fail('Account state schema differs') changed = False for alias, account in self.config.items(): identity_hash = stable_hash(str(account.get('username', '')).strip()) record = self.data['accounts'].get(alias) if record is not None and record.get('login_hash') != identity_hash: raise CrawlerError('config_error', f'Account alias {alias} is bound to another login') if record is None: self.data['accounts'][alias] = { 'alias': alias, 'login_hash': identity_hash, 'state': 'needs_auth', 'reason': 'not_authenticated', 'pool_revision': 0, 'session_revision': 0, 'session_identity_id': None, 'cooldown_until': None, 'server_not_before': None, 'last_used_at': None, 'last_explicit_login': None, 'mutation': None, } changed = True if changed: self._save() def _save(self): atomic_json(self.path, self.data) def record(self, alias): if alias not in self.config: raise CrawlerError('config_error', 'Unknown account alias') return _files_copy.deepcopy(self.data['accounts'][alias]) def session_path(self, alias): self.record(alias) return safe_path(self.output, f'sessions/{alias}/session.json') def load_session(self, alias): path = self.session_path(alias) return read_json(path) if path.exists() else None def initialize_session(self, alias, snapshot): existing = self.load_session(alias) if existing is not None: return existing self._validate_snapshot(alias, snapshot, initial=True) atomic_json(self.session_path(alias), snapshot) return _files_copy.deepcopy(snapshot) def _validate_snapshot(self, alias, snapshot, initial=False): if not isinstance(snapshot, dict) or not snapshot.get('session_identity_id') or not isinstance(snapshot.get('session_revision'), int): _files_fail('Session identity or revision missing') if snapshot['session_revision'] < 0: _files_fail('Negative session revision') existing = self.load_session(alias) if existing: if snapshot['session_identity_id'] != existing.get('session_identity_id'): _files_fail('Session identity changed without explicit reset') if snapshot['session_revision'] <= existing.get('session_revision', -1): if snapshot == existing: return _files_fail('Session revision did not increase') def _future(self, value): return bool(value and parse_utc(value) > parse_utc(utc_now())) def _blocked(self, alias, blocked): if alias not in blocked: return False entry = blocked[alias] if isinstance(blocked, dict) else None evidence = self.data['accounts'][alias].get('last_explicit_login') if not isinstance(entry, dict) or not evidence: return True return evidence.get('pool_revision', -1) <= entry.get('pool_revision', 0) def select(self, preferred=None, blocked=None): blocked = blocked or {} aliases = [alias for alias, config in self.config.items() if config.get('enabled', True)] if preferred in aliases: index = aliases.index(preferred) aliases = aliases[index:] + aliases[:index] for alias in aliases: record = self.data['accounts'][alias] if self._blocked(alias, blocked) or record['state'] == 'disabled': continue if self._future(record.get('server_not_before')) or self._future(record.get('cooldown_until')): continue return alias return None def _control_ref(self, control_path): path = _FilesPath(control_path).resolve() if not path.is_relative_to(self.output): _files_fail('Account mutation control outside output') return path.relative_to(self.output).as_posix() def _apply_mutation(self, alias, mutation, control=None, control_path=None): reference = mutation.get('control_path') if not reference: return path = safe_path(self.output, reference) state = read_json(path) acknowledgements = state.setdefault('account_ack', {}) if acknowledgements.get(alias) != mutation['id']: effect = mutation['effect'] blocked = state.setdefault('blocked_accounts', {}) if effect.get('block'): blocked[alias] = {key: effect.get(key) for key in ('reason', 'session_identity_id', 'session_revision', 'pool_revision')} acknowledgements[alias] = mutation['id'] try: atomic_json(path, state) except OSError as exc: raise CrawlerError('storage_error', f'Cannot reconcile account control: {exc}') from exc if control is not None and control_path is not None and path == _FilesPath(control_path).resolve(): control.clear() control.update(state) def reconcile(self, control=None, control_path=None): changed = False for alias, record in self.data['accounts'].items(): mutation = record.get('mutation') if mutation and not mutation.get('confirmed'): self._apply_mutation(alias, mutation, control, control_path) mutation['confirmed'] = True changed = True if changed: self._save() if control is not None: state = read_json(control_path) if control_path is not None else _files_copy.deepcopy(control) blocked = state.setdefault('blocked_accounts', {}) cleared = [alias for alias in blocked if alias in self.config and not self._blocked(alias, blocked)] for alias in cleared: blocked.pop(alias) if cleared: if control_path is not None: atomic_json(control_path, state) control.clear() control.update(state) changed = True return changed def mark(self, alias, state, reason, *, cooldown_until=None, server_not_before=None, control_path=None, control=None, source=None): if state not in ('ready', 'needs_auth', 'cooldown', 'disabled'): raise CrawlerError('config_error', 'Unknown account state') self.reconcile(control, control_path) record = self.data['accounts'][alias] record.update(state=state, reason=reason, pool_revision=record['pool_revision'] + 1) if cooldown_until is not None: record['cooldown_until'] = cooldown_until if server_not_before is not None: previous = record.get('server_not_before') record['server_not_before'] = max(filter(None, (previous, server_not_before)), key=parse_utc) mutation = { 'id': _files_uuid.uuid4().hex, 'confirmed': control_path is None, 'control_path': self._control_ref(control_path) if control_path is not None else None, 'source': dict(source or {}), 'effect': {'block': state in ('cooldown', 'disabled'), 'reason': reason, 'session_identity_id': record.get('session_identity_id'), 'session_revision': record.get('session_revision', 0), 'pool_revision': record['pool_revision']}, } record['mutation'] = mutation self._save() if control_path is not None: self._apply_mutation(alias, mutation, control, control_path) mutation['confirmed'] = True self._save() return self.record(alias) def commit_session(self, alias, snapshot, *, explicit_auth=False, auth_id=None, control_path=None, control=None): self.reconcile(control, control_path) if explicit_auth and not auth_id: _files_fail('Explicit authentication requires auth_id') self._validate_snapshot(alias, snapshot) atomic_json(self.session_path(alias), snapshot) record = self.data['accounts'][alias] record.update(session_identity_id=snapshot['session_identity_id'], session_revision=snapshot['session_revision']) if explicit_auth: if not auth_id: _files_fail('Explicit authentication requires auth_id') record['cooldown_until'] = None record['last_explicit_login'] = { 'auth_id': auth_id, 'session_identity_id': snapshot['session_identity_id'], 'session_revision': snapshot['session_revision'], 'pool_revision': record['pool_revision'] + 1, } result = self.mark(alias, 'ready', 'explicit_login', control_path=control_path, control=control, source={'auth_id': auth_id}) elif record['state'] == 'ready': self._save() result = self.record(alias) else: # Session refresh is data, not evidence that a blocked account was explicitly authenticated. self._save() result = self.record(alias) self.reconcile(control, control_path) return result # ================ processing ================ LEGACY_FLIGHT_FIELDS = ( "sequenceNo", "marketAirlineCode", "marketAlliance", "departureCountryCode", "departureProvinceId", "departureCityId", "departureCityCode", "departureAirportShortName", "departureTerminal", "arrivalCountryCode", "arrivalProvinceId", "arrivalCityId", "arrivalCityCode", "arrivalAirportShortName", "arrivalTerminal", "transferDuration", "departureDateTime", "arrivalDateTime", "leakedVisaTagSwitch", "highLightPlaneNo", "istTransitService", "mainSegment", "operateAirlineCode", "operateAirlineName", "operateAlliance", "operateFlightNo", "isLowCostCarrier", "stopList", ) CSV_COLUMNS = ( ("run_id", "批次标识"), ("task_key", "任务标识"), ("itineraryId", "行程标识"), ("observed_at", "采集时间"), ("dateGetTime", "数据获取日期"), ("flightNo", "航班号"), ("operateFlightNo", "实际承运航班号"), ("marketAirlineName", "航空公司"), ("departureday", "出发日期"), ("departuretime", "出发时间"), ("arrivalday", "到达日期"), ("arrivaltime", "到达时间"), ("duration", "飞行时长"), ("departureCountryName", "出发国家"), ("departureCityName", "出发城市"), ("departureAirportName", "出发机场"), ("departureAirportCode", "出发机场三字码"), ("arrivalCountryName", "到达国家"), ("arrivalCityName", "到达城市"), ("arrivalAirportName", "到达机场"), ("arrivalAirportCode", "到达机场三字码"), ("aircraftName", "飞机型号"), ("aircraftSize", "飞机尺寸"), ("aircraftCode", "飞机型号三字码"), ("stopCount", "停留次数"), ("stopInfo", "中转信息"), ("currency", "币种"), ("price_status", "价格状态"), ("price_reason", "价格不完整原因"), ("economy_origin", "economy_origin"), ("economy_tax", "economy_tax"), ("economy_total", "economy_total"), ("economy_full", "economy_full"), ("economy_price_status", "经济舱价格状态"), ("economy_comparison_basis", "经济舱比较口径"), ("economy_currency", "经济舱币种"), ("bussiness_origin", "bussiness_origin"), ("bussiness_tax", "bussiness_tax"), ("bussiness_total", "bussiness_total"), ("bussiness_full", "bussiness_full"), ("bussiness_price_status", "商务舱价格状态"), ("bussiness_comparison_basis", "商务舱比较口径"), ("bussiness_currency", "商务舱币种"), ("comfort_status", "舒适度状态"), ("departure_delay_time", "出发延误时间"), ("departure_bridge_rate", "出发廊桥率"), ("arrival_delay_time", "到达延误时间"), ("plane_type", "飞机类型"), ("plane_width", "飞机宽度"), ("plane_age", "飞机机龄"), ("Y_has_meal", "经济舱餐食标记(原值)"), ("Y_seat_tilt", "经济舱座椅倾斜度"), ("Y_seat_width", "经济舱座椅宽度"), ("Y_seat_pitch", "经济舱座椅间距"), ("Y_meal_msg", "经济舱餐食信息"), ("Y_power", "经济舱电源"), ("C_has_meal", "商务舱餐食标记(原值)"), ("C_seat_tilt", "商务舱座椅倾斜度"), ("C_seat_width", "商务舱座椅宽度"), ("C_seat_pitch", "商务舱座椅间距"), ("C_meal_msg", "商务舱餐食信息"), ("C_power", "商务舱电源"), ) + tuple(("legacy_operateFlightNo" if name == "operateFlightNo" else name, name) for name in LEGACY_FLIGHT_FIELDS) CSV_FIELDS = tuple(label for internal, label in CSV_COLUMNS) CSV_INTERNAL_FIELDS = tuple(internal for internal, label in CSV_COLUMNS) CSV_INTERNAL_NAMES = {label: internal for internal, label in CSV_COLUMNS} def _processing_source_value(value): """Keep source values, including false/zero and explicit empty structures.""" if value is None: return "" if isinstance(value, (dict, list)): return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False) return value def _processing_money(value, field): if value is None or isinstance(value, bool): raise CrawlerError("data_invalid", f"Missing or invalid quote field: {field}") try: amount = Decimal(str(value)) except (InvalidOperation, ValueError, TypeError) as exc: raise CrawlerError("data_invalid", f"Invalid amount in {field}") from exc if not amount.is_finite() or amount < 0: raise CrawlerError("data_invalid", f"Non-finite or negative amount in {field}") return amount def _processing_decimal_text(amount): text = format(amount, "f") return text.rstrip("0").rstrip(".") if "." in text else text def _processing_currency(value): if not isinstance(value, str) or len(value) != 3 or not value.isascii() or not value.isalpha(): raise CrawlerError("data_invalid", "Quote currency is missing or invalid") code = value.upper() return "CNY" if code == "RMB" else code def _processing_quote(price, currency): """Preserve explicit components; absence is partial data, never invented tax.""" base = _processing_money(price.get("adultPrice"), "adultPrice") tax = None if price.get("adultTax") is not None and price.get("adultTax") != "": tax = _processing_money(price["adultTax"], "adultTax") elif price.get("freeOilFeeAndTax") is True: tax = Decimal(0) # Luggage criteria is an observed explicit total/currency contract. Its # absence is common for domestic quotes. sortPrice and ancillary package # prices do not establish tax, total or currency. embedded_currency, embedded_total = None, None if price.get("luggageVisaKey") not in (None, ""): try: baggage = json.loads(price["luggageVisaKey"]) criteria = baggage["criteria"] if not isinstance(criteria, dict): raise ValueError("criteria") if criteria.get("Currency") not in (None, ""): embedded_currency = _processing_currency(criteria["Currency"]) if criteria.get("TotalPrice") not in (None, ""): embedded_total = _processing_money(criteria["TotalPrice"], "criteria.TotalPrice") except (TypeError, ValueError, KeyError) as exc: raise CrawlerError("data_invalid", "Invalid luggageVisaKey quote criteria") from exc total = base + tax if tax is not None else embedded_total if embedded_total is not None: if embedded_total < base or (tax is not None and embedded_total != base + tax): raise CrawlerError("data_invalid", "Quote total conflicts with its explicit components") currencies = {_processing_currency(value) for value in (price.get("currency"), price.get("currencyCode"), currency, embedded_currency) if value is not None and value != ""} if len(currencies) > 1: raise CrawlerError("data_invalid", "Quote currency conflicts with its explicit criteria") quote_currency = next(iter(currencies), None) missing = [] if quote_currency is None: missing.append("currency_missing") if tax is None: missing.append("tax_missing") if total is None: missing.append("total_missing") return {"base": base, "tax": tax, "total": total, "currency": quote_currency, "complete": not missing, "missing": missing, "legacy_full": _processing_source_value(price.get("miseryIndex"))} def _processing_datetime(value, field): if not isinstance(value, str): raise CrawlerError("data_invalid", f"Missing datetime field {field}") try: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError as exc: raise CrawlerError("data_invalid", f"Invalid datetime field {field}") from exc return parsed.date().isoformat(), parsed.time().isoformat(timespec="seconds") def normalize_response(payload: dict, task: dict, options: dict, observed_at: str) -> dict: """Normalize one adapter-confirmed complete search response without I/O.""" data = payload.get("data") if isinstance(payload, dict) else None if not isinstance(data, dict) or not isinstance(data.get("flightItineraryList"), list): raise CrawlerError("protocol_changed", "Expected data.flightItineraryList list") if not options.get("direct_flight", True): raise CrawlerError("unsupported_mode", "Only complete direct-flight itineraries are currently supported") items = data["flightItineraryList"] try: observed_time = datetime.fromisoformat(observed_at.replace("Z", "+00:00")) except (AttributeError, TypeError, ValueError) as exc: raise CrawlerError("data_invalid", "Invalid observation timestamp") from exc if observed_time.tzinfo is None: raise CrawlerError("data_invalid", "Observation timestamp must include its UTC offset") observed_day = observed_time.astimezone(ZoneInfo(options.get("timezone", "Asia/Shanghai"))).date().isoformat() comfort_status = "unavailable" if options.get("comft_flight", False) else "not_requested" rows = [] max_rows = options.get('max_rows') price_reasons = set() identities = set() response_currencies = {_processing_currency(value) for value in (data.get("currency"), data.get("currencyCode")) if value is not None and value != ""} if len(response_currencies) > 1: raise CrawlerError("data_invalid", "Search response has conflicting currency sources") default_currency = next(iter(response_currencies), None) for item in items: if not isinstance(item, dict): raise CrawlerError("protocol_changed", "Itinerary must be an object") identity = item.get("itineraryId") segments = item.get("flightSegments") if not isinstance(identity, str) or not identity or not isinstance(segments, list) or not segments: raise CrawlerError("protocol_changed", "Itinerary identity or segments are missing") if identity in identities: raise CrawlerError("data_invalid", "Duplicate itinerary identity in complete response") identities.add(identity) if len(segments) != 1: raise CrawlerError("data_invalid", "Direct itinerary contains multiple flight segments") segment = segments[0] if not isinstance(segment, dict) or not isinstance(segment.get("transferCount"), int): raise CrawlerError("protocol_changed", "Itinerary transferCount is missing") if segment["transferCount"] != 0: continue flights = segment.get("flightList") if not isinstance(flights, list) or len(flights) != 1 or not isinstance(flights[0], dict): raise CrawlerError("data_invalid", "Direct itinerary must contain exactly one flight record") flight = flights[0] for field in ("flightNo", "departureAirportCode", "arrivalAirportCode"): if not isinstance(flight.get(field), str) or not flight[field]: raise CrawlerError("data_invalid", f"Flight identity field is missing: {field}") departure_day, departure_time = _processing_datetime(flight.get("departureDateTime"), "departureDateTime") arrival_day, arrival_time = _processing_datetime(flight.get("arrivalDateTime"), "arrivalDateTime") if task.get("departure_date") and departure_day != task["departure_date"]: raise CrawlerError("data_invalid", "Itinerary departure date differs from current task") origin = task.get("origin", {}) destination = task.get("destination", {}) for side, expected in (("departure", origin), ("arrival", destination)): code = flight.get(side + "CityCode") if code and expected.get("code") and code.upper() != expected["code"].upper(): raise CrawlerError("data_invalid", "Itinerary city code differs from current task") prices = item.get("priceList") if not isinstance(prices, list): raise CrawlerError("protocol_changed", "Itinerary priceList must be a list") candidates = {"Y": [], "C": []} currencies = set() unknown_currency = False row_reasons = set() for price in prices: if not isinstance(price, dict) or "cabin" not in price: raise CrawlerError("protocol_changed", "Quote cabin is missing") cabin = price["cabin"] if cabin not in ("Y", "C"): continue parsed = _processing_quote(price, default_currency) candidates[cabin].append(parsed) row_reasons.update(parsed["missing"]) if parsed["currency"] is None: unknown_currency = True else: currencies.add(parsed["currency"]) if len(currencies) > 1: raise CrawlerError("data_invalid", "Cannot compare itinerary quotes in multiple currencies") if not any(candidates.values()): row_reasons.add("no_target_quote") row_price_status = "partial" if row_reasons else "complete" price_reasons.update(row_reasons) row = dict.fromkeys(CSV_FIELDS, "") row.update({name: _processing_source_value(flight.get(name)) for name in LEGACY_FLIGHT_FIELDS}) row.update({ "批次标识": task.get("run_id", ""), "任务标识": task.get("key", ""), "行程标识": identity, "采集时间": observed_at, "数据获取日期": observed_day, "航班号": flight["flightNo"], "实际承运航班号": flight.get("operateFlightNo", ""), "航空公司": flight.get("marketAirlineName", ""), "出发日期": departure_day, "出发时间": departure_time, "到达日期": arrival_day, "到达时间": arrival_time, "飞行时长": flight.get("duration", ""), "出发国家": flight.get("departureCountryName", ""), "出发城市": flight.get("departureCityName") or origin.get("name", ""), "出发机场": flight.get("departureAirportName", ""), "出发机场三字码": flight["departureAirportCode"], "到达国家": flight.get("arrivalCountryName", ""), "到达城市": flight.get("arrivalCityName") or destination.get("name", ""), "到达机场": flight.get("arrivalAirportName", ""), "到达机场三字码": flight["arrivalAirportCode"], "飞机型号": flight.get("aircraftName", ""), "飞机尺寸": flight.get("aircraftSize", ""), "飞机型号三字码": flight.get("aircraftCode", ""), "停留次数": flight.get("stopCount", ""), "币种": next(iter(currencies), "") if not unknown_currency else "", "价格状态": row_price_status, "价格不完整原因": ";".join(sorted(row_reasons)), "舒适度状态": comfort_status, }) stops = flight.get("stopList") or [] if not isinstance(stops, list) or any(not isinstance(stop, dict) for stop in stops): raise CrawlerError("data_invalid", "Invalid stopList") row["中转信息"] = " -> ".join(f"{stop.get('cityName', '')}({stop.get('airportName', '')}, {stop.get('duration', '')}分钟)" for stop in stops) or "无中转" for cabin, prefix, label in (("Y", "economy", "经济舱"), ("C", "bussiness", "商务舱")): quotes = candidates[cabin] if not quotes: row[label + "价格状态"] = "not_available" continue complete = all(quote["complete"] for quote in quotes) if complete: selected = min(quotes, key=lambda quote: quote["total"]) basis = "total_fare" else: selected = min(quotes, key=lambda quote: quote["base"]) # This is only the minimum source adultPrice number when any # candidate omits currency, not a same-currency price claim. basis = "base_fare_currency_unknown" if any(quote["currency"] is None for quote in quotes) else "base_fare" row[label + "价格状态"] = "complete" if complete else "partial" row[label + "比较口径"] = basis row[label + "币种"] = selected["currency"] or "" row[prefix + "_full"] = selected["legacy_full"] for suffix, field in (("origin", "base"), ("tax", "tax"), ("total", "total")): value = selected[field] row[f"{prefix}_{suffix}"] = _processing_decimal_text(value) if value is not None else "" rows.append(row) if max_rows is not None and len(rows) > max_rows: raise CrawlerError('response_too_large', 'Qualified itinerary rows exceed the configured limit') columns = CSV_FIELDS if options.get("rename_col", True) is False: rows = [{internal: row[label] for internal, label in CSV_COLUMNS} for row in rows] columns = CSV_INTERNAL_FIELDS return {"rows": rows, "columns": list(columns), "status": "succeeded" if rows else "empty", "observed_at": observed_at, "comfort_status": comfort_status, "price_status": "not_applicable" if not rows else ("partial" if price_reasons else "complete"), "price_reason": sorted(price_reasons)} def _processing_comfort_value(value): return (isinstance(value, (str, int, float, bool)) and (not isinstance(value, str) or bool(value.strip()))) def _processing_comfort_data(payload): if (not isinstance(payload, dict) or type(payload.get("status")) is not int or payload["status"] != 0 or payload.get("msg") != "success"): return None data = payload.get("data") if not isinstance(data, dict): return None punctuality, plane, cabins = data.get("punctualityInfo"), data.get("planeInfo"), data.get("cabinInfoList") if not isinstance(punctuality, dict) or not isinstance(plane, dict) or not isinstance(cabins, list): return None values = {} for source, mapping in ( (punctuality, {"departureDelaytime": "出发延误时间", "departureBridge": "出发廊桥率", "arrivalDelaytime": "到达延误时间"}), (plane, {"planeTypeName": "飞机类型", "planeWidthCategory": "飞机宽度", "planeAge": "飞机机龄"}), ): for key, label in mapping.items(): if _processing_comfort_value(source.get(key)): values[label] = source[key] for cabin in cabins: if not isinstance(cabin, dict) or cabin.get("cabin") not in ("Y", "C"): continue name = "经济舱" if cabin["cabin"] == "Y" else "商务舱" fields = {"hasMeal": "餐食标记(原值)", "mealMsg": "餐食信息", "power": "电源"} for key, label in fields.items(): value = cabin.get(key) if _processing_comfort_value(value): values[name + label] = value for key, label in (("seatTilt", "座椅倾斜度"), ("seatWidth", "座椅宽度"), ("seatPitch", "座椅间距")): seat = cabin.get(key) if isinstance(seat, dict) and _processing_comfort_value(seat.get("value")): value = seat["value"] # The source page displays these numeric sentinel values as unknown. if isinstance(value, (int, float)) and (value == 0 if key == "seatTilt" else -0.5 <= value < 0.5): continue values[name + label] = seat["value"] return values def _record_comfort_values(by_flight, flight_no, payload): values = _processing_comfort_data(payload) if values is not None: by_flight.setdefault(flight_no, {}).update(values) def apply_comfort(rows, responses): """Attach known comfort responses by operating flight, preserving quotes.""" by_flight = {} for response in responses: if not isinstance(response, dict) or not isinstance(response.get("flight_no"), str): continue _record_comfort_values(by_flight, response["flight_no"], response.get("payload")) return _merge_comfort_rows(rows, by_flight) def _merge_comfort_rows(rows, by_flight): result = [] statuses = [] targets, covered = set(), set() covered_rows = 0 missing_fields = {} common = {"出发延误时间", "出发廊桥率", "到达延误时间", "飞机类型", "飞机宽度", "飞机机龄"} for original in rows: row = dict(original) english = "flightNo" in row and "航班号" not in row def column(label): return CSV_INTERNAL_NAMES[label] if english else label number = row.get(column("实际承运航班号")) or row.get(column("航班号")) targets.add(number) values = by_flight.get(number, {}) required = set(common) for prefix, name in (("economy", "经济舱"), ("bussiness", "商务舱")): if row.get(prefix + "_origin") not in (None, ""): required.update(name + suffix for suffix in ("餐食信息", "座椅倾斜度", "座椅宽度", "座椅间距")) status = "complete" if required.issubset(values) else ("partial" if values else "unavailable") if number in by_flight: covered.add(number) covered_rows += 1 for label in required - values.keys(): field = CSV_INTERNAL_NAMES[label] missing_fields[field] = missing_fields.get(field, 0) + 1 for label, value in values.items(): row[column(label)] = value row[column("舒适度状态")] = status result.append(row) statuses.append(status) status = "not_applicable" if not rows else "complete" if all(item == "complete" for item in statuses) else ( "unavailable" if all(item == "unavailable" for item in statuses) else "partial") reasons = [] if covered_rows < len(rows): reasons.append("response_coverage_incomplete") if missing_fields: reasons.append("source_missing") return {"rows": result, "comfort_status": status, "comfort_reason": ";".join(reasons) or None, "comfort_summary": {"result_flights": len(targets), "covered_flights": len(covered), "covered_rows": covered_rows, "complete_rows": statuses.count("complete"), "partial_rows": statuses.count("partial"), "unavailable_rows": statuses.count("unavailable"), "missing_fields": dict(sorted(missing_fields.items()))}} # ================ browser ================ # Browser dependencies are imported lazily so --help works without installation. CAMOUFOX_BUILD = "official/152.0.4-beta.29" CTRIP_HOME = "https://flights.ctrip.com/online/channel/domestic" SEARCH_API_PATH = "/international/search/api/search/batchSearch" def browser_environment_check(): """Check installed assets without downloading or starting a collection.""" import subprocess from camoufox.fpgen_model import is_pinned from camoufox.multiversion import find_installed_version from camoufox.pkgman import launch_path installed = find_installed_version(CAMOUFOX_BUILD) if installed is None: raise CrawlerError("browser_missing", "Install the pinned Camoufox browser: python -m camoufox fetch " + CAMOUFOX_BUILD) if not is_pinned(): raise CrawlerError("browser_missing", "Install the pinned fingerprint model explicitly: python -c \"from camoufox.fpgen_model import ensure_fpgen_model; ensure_fpgen_model()\"") try: checked = subprocess.run([launch_path(installed), "--version"], capture_output=True, timeout=10, check=False) except (OSError, subprocess.TimeoutExpired) as exc: raise CrawlerError("browser_unavailable", "The installed Camoufox executable cannot start; check its platform dependencies") from exc if checked.returncode: raise CrawlerError("browser_unavailable", "The installed Camoufox executable failed its startup check") return {"browser_build": CAMOUFOX_BUILD, "installed": True} def generate_identity(config): """Resolve one identity once; the caller persists it before browser launch.""" from camoufox.fingerprints import get_random_preset from camoufox.addons import DefaultAddons from camoufox.multiversion import find_installed_version from camoufox.pkgman import launch_path from camoufox.utils import launch_options installed = find_installed_version(CAMOUFOX_BUILD) if not installed: raise CrawlerError("browser_missing", "Install the pinned Camoufox browser: python -m camoufox fetch " + CAMOUFOX_BUILD) operating_system = {"Windows": "windows", "Linux": "linux", "Darwin": "macos"}.get(platform.system()) if operating_system is None: raise CrawlerError("platform_unsupported", "Camoufox requires a supported desktop operating system") preset = get_random_preset(os=operating_system, ff_version=CAMOUFOX_BUILD.split("/")[-1].split(".")[0]) if not preset: raise CrawlerError("identity_unavailable", "The pinned package has no fingerprint preset for this platform") options = launch_options(executable_path=launch_path(installed), fingerprint_preset=copy.deepcopy(preset), os=operating_system, headless=bool(config.get("headless", True)), locale="zh-CN", env={}, pin_cpu_cores=False, exclude_addons=list(DefaultAddons)) # env={} prevents credentials and unrelated host variables entering session.json. options["env"] = {key: value for key, value in options["env"].items() if key.startswith("CAMOU_") or key == "FONTCONFIG_FILE"} identity = {"schema": 1, "platform": platform.system(), "browser_build": CAMOUFOX_BUILD, "identity_id": uuid.uuid4().hex, "preset": preset, "launch": options} # Refuse an identity that cannot be persisted without custom encoders. json.dumps(identity, ensure_ascii=False, allow_nan=False) return identity def identity_launch_options(identity, config): if (not isinstance(identity, dict) or identity.get("schema") != 1 or identity.get("platform") != platform.system() or identity.get("browser_build") != CAMOUFOX_BUILD): raise CrawlerError("identity_incompatible", "Saved browser identity requires explicit recreation on this platform/build") options = copy.deepcopy(identity["launch"]) options["env"] = {**os.environ, **options.get("env", {})} if platform.system() == "Linux": binary_directory = str(Path(options["executable_path"]).parent) options["env"]["LD_LIBRARY_PATH"] = binary_directory + ( ":" + options["env"]["LD_LIBRARY_PATH"] if options["env"].get("LD_LIBRARY_PATH") else "") runtime = options["env"].get("XDG_RUNTIME_DIR") if runtime and config.get("headless", True): try: if Path(runtime).stat().st_uid != os.getuid(): options["env"].pop("XDG_RUNTIME_DIR", None) except OSError: options["env"].pop("XDG_RUNTIME_DIR", None) options["headless"] = bool(config.get("headless", True)) proxy = config.get("proxy") if proxy: options["proxy"] = {"server": proxy} if isinstance(proxy, str) else copy.deepcopy(proxy) return options def search_request_matches(payload, task): """Only the current single-adult, one-way query is eligible for capture.""" if not isinstance(payload, dict): return False segments = payload.get("flightSegments") if not isinstance(segments, list) or len(segments) != 1 or not isinstance(segments[0], dict): return False segment = segments[0] if (segment.get("departureCityCode") != task["origin"]["code"] or segment.get("arrivalCityCode") != task["destination"]["code"] or segment.get("departureDate") != task["departure_date"]): return False return (type(payload.get("adultCount")) is int and payload["adultCount"] == 1 and type(payload.get("childCount")) is int and payload["childCount"] == 0 and type(payload.get("infantCount")) is int and payload["infantCount"] == 0 and payload.get("flightWay") == "S" and payload.get("cabin") == "Y_S_C_F") def resolve_city_payload(payload, requested_name): if (not isinstance(payload, dict) or payload.get("Status") != 0 or payload.get("Key") != requested_name or not isinstance(payload.get("Data"), list)): raise CrawlerError("protocol_changed", "City suggestions do not match the requested city") candidates = {} for entry in payload["Data"]: if not isinstance(entry, dict) or entry.get("Type") != 5 or entry.get("canSelect") is not True: continue if (not isinstance(entry.get("Code"), str) or not re.fullmatch(r"[A-Z]{3}", entry["Code"]) or not isinstance(entry.get("Name"), str) or not entry["Name"]): raise CrawlerError("protocol_changed", "City suggestion has an invalid identity") candidates[entry["Code"]] = entry exact = [entry for entry in candidates.values() if requested_name.casefold() in (entry["Name"].casefold(), str(entry.get("EName", "")).casefold(), entry["Code"].casefold())] choices = exact if exact else list(candidates.values()) if len(choices) != 1: raise CrawlerError("city_ambiguous", "City name is absent or ambiguous; use its precise city name") return {"code": choices[0]["Code"], "name": choices[0]["Name"]} def member_authenticated(payload): if not isinstance(payload, dict): return False status = payload.get("ResponseStatus") result = payload.get("result") return (isinstance(status, dict) and status.get("Ack") == "Success" and "Errors" in status and isinstance(status["Errors"], list) and not status["Errors"] and isinstance(result, dict) and type(result.get("resultCode")) is int and result["resultCode"] == 0) def is_member_summary_request(url, method): parsed = urlparse(url) return (parsed.scheme == "https" and parsed.hostname == "m.ctrip.com" and parsed.path == "/restapi/soa2/15201/getMemberSummaryInfo" and method == "POST") async def accept_login_agreement(page, timeout_ms): checkbox = page.locator("#checkboxAgreementInput") if not await checkbox.is_checked(timeout=timeout_ms): await page.locator('label[for="checkboxAgreementInput"]').click(timeout=timeout_ms) if not await checkbox.is_checked(timeout=timeout_ms): raise CrawlerError("auth_failed", "The login agreement was not selected") def comfort_target_aliases(rows): aliases = {} for row in rows: marketing = row.get("航班号") or row.get("flightNo") operating = row.get("实际承运航班号") or row.get("operateFlightNo") or marketing for number in (marketing, operating): if number: aliases.setdefault(number, set()).add(operating) return {number: next(iter(targets)) for number, targets in aliases.items() if len(targets) == 1} def comfort_request_key(payload, task): if (not isinstance(payload, dict) or payload.get("departureCityCode") != task["origin"]["code"] or payload.get("arrivalCityCode") != task["destination"]["code"] or payload.get("departureDate") != task["departure_date"]): return None numbers = payload.get("flightNoList") if not isinstance(numbers, list) or len(numbers) != 1 or not isinstance(numbers[0], str): return None digest = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest() return numbers[0], digest def comfort_request_identity(payload, task, aliases): key = comfort_request_key(payload, task) operating = aliases.get(key[0]) if key is not None else None if not operating: return None return operating, key[1] class SearchChain: """Track linked snapshots and pending notices until explicit completion.""" _SNAPSHOT_FIELDS = ("flightItineraryList", "currency", "currencyCode") def __init__(self, task): self.task = task self.search_id = None self.transaction_id = None self._snapshot = None @property def itineraries(self): return self._snapshot["flightItineraryList"] if self._snapshot is not None else None def matches_request(self, path, method, request_payload): if method != "POST" or not search_request_matches(request_payload, self.task): return False if self.search_id is None: if path != SEARCH_API_PATH: return False elif path != "/international/search/api/search/pull/" + self.search_id: return False transaction_id = request_payload.get("transactionID") if not isinstance(transaction_id, str) or not transaction_id: raise CrawlerError("protocol_changed", "Search request has no transaction identity") return self.search_id is None or transaction_id == self.transaction_id def accept(self, path, method, request_payload, http_status, payload): if not self.matches_request(path, method, request_payload): return None if http_status == 429: raise CrawlerError("rate_limited", "The search service requested a cooling period") if http_status >= 500: raise CrawlerError("network_error", "The search service is temporarily unavailable") if http_status != 200: raise CrawlerError("site_blocked", "The search response did not have a successful HTTP status") if not isinstance(payload, dict) or payload.get("status") != 0 or not isinstance(payload.get("data"), dict): raise CrawlerError("protocol_changed", "The search service did not return the expected business response") data = payload["data"] if data.get("needUserLogin") is True: raise CrawlerError("needs_auth", "The current search requires authentication") context = data.get("context") if isinstance(context, dict) and context.get("showAuthCode") is True: raise CrawlerError("challenge", "The current search requires human verification") if (not isinstance(context, dict) or type(context.get("finished")) is not bool or not isinstance(context.get("searchId"), str) or not context["searchId"]): raise CrawlerError("protocol_changed", "Search completion or itinerary structure is missing") if "flightItineraryList" in data: itineraries = data["flightItineraryList"] if not isinstance(itineraries, list): raise CrawlerError("protocol_changed", "Search itinerary structure is invalid") elif context["finished"] and self.itineraries is None: raise CrawlerError("protocol_changed", "Search response has no known itinerary snapshot") else: itineraries = None # A pending response may advance the poll chain before a snapshot arrives. self.transaction_id = request_payload["transactionID"] self.search_id = context["searchId"] # The site's SEARCH_FLIGHTS reducer retains a nonempty list when a # later pull carries no itineraries, while still applying isFinished. # Nonempty responses replace the snapshot; they are never appended. if itineraries is not None and (itineraries or self.itineraries is None): self._snapshot = {field: data[field] for field in self._SNAPSHOT_FIELDS if field in data} if not context["finished"]: return None if itineraries is not None and (itineraries or not self.itineraries): return payload completed = copy.deepcopy(payload) # The currency describes the retained quotes, so use the same response # for both instead of taking currency from the completion notice. for field in self._SNAPSHOT_FIELDS: completed["data"].pop(field, None) completed["data"].update(copy.deepcopy(self._snapshot)) self._snapshot = None return completed def _rate_limit_error(retry_after): delay = None if retry_after: try: delay = float(retry_after) except ValueError: from email.utils import parsedate_to_datetime try: delay = (parsedate_to_datetime(retry_after) - datetime.now(timezone.utc)).total_seconds() except (TypeError, ValueError, OverflowError): raise CrawlerError("protocol_changed", "The service supplied an invalid Retry-After header") if not math.isfinite(delay): raise CrawlerError("protocol_changed", "The service supplied an invalid Retry-After header") delay = max(0, delay) return CrawlerError("rate_limited", "The service requested a cooling period", retry_after=delay) def _comfort_outstanding(queue, traffic): return len(traffic["pending"]) + queue.qsize() + traffic["reading"] class BrowserSession: def __init__(self, config, identity, state, emit): self.config = config self.identity = identity self.state = state or {} self.emit = emit self.manager = None self.browser = None self.context = None self.challenge_page = None self.challenge_handle = None self.auth_checkpoint = None self.diagnostic_stage = 'startup.browser' async def start(self): self.diagnostic_stage = 'startup.browser' from camoufox.async_api import AsyncCamoufox self.manager = AsyncCamoufox(from_options=identity_launch_options(self.identity, self.config)) try: self.browser = await self.manager.__aenter__() options = {"locale": "zh-CN", "timezone_id": "Asia/Shanghai", "no_viewport": True, "ignore_https_errors": True} if self.state.get("storage_state"): options["storage_state"] = self.state["storage_state"] self.context = await self.browser.new_context(**options) except BaseException: await self.close() raise async def snapshot(self): return {"storage_state": await self.context.storage_state(indexed_db=True)} async def _read_json(self, response): if response.status == 429: raise _rate_limit_error(response.headers.get("retry-after")) if response.status >= 500: raise CrawlerError("network_error", "The target service is temporarily unavailable") if response.status != 200: raise CrawlerError("site_blocked", "The target interface did not return a successful HTTP status") from playwright.async_api import Error as BrowserError try: body = await response.body() except BrowserError as exc: # A 200 response only establishes headers. Correlate body transport # evidence with this request, not another failure on the page. failure = response.request.failure exc.diagnostic = {"network": { "response_body_failed": True, "response_request_failed": bool(failure), "response_request_error_code": firefox_error_code(failure) if failure else None, }} raise if len(body) > self.config.get("max_response_bytes", 32 * 1024 * 1024): raise CrawlerError("response_too_large", "A target response exceeds the configured size limit") try: return json.loads(body) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise CrawlerError("protocol_changed", "A target interface returned a non-JSON response") from exc async def resolve_cities(self, names): self.diagnostic_stage = 'resolve.page' page = await self.context.new_page() try: self.diagnostic_stage = 'resolve.navigation' await page.goto(CTRIP_HOME, wait_until="domcontentloaded", timeout=self.config.get("navigation_timeout", 30) * 1000) result = [] for name in names: self.diagnostic_stage = 'resolve.city_lookup' endpoint = "/international/search/api/poi/search?" + urlencode({"key": name, "filterAirport": "false"}) async with page.expect_response(lambda response: response.request.method == "GET" and response.url == "https://flights.ctrip.com" + endpoint, timeout=self.config.get("action_timeout", 10) * 1000) as response_info: await page.evaluate("endpoint => fetch(endpoint, {credentials: 'same-origin'}).then(() => null)", endpoint) payload = await self._read_json(await response_info.value) self.diagnostic_stage = 'resolve.normalize' result.append(resolve_city_payload(payload, name)) return result finally: await page.close() async def _collect_comfort(self, page, task, rows, queue, deadline, errors, traffic): from playwright.async_api import Error as BrowserError, TimeoutError as BrowserTimeout aliases = comfort_target_aliases(rows) targets = set(aliases.values()) values, readers, tails = {}, set(), {} traffic["aliases"] = aliases # Listeners start before the core result establishes eligible identities. for kind in ("sent", "received", "failed"): counts = {} for number, count in traffic[kind].items(): if number in aliases: operating = aliases[number] counts[operating] = counts.get(operating, 0) + count traffic[kind] = counts traffic["pending"] = {request: number for request, number in traffic["pending"].items() if number in aliases} early_limit = next((item for item in traffic["limits"].items() if item[0] in aliases), None) traffic["limits"] = dict([early_limit]) if early_limit is not None else {} attempted = set().union(*(traffic[kind] for kind in ("sent", "received", "failed"))) read_failure = None def action_ms(until): return max(1, min(self.config.get("action_timeout", 10), until - time.monotonic()) * 1000) def requested(number): return any(number in traffic[kind] for kind in ("sent", "received", "failed")) async def read(operating, response, previous): try: # Preserve response order for the same operating flight while # allowing another flight's body to finish independently. if previous is not None: await previous payload = await asyncio.wait_for(self._read_json(response), deadline - time.monotonic()) _record_comfort_values(values, operating, payload) except CrawlerError as exc: if exc.code == "rate_limited": raise errors.add(exc.code) except (ValueError, TypeError): errors.add("protocol_changed") except asyncio.TimeoutError: errors.add("response_body_timeout") except BrowserError: errors.add("network_error") def reader_done(job, operating): nonlocal read_failure readers.discard(job) traffic["reading"] -= 1 if tails.get(operating) is job: tails.pop(operating) if not job.cancelled(): read_failure = read_failure or job.exception() traffic["changed"].set() def check_health(): if traffic["limits"]: traffic["http_status"] = 429 raise _rate_limit_error(next(iter(traffic["limits"].values()))) if read_failure is not None: raise read_failure def pump_responses(): check_health() while not queue.empty() and time.monotonic() < deadline: number, response = queue.get_nowait() operating = aliases.get(number) if operating is None: continue traffic["http_status"] = response.status job = asyncio.create_task(read(operating, response, tails.get(operating))) traffic["reading"] += 1 readers.add(job) tails[operating] = job job.add_done_callback(lambda done, number=operating: reader_done(done, number)) async def wait_for_change(ready, until): while True: pump_responses() remaining = until - time.monotonic() if ready() or remaining <= 0: return traffic["changed"].clear() try: await asyncio.wait_for(traffic["changed"].wait(), remaining) except asyncio.TimeoutError: return def has_slot(): return _comfort_outstanding(queue, traffic) < queue.maxsize or traffic["truncated"] try: pump_responses() if targets - attempted and time.monotonic() < deadline and not traffic["truncated"]: locators = page.locator(".flight-item .plane-No") timeout_reason = "page_cards_timeout" try: await locators.first.wait_for(state="attached", timeout=action_ms(deadline)) index = 0 while time.monotonic() < deadline and not traffic["truncated"]: await wait_for_change(has_slot, deadline) now = time.monotonic() if now >= deadline or traffic["truncated"]: break count = await locators.count() if index >= count: if all(requested(number) for number in targets): break timeout_reason = "page_pagination_timeout" await locators.last.scroll_into_view_if_needed(timeout=action_ms(deadline)) box = await locators.last.bounding_box(timeout=action_ms(deadline)) if box is None: errors.add("page_details_not_loaded") break pump_responses() await page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) await page.mouse.wheel(0, 700) await page.wait_for_function( "count => document.querySelectorAll('.flight-item .plane-No').length > count", arg=count, timeout=action_ms(deadline)) continue # Give remaining targets a bounded chance to expose an # interactive card, including later marketing aliases. card_deadline = now + min(self.config.get("action_timeout", 10), (deadline - now) / max(1, len(targets) - len(attempted))) locator = locators.nth(index) index += 1 try: number = await locator.evaluate( "el => Array.from(el.childNodes).filter(n => n.nodeType === 3).map(n => n.textContent).join('').trim()", timeout=action_ms(card_deadline)) except BrowserTimeout: errors.add("page_card_read_timeout") continue operating = aliases.get(number) if operating is None or requested(operating): continue attempted.add(operating) for _ in range(2): await wait_for_change(has_slot, card_deadline) if requested(operating) or time.monotonic() >= card_deadline or traffic["truncated"]: break try: await page.mouse.move(0, 0) pump_responses() await locator.hover(timeout=action_ms(card_deadline)) except BrowserTimeout: errors.add("page_hover_timeout") continue # Native hover delays need the existing action # timeout even when many targets remain unvisited. request_deadline = min(deadline, time.monotonic() + self.config.get("action_timeout", 10)) await wait_for_change(lambda: requested(operating) or traffic["truncated"], request_deadline) if not requested(operating): errors.add("page_hover_no_request") break except BrowserTimeout: errors.add(timeout_reason) except BrowserError: errors.add("network_error") await wait_for_change(lambda: not _comfort_outstanding(queue, traffic), deadline) pump_responses() finally: if time.monotonic() >= deadline: if any(not job.done() for job in readers): errors.add("response_body_timeout") if traffic["pending"]: errors.add("response_wait_timeout") active = tuple(readers) for job in active: job.cancel() outcomes = await asyncio.gather(*active, return_exceptions=True) check_health() # A completed reader may be gathered before its done callback runs. for outcome in outcomes: if isinstance(outcome, BaseException) and not isinstance(outcome, asyncio.CancelledError): raise outcome if traffic["failed"]: errors.add("network_error") if time.monotonic() >= deadline and (targets - values.keys() or traffic["pending"] or not queue.empty()): errors.add("comfort_budget_exhausted") result = _merge_comfort_rows(rows, values) result["comfort_summary"].update( requested_flights=len(traffic["sent"]), responded_flights=len(traffic["received"]), requests_sent=sum(traffic["sent"].values()), responses_received=sum(traffic["received"].values()), truncated=traffic["truncated"]) if errors and result["comfort_status"] in ("partial", "unavailable"): result["comfort_reason"] = ";".join(sorted(errors | {result["comfort_reason"]})) return result async def collect(self, task, deadline_seconds): from playwright.async_api import Error as BrowserError self.diagnostic_stage = 'collect.page' page = await self.context.new_page() queue = asyncio.Queue(maxsize=self.config.get("max_candidates", 64)) comfort_queue = asyncio.Queue(maxsize=self.config.get("max_candidates", 64)) comfort_errors = set() traffic = {"sent": {}, "received": {}, "failed": {}, "limits": {}, "pending": {}, "aliases": None, "reading": 0, "http_status": None, "changed": asyncio.Event(), "truncated": False} capacity = self.config.get("max_candidates", 64) # Before the core result arrives, a flight can be named by either its # marketing or operating number. The queue bounds live response work, # independently of how many eligible flights the result contains. identity_capacity = 2 * self.config.get("max_rows", 20000) network = {"search_responses_received": 0, "failed_request_count": 0, "request_failed": False} statuses = {"navigation": None, "search": None} navigation_url = None overflow = False chain = SearchChain(task) final_payload = None deadline = time.monotonic() + deadline_seconds retain_challenge = False def request_kind(request): parsed = urlparse(request.url) if parsed.hostname != "flights.ctrip.com": return None if request.url == navigation_url and request.method == "GET": return "navigation" if parsed.path == SEARCH_API_PATH or parsed.path.startswith("/international/search/api/search/pull/"): return "search" if parsed.path == "/international/search/api/flight/comfort/getFlightComfort": return "comfort" return None def comfort_key(request): if request.method != "POST" or request_kind(request) != "comfort": return None try: key = comfort_request_key(request.post_data_json, task) return key[0] if key is not None else None except (BrowserError, ValueError, TypeError, KeyError): return None def truncate_comfort(): traffic["truncated"] = True comfort_errors.add("response_too_large") traffic["changed"].set() def track(kind, number): if traffic["aliases"] is not None: number = traffic["aliases"].get(number) if number is None: return False values = traffic[kind] if number not in values and len(values) >= identity_capacity: truncate_comfort() return False values[number] = values.get(number, 0) + 1 traffic["changed"].set() return True def receive_request(request): if self.config.get("comft_flight"): key = comfort_key(request) if key is not None and track("sent", key): if _comfort_outstanding(comfort_queue, traffic) >= capacity: truncate_comfort() else: traffic["pending"][request] = key def receive_failed(request): if request_kind(request) is None: return network["request_failed"] = True network["failed_request_count"] += 1 if self.config.get("comft_flight"): key = comfort_key(request) if key is not None: traffic["pending"].pop(request, None) track("failed", key) def annotate(error): kind = "navigation" if self.diagnostic_stage == "collect.navigation" else ( "comfort" if self.diagnostic_stage == "collect.comfort" else "search") status = traffic["http_status"] if kind == "comfort" else statuses[kind] diagnostic = dict(getattr(error, "diagnostic", {}) or {}) diagnostic.update(stage=self.diagnostic_stage, network={**network, **diagnostic.get("network", {}), "response_kind": kind, "method": "GET" if kind == "navigation" else "POST", "http_status": status}) error.diagnostic = diagnostic return error def receive(response): nonlocal overflow parsed = urlparse(response.url) if parsed.hostname != "flights.ctrip.com": return path = parsed.path if path == SEARCH_API_PATH or path.startswith("/international/search/api/search/pull/"): network["search_responses_received"] += 1 try: queue.put_nowait(response) except asyncio.QueueFull: overflow = True elif self.config.get("comft_flight") and path == "/international/search/api/flight/comfort/getFlightComfort": key = comfort_key(response.request) if key is None: return traffic["pending"].pop(response.request, None) if response.status == 429: aliases, limits = traffic["aliases"], traffic["limits"] if aliases is None: if key in limits or len(limits) < identity_capacity: limits.setdefault(key, response.headers.get("retry-after")) else: truncate_comfort() elif key in aliases and not limits: limits[key] = response.headers.get("retry-after") track("received", key) return if not track("received", key): return if _comfort_outstanding(comfort_queue, traffic) >= capacity: truncate_comfort() return try: comfort_queue.put_nowait((key, response)) except asyncio.QueueFull: truncate_comfort() page.on("request", receive_request) page.on("requestfailed", receive_failed) page.on("response", receive) try: url = ("https://flights.ctrip.com/online/list/oneway-" + task["origin"]["code"].lower() + "-" + task["destination"]["code"].lower() + "?" + urlencode({ "depdate": task["departure_date"], "cabin": "y_s_c_f", "adult": 1, "child": 0, "infant": 0})) navigation_url = url self.diagnostic_stage = 'collect.navigation' navigation = await page.goto(url, wait_until="commit", timeout=max(1, min( self.config.get("navigation_timeout", 30), deadline - time.monotonic()) * 1000)) if navigation is not None: statuses["navigation"] = navigation.status if navigation.status >= 400: await self._read_json(navigation) while final_payload is None: self.diagnostic_stage = 'collect.wait_response' if overflow: raise CrawlerError("response_too_large", "The target response queue exceeded its capacity") remaining = deadline - time.monotonic() - 10 if remaining <= 0: raise CrawlerError("response_timeout", "The search did not reach its explicit completion state") response = await asyncio.wait_for(queue.get(), remaining) path = urlparse(response.url).path try: request_payload = response.request.post_data_json except (BrowserError, ValueError, TypeError, KeyError): request_payload = None if not chain.matches_request(path, response.request.method, request_payload): continue statuses["search"] = response.status self.diagnostic_stage = 'collect.decode_response' payload = await self._read_json(response) self.diagnostic_stage = 'collect.protocol' data = payload.get('data') if isinstance(payload, dict) else None context = data.get('context') if isinstance(data, dict) else None context = context if isinstance(context, dict) else {} items = data.get('flightItineraryList') if isinstance(data, dict) else None transaction = request_payload.get('transactionID') search_id = context.get('searchId') summary = { 'http_status': response.status, 'business_status': payload.get('status') if isinstance(payload, dict) else None, 'finished': context.get('finished') if type(context.get('finished')) is bool else None, 'finished_type': type(context['finished']).__name__ if 'finished' in context else 'missing', 'list_present': isinstance(data, dict) and 'flightItineraryList' in data, 'list_type': type(items).__name__ if isinstance(data, dict) and 'flightItineraryList' in data else 'missing', 'list_count': len(items) if isinstance(items, list) else None, 'known_snapshot': chain.itineraries is not None, 'request_matches': True, 'transaction_present': bool(transaction), 'transaction_matches': transaction == chain.transaction_id if chain.transaction_id is not None else None, 'search_id_present': bool(search_id), 'search_id_matches': search_id == chain.search_id if chain.search_id is not None else None, } try: final_payload = chain.accept(path, response.request.method, request_payload, response.status, payload) except CrawlerError as exc: exc.diagnostic.update(stage=self.diagnostic_stage, protocol=summary) raise observed_at = datetime.now(timezone.utc).isoformat() self.diagnostic_stage = 'collect.normalize' observation = normalize_response(final_payload, task, self.config, observed_at) if self.config.get("comft_flight"): self.diagnostic_stage = 'collect.comfort' comfort_deadline = min(deadline - 10, time.monotonic() + self.config.get("comfort_timeout", 15)) observation.update(await self._collect_comfort(page, task, observation["rows"], comfort_queue, comfort_deadline, comfort_errors, traffic)) return observation except (CrawlerError, BrowserError) as exc: annotate(exc) if isinstance(exc, CrawlerError) and exc.code == "challenge" and self.config.get("challenge_policy") == "wait_then_switch": self.challenge_page = page self.challenge_handle = uuid.uuid4().hex self.challenge_expires_at = time.monotonic() + 10 exc.challenge_handle = self.challenge_handle retain_challenge = True raise except asyncio.TimeoutError as exc: raise annotate(CrawlerError("response_timeout", "No complete response arrived before the attempt deadline")) from exc finally: page.remove_listener("request", receive_request) page.remove_listener("requestfailed", receive_failed) page.remove_listener("response", receive) if not retain_challenge: await page.close() async def authenticate(self, account, timeout, challenge_handle=None): from playwright.async_api import TimeoutError as BrowserTimeout self.diagnostic_stage = 'auth.prepare' self.auth_checkpoint = None if not account: raise CrawlerError("needs_auth", "Authentication requires a configured account") page = None transferred_challenge = False if self.challenge_page: if (challenge_handle in (None, self.challenge_handle) and time.monotonic() <= self.challenge_expires_at): page = self.challenge_page transferred_challenge = True else: await self.challenge_page.close() self.challenge_page = None self.challenge_handle = None page = page or await self.context.new_page() deadline = time.monotonic() + timeout authenticated = asyncio.Event() member_seen = asyncio.Event() member_failure = None jobs = set() checkpoint_at = 0.0 def check_member_failure(): if member_failure is not None: raise member_failure def action_timeout(): check_member_failure() remaining = deadline - time.monotonic() if remaining <= 0: raise CrawlerError("auth_timeout", "The authentication operation reached its deadline") return min(self.config.get("action_timeout", 10), remaining) * 1000 async def check_member(response): nonlocal member_failure if not is_member_summary_request(response.url, response.request.method): return try: if response.status in (200, 429) and member_authenticated(await self._read_json(response)): authenticated.set() except CrawlerError as exc: if response.status == 429: member_failure = exc except ValueError: return finally: member_seen.set() def receive_member(response): if is_member_summary_request(response.url, response.request.method): job = asyncio.create_task(check_member(response)) jobs.add(job) job.add_done_callback(jobs.discard) self.context.on("response", receive_member) try: if not transferred_challenge: self.diagnostic_stage = 'auth.session_check' await page.goto(CTRIP_HOME, wait_until="domcontentloaded", timeout=min( self.config.get("navigation_timeout", 30), max(1, deadline - time.monotonic())) * 1000) try: await asyncio.wait_for(member_seen.wait(), min(5, max(0.01, deadline - time.monotonic()))) except asyncio.TimeoutError: pass check_member_failure() if authenticated.is_set(): return {"authenticated": True} if self.config.get("headless", True) and not account.get("password"): raise CrawlerError("needs_auth", "The saved session is not valid; headless login requires a password") login_url = "https://passport.ctrip.com/user/login?" + urlencode({"BackUrl": CTRIP_HOME}) self.diagnostic_stage = 'auth.login' await page.goto(login_url, wait_until="domcontentloaded", timeout=min( self.config.get("navigation_timeout", 30), max(1, deadline - time.monotonic())) * 1000) if account.get("username") and account.get("password"): panel = page.locator('[data-testid="accountPanel"]') await panel.wait_for(state="visible", timeout=action_timeout()) await panel.locator('[data-testid="accountNameInput"]').fill(account["username"], timeout=action_timeout()) await panel.locator('[data-testid="passwordInput"]').fill(account["password"], timeout=action_timeout()) await accept_login_agreement(page, action_timeout()) await panel.locator('[data-testid="loginButton"]').click(timeout=action_timeout()) self.diagnostic_stage = 'auth.wait_verification' while time.monotonic() < deadline: check_member_failure() if authenticated.is_set(): return {"authenticated": True} challenge_visible = await page.locator('#sc_mobilevalidate').is_visible() if time.monotonic() >= checkpoint_at: self.auth_checkpoint = {"state": await self.snapshot(), "confirmed": False, "challenge_visible": challenge_visible} if self.emit: self.emit('auth_checkpoint', self.auth_checkpoint) checkpoint_at = time.monotonic() + 5 if challenge_visible: if self.config.get("headless", True) or self.config.get("challenge_policy") == "switch": raise CrawlerError("challenge", "Login requires manual verification") await asyncio.sleep(min(0.25, max(0, deadline - time.monotonic()))) raise CrawlerError("auth_timeout", "Login was not confirmed before the authentication deadline") except BrowserTimeout as exc: raise CrawlerError("auth_timeout", "A login page operation did not complete before its deadline") from exc finally: self.context.remove_listener("response", receive_member) for job in jobs: job.cancel() if jobs: await asyncio.gather(*jobs, return_exceptions=True) try: self.auth_checkpoint = {"state": await self.snapshot(), "confirmed": authenticated.is_set()} except Exception as exc: if authenticated.is_set(): raise CrawlerError("session_snapshot_failed", "Authenticated state could not be captured") from exc finally: await page.close() async def close(self): try: if self.context: await self.context.close() finally: self.context = None if self.manager: await self.manager.__aexit__(None, None, None) self.manager = None self.browser = None # ================ worker ================ def _enable_child_subreaper(): """Keep orphaned owned browser descendants reapable by this supervisor.""" if sys.platform != 'linux': return import ctypes libc = ctypes.CDLL(None, use_errno=True) if libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER raise CrawlerError('process_cleanup', '无法建立 Linux 自有子进程回收边界') class _ParentConnection: """Closing a POSIX pipe must also interrupt another thread blocked in recv.""" def __init__(self, connection): self._connection = connection def send_bytes(self, *args, **kwargs): return self._connection.send_bytes(*args, **kwargs) def recv_bytes(self, *args, **kwargs): return self._connection.recv_bytes(*args, **kwargs) def close(self): if self._connection.closed: return if os.name == 'posix': import socket # multiprocessing's POSIX duplex Pipe is a socketpair. Shutdown # wakes the reader thread; merely closing its FD can leave the # underlying socket referenced by a blocked recv indefinitely. try: duplicate = socket.fromfd(self._connection.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) try: duplicate.shutdown(socket.SHUT_RDWR) finally: duplicate.close() except OSError: pass # Already disconnected; close the original handle below. self._connection.close() @contextlib.contextmanager def _linux_pidfd(pid): descriptor = os.pidfd_open(pid, 0) try: yield descriptor finally: os.close(descriptor) def _wait_linux_process_exit(descriptors, timeout): """Observe whole thread-group exit, then reap only waitable children.""" import select pending = set(descriptors) poller = select.poll() for descriptor in pending: poller.register(descriptor, select.POLLIN) deadline = time.monotonic() + timeout while pending: milliseconds = math.ceil(max(0.0, deadline - time.monotonic()) * 1000) for descriptor, events in poller.poll(milliseconds): if not events & (select.POLLIN | select.POLLHUP): raise CrawlerError('process_cleanup', '无法观察自有进程的终止状态') try: os.waitid(os.P_PIDFD, descriptor, os.WEXITED | os.WNOHANG) except ChildProcessError: pass # The real parent owns this exited process's status. pending.remove(descriptor) poller.unregister(descriptor) if time.monotonic() >= deadline: break return pending def check_process_environment(): if sys.platform != 'linux': return try: with _linux_pidfd(os.getpid()) as descriptor: signal.pidfd_send_signal(descriptor, 0, None, 0) _wait_linux_process_exit({descriptor}, 0) try: os.waitid(os.P_PIDFD, descriptor, os.WEXITED | os.WNOHANG) except ChildProcessError: pass # A process cannot reap itself. The kernel accepted P_PIDFD. except (AttributeError, OSError) as exc: raise CrawlerError('environment_invalid', 'Linux 进程清理需要允许 pidfd_open、pidfd_send_signal、poll 和 waitid(P_PIDFD)') from exc def _terminate_linux_processes(identities, timeout): import psutil try: with contextlib.ExitStack() as resources: descriptors = set() for pid, created in reversed(list(identities.items())): try: process = psutil.Process(int(pid)) if process.create_time() != created: continue descriptor = resources.enter_context(_linux_pidfd(process.pid)) # Confirm that the descriptor bound the validated identity. if process.is_running(): descriptors.add(descriptor) except (psutil.NoSuchProcess, ProcessLookupError): continue pending = _wait_linux_process_exit(descriptors, 0) for signum in (signal.SIGTERM, signal.SIGKILL): for descriptor in pending: try: signal.pidfd_send_signal(descriptor, signum, None, 0) except ProcessLookupError: pass # A bound process may exit before the signal. pending = _wait_linux_process_exit(pending, timeout) if pending: raise CrawlerError('process_cleanup', '自有浏览器进程未能在关闭期限内退出') except (AttributeError, OSError, psutil.AccessDenied) as exc: raise CrawlerError('process_cleanup', '无法确认自有进程是否已经终止') from exc def _terminate_owned_processes(identities, timeout=2.0): if sys.platform == 'linux': return _terminate_linux_processes(identities, timeout) import psutil processes = [] for pid, created in reversed(list(identities.items())): try: process = psutil.Process(int(pid)) if process.create_time() == created: process.terminate() processes.append(process) except psutil.NoSuchProcess: continue except psutil.AccessDenied as exc: raise CrawlerError('process_cleanup', '无法终止当前运行拥有的进程') from exc _, alive = psutil.wait_procs(processes, timeout=timeout) for process in alive: try: process.kill() except psutil.NoSuchProcess: pass _, alive = psutil.wait_procs(alive, timeout=timeout) if alive: raise CrawlerError('process_cleanup', '自有浏览器进程未能在关闭期限内退出') def _windows_worker_job(): """Bind browser descendants to worker lifetime, even if Python is killed.""" if os.name != 'nt': return None import ctypes from ctypes import wintypes class BasicLimits(ctypes.Structure): _fields_ = [('PerProcessUserTimeLimit', ctypes.c_longlong), ('PerJobUserTimeLimit', ctypes.c_longlong), ('LimitFlags', wintypes.DWORD), ('MinimumWorkingSetSize', ctypes.c_size_t), ('MaximumWorkingSetSize', ctypes.c_size_t), ('ActiveProcessLimit', wintypes.DWORD), ('Affinity', ctypes.c_size_t), ('PriorityClass', wintypes.DWORD), ('SchedulingClass', wintypes.DWORD)] class IoCounters(ctypes.Structure): _fields_ = [(name, ctypes.c_ulonglong) for name in ( 'ReadOperationCount', 'WriteOperationCount', 'OtherOperationCount', 'ReadTransferCount', 'WriteTransferCount', 'OtherTransferCount')] class ExtendedLimits(ctypes.Structure): _fields_ = [('BasicLimitInformation', BasicLimits), ('IoInfo', IoCounters), ('ProcessMemoryLimit', ctypes.c_size_t), ('JobMemoryLimit', ctypes.c_size_t), ('PeakProcessMemoryUsed', ctypes.c_size_t), ('PeakJobMemoryUsed', ctypes.c_size_t)] kernel = ctypes.WinDLL('kernel32', use_last_error=True) kernel.CreateJobObjectW.restype = wintypes.HANDLE kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR] kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD] kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] kernel.GetCurrentProcess.restype = wintypes.HANDLE kernel.CloseHandle.argtypes = [wintypes.HANDLE] job = kernel.CreateJobObjectW(None, None) limits = ExtendedLimits() limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE if not job or not kernel.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)) or not kernel.AssignProcessToJobObject(job, kernel.GetCurrentProcess()): if job: kernel.CloseHandle(job) raise CrawlerError('process_cleanup', '无法建立 Windows 子进程生命周期边界') # Keep the raw handle open until this process exits; closing kills this job. return job def _worker_failure_code(error, *, startup=False): if isinstance(error, CrawlerError): return error.code if isinstance(error, (asyncio.TimeoutError, TimeoutError)): return 'response_timeout' try: from playwright.async_api import Error as BrowserError, TimeoutError as BrowserTimeout except ImportError: return 'worker_error' if isinstance(error, BrowserTimeout): return 'response_timeout' if isinstance(error, BrowserError): # Firefox HTTP CONNECT errors: nsHttp::HttpProxyResponseToErrorCode; # transport / DNS symbols: xpcom/base/ErrorList.py. Match exact engine # symbols only: a target HTTP 403 is not a proxy-authentication failure. symbol = firefox_error_code(error) if symbol in ('NS_ERROR_PROXY_UNAUTHORIZED', 'NS_ERROR_PROXY_FORBIDDEN', 'NS_ERROR_PROXY_AUTHENTICATION_FAILED', 'NS_ERROR_PROXY_NETWORK_AUTHENTICATION_REQUIRED'): return 'proxy_access_denied' if symbol in ('NS_ERROR_PROXY_CONNECTION_REFUSED', 'NS_ERROR_UNKNOWN_PROXY_HOST', 'NS_ERROR_PROXY_REQUEST_TIMEOUT', 'NS_ERROR_PROXY_GATEWAY_TIMEOUT', 'NS_ERROR_PROXY_BAD_GATEWAY', 'NS_ERROR_PROXY_TOO_MANY_REQUESTS'): return 'proxy_unavailable' if symbol in ('NS_ERROR_CONNECTION_REFUSED', 'NS_ERROR_NET_TIMEOUT', 'NS_ERROR_NET_RESET', 'NS_ERROR_NET_INTERRUPT', 'NS_ERROR_UNKNOWN_HOST', 'NS_ERROR_DEFINITIVE_UNKNOWN_HOST', 'NS_ERROR_OFFLINE'): return 'network_error' return 'browser_startup' if startup else 'browser_error' return 'worker_error' def worker_main(connection, config, identity, state): signal.signal(signal.SIGINT, signal.SIG_IGN) if hasattr(signal, 'SIGBREAK'): signal.signal(signal.SIGBREAK, signal.SIG_IGN) job = None messages = queue.Queue(maxsize=2) disconnected = threading.Event() envelope = config['envelope'] send_lock = threading.Lock() def send(kind, value=None, command=None, **extra): packet = {**envelope, **({k: command[k] for k in ('operation_id', 'attempt_id', 'auth_id', 'run_id', 'task_key', 'task_index') if k in command} if command else {}), 'type': kind, 'value': value, **extra} raw = json.dumps(packet, ensure_ascii=False, allow_nan=False).encode('utf-8') limit = 8 * 1024 * 1024 if kind in ('session', 'profile', 'auth_checkpoint') else config['max_result_bytes'] if len(raw) > limit: raise CrawlerError('result_too_large', '工作进程结果超过通信上限') with send_lock: connection.send_bytes(raw) def read_commands(): try: while True: packet = json.loads(connection.recv_bytes(64 * 1024)) if not isinstance(packet, dict): raise ValueError('command') messages.put(packet, timeout=2) except (EOFError, OSError, ValueError, queue.Full): disconnected.set() # Control-channel loss is sufficient: Windows can retain the old # parent PID after parent exit, and the event loop may be blocked. try: import psutil owned = {p.pid: p.create_time() for p in psutil.Process().children(recursive=True)} _terminate_owned_processes(owned, timeout=min(2, config['close_timeout'])) finally: os._exit(4) async def next_command(): while not disconnected.is_set(): try: return messages.get_nowait() except queue.Empty: await asyncio.sleep(0.05) raise EOFError async def run(): nonlocal identity, job session = None stage = 'startup.process_boundary' try: job = _windows_worker_job() if identity is None: stage = 'startup.identity' identity = await asyncio.to_thread(generate_identity, config) send('profile', identity) ack = await next_command() if ack.get('type') != 'profile_accepted': raise CrawlerError('ipc_invalid', '会话身份尚未保存') active_command = None def emit_browser(kind, value): if kind == 'auth_checkpoint' and active_command and active_command.get('type') == 'auth': send(kind, value, active_command) session = BrowserSession(config, identity, state, emit_browser) stage = 'startup.browser' await session.start() send('ready') snapshot_sequence = 0 while True: command = await next_command() active_command = command if command.get('type') == 'shutdown': break if any(command.get(k) != envelope[k] for k in ('worker_generation', 'account_alias', 'binding_epoch')): raise CrawlerError('ipc_invalid', '工作进程账号绑定不匹配') try: kind = command['type'] stage = kind timeout = command['timeout'] if kind == 'resolve': value = await asyncio.wait_for(session.resolve_cities(command['value']['names']), timeout) elif kind == 'collect': value = await asyncio.wait_for(session.collect(command['value']['task'], timeout), timeout) elif kind == 'auth': value = await asyncio.wait_for(session.authenticate(command['value']['account'], timeout), timeout) else: raise CrawlerError('ipc_invalid', '不支持的工作进程命令') stage = 'session.snapshot' snapshot = await session.snapshot() snapshot_sequence += 1 send('session', {'identity': identity, 'state': snapshot}, command, snapshot_sequence=snapshot_sequence) send('result', value, command, snapshot_sequence=snapshot_sequence) except Exception as exc: checkpoint = getattr(session, 'auth_checkpoint', None) if command.get('type') == 'auth' and checkpoint: send('auth_checkpoint', checkpoint, command) failure_stage = getattr(session, 'diagnostic_stage', kind) if stage == kind else stage diagnostic = make_diagnostic(exc, stage=failure_stage, config=config, command=command) send('failure', command=command, code=_worker_failure_code(exc), message=diagnostic['message'], retry_after=getattr(exc, 'retry_after', None), diagnostic=diagnostic) except EOFError: pass except Exception as exc: try: diagnostic = make_diagnostic(exc, stage=stage, config=config) send('startup_failure', code=_worker_failure_code(exc, startup=True), message=diagnostic['message'], diagnostic=diagnostic) except (OSError, EOFError): pass finally: if session: try: await asyncio.wait_for(session.close(), config['close_timeout']) except (Exception, asyncio.CancelledError): # Parent owns the final process-tree cleanup after grace. pass try: send('stopped') except (OSError, EOFError): pass reader = threading.Thread(target=read_commands, daemon=True, name='ctrip-command-reader') reader.start() try: asyncio.run(run()) finally: disconnected.set() connection.close() class WorkerClient: """One supervised worker; no browser objects or blocking pipe I/O on parent.""" def __init__(self, config, identity, state, *, generation, alias=None, on_profile=None, on_session=None, on_checkpoint=None, owner_path=None, target=None): self.config = copy.deepcopy(config) self.generation = generation self.envelope = {'protocol_version': 1, 'worker_generation': generation, 'account_alias': alias, 'binding_epoch': generation} self.config['envelope'] = self.envelope self.config['parent_pid'] = os.getpid() self.identity, self.state = identity, state self.on_profile, self.on_session = on_profile, on_session self.on_checkpoint = on_checkpoint self.owner_path = owner_path self.target = target or worker_main self.context = multiprocessing.get_context('spawn') _enable_child_subreaper() parent_connection, self.child_connection = self.context.Pipe() self.connection = _ParentConnection(parent_connection) self.process = self.context.Process(target=self.target, args=(self.child_connection, self.config, identity, state), name='ctrip-browser') self.incoming = queue.Queue(maxsize=1) self.outgoing = queue.Queue(maxsize=1) self.stop_event = threading.Event() self.identities = {} self.threads = [] self.last_sample = 0.0 self.closed = False self.snapshot_sequence = 0 def __enter__(self): return self def __exit__(self, *_): self.close() def _deliver(self, value): while not self.stop_event.is_set(): try: self.incoming.put(value, timeout=0.1) return except queue.Full: continue def _receive(self): try: while not self.stop_event.is_set(): raw = self.connection.recv_bytes(self.config['max_result_bytes']) value = json.loads(raw) if not isinstance(value, dict): raise ValueError('message') self._deliver(value) except (OSError, EOFError, ValueError) as exc: self._deliver({'type': 'channel_closed', 'diagnostic': make_diagnostic(exc, stage='ipc.receive', config=self.config)}) def _send(self): try: while not self.stop_event.is_set(): try: value = self.outgoing.get(timeout=0.1) except queue.Empty: continue self.connection.send_bytes(value) except (OSError, EOFError) as exc: self._deliver({'type': 'channel_closed', 'diagnostic': make_diagnostic(exc, stage='ipc.send', config=self.config)}) def send(self, kind, value=None, **extra): packet = {**self.envelope, 'type': kind, 'value': value, **extra} raw = json.dumps(packet, ensure_ascii=False, allow_nan=False).encode('utf-8') if len(raw) > 64 * 1024: raise CrawlerError('ipc_invalid', '命令超过通信上限') try: self.outgoing.put_nowait(raw) except queue.Full as exc: raise CrawlerError('ipc_blocked', '命令发送通道阻塞') from exc def _sample(self, enforce_limit=True): import psutil if time.monotonic() - self.last_sample < 0.5: return self.last_sample = time.monotonic() try: parent = psutil.Process(self.process.pid) processes = [parent, *parent.children(recursive=True)] total = 0 changed = False for process in processes: try: created = process.create_time() if self.identities.get(process.pid) != created: self.identities[process.pid] = created changed = True total += process.memory_info().rss except psutil.NoSuchProcess: continue if self.owner_path and changed: atomic_json(self.owner_path, {'owner_pid': os.getpid(), 'processes': self.identities}) if enforce_limit and total > self.config['memory_limit_mb'] * 1024 * 1024: raise CrawlerError('memory_limit', '浏览器进程树超过内存上限') except psutil.NoSuchProcess: return def _next(self, deadline): while time.monotonic() < deadline: self._sample() try: packet = self.incoming.get(timeout=min(0.1, max(0.001, deadline - time.monotonic()))) except queue.Empty: if not self.process.is_alive(): raise CrawlerError('worker_crashed', '浏览器工作进程已退出') continue if time.monotonic() >= deadline: break if packet.get('type') == 'channel_closed': raise CrawlerError('ipc_closed', '浏览器通信连接已关闭', diagnostic=packet.get('diagnostic')) if any(packet.get(k) != v for k, v in self.envelope.items()): raise CrawlerError('ipc_invalid', '拒绝账号或代次不匹配的消息') return packet raise CrawlerError('worker_timeout', '工作进程未在截止时间内返回完整结果') def start(self, timeout=None): self.process.start() self.child_connection.close() for target in (self._receive, self._send): thread = threading.Thread(target=target, daemon=True) thread.start() self.threads.append(thread) deadline = time.monotonic() + (timeout or self.config['startup_timeout']) while True: packet = self._next(deadline) if packet['type'] == 'profile': self.identity = packet['value'] if not self.on_profile: raise CrawlerError('state_invalid', '缺少会话身份保存处理器') self.on_profile(self.identity) self.send('profile_accepted') elif packet['type'] == 'ready': return elif packet['type'] == 'startup_failure': raise CrawlerError(packet['code'], packet['message'], diagnostic=packet.get('diagnostic')) else: raise CrawlerError('ipc_invalid', '启动期间收到无效消息') def call(self, kind, value, *, timeout, attempt_id=None, auth_id=None): operation = uuid.uuid4().hex starting_sequence = self.snapshot_sequence extra = {'operation_id': operation, 'timeout': timeout} if attempt_id: extra['attempt_id'] = attempt_id if auth_id: extra['auth_id'] = auth_id if kind == 'collect': task = value['task'] extra.update(run_id=task['run_id'], task_key=task['key'], task_index=task['index']) self.send(kind, value, **extra) deadline = time.monotonic() + timeout while True: packet = self._next(deadline) if packet.get('operation_id') != operation: raise CrawlerError('ipc_invalid', '拒绝迟到的操作结果') for key in ('attempt_id', 'auth_id', 'run_id', 'task_key', 'task_index'): if key in extra and packet.get(key) != extra[key]: raise CrawlerError('ipc_invalid', '拒绝任务或认证身份不符的结果') if packet['type'] == 'auth_checkpoint': if kind != 'auth': raise CrawlerError('ipc_invalid', '非认证操作不能更新认证候选状态') if self.on_checkpoint: self.on_checkpoint(packet['value']) elif packet['type'] == 'session': sequence = packet.get('snapshot_sequence') if sequence != self.snapshot_sequence + 1: raise CrawlerError('ipc_invalid', '认证快照序号不连续') self.state = packet['value']['state'] if self.on_session: self.on_session(packet['value']) self.snapshot_sequence = sequence elif packet['type'] == 'result': if (self.snapshot_sequence <= starting_sequence or packet.get('snapshot_sequence') != self.snapshot_sequence): raise CrawlerError('ipc_invalid', '结果引用了未持久保存的认证快照') return packet['value'] elif packet['type'] == 'failure': raise CrawlerError(packet['code'], packet['message'], retry_after=packet.get('retry_after'), diagnostic=packet.get('diagnostic')) else: raise CrawlerError('ipc_invalid', '收到未知操作响应') def close(self): if self.closed: return self.closed = True cleanup_error = None if self.process.pid: try: try: # Do not let rate limiting hide a just-created descendant. self.last_sample = 0.0 self._sample(enforce_limit=False) except Exception as exc: cleanup_error = exc if self.process.is_alive(): try: self.send('shutdown') except CrawlerError: pass self.process.join(self.config['close_timeout']) # multiprocessing alone owns waitpid/reaping for this process. # psutil.wait_procs on it steals the exit status on POSIX and # leaves multiprocessing.Process.is_alive() permanently true. if self.process.is_alive(): self.process.terminate() self.process.join(timeout=min(2, self.config['close_timeout'])) if self.process.is_alive(): self.process.kill() self.process.join(timeout=2) if self.process.is_alive(): raise CrawlerError('process_cleanup', '工作进程未能在关闭期限内退出') descendants = {pid: created for pid, created in self.identities.items() if int(pid) != self.process.pid} _terminate_owned_processes(descendants, timeout=min(2, self.config['close_timeout'])) except Exception as exc: cleanup_error = exc if self.process.is_alive(): self.process.kill() self.process.join(timeout=2) self.stop_event.set() self.connection.close() self.child_connection.close() for thread in self.threads: thread.join(timeout=1) if any(t.is_alive() for t in self.threads): raise CrawlerError('ipc_cleanup', '通信线程未退出,停止运行以避免泄漏') if cleanup_error: raise cleanup_error # ================ main ================ RECOVERABLE_FAILURES = frozenset({ 'worker_timeout', 'worker_crashed', 'ipc_closed', 'response_timeout', 'network_error', 'browser_error', 'memory_limit', 'process_interrupted', 'proxy_access_denied', 'proxy_unavailable', 'worker_startup_exhausted', }) PROXY_FAILURES = frozenset({'proxy_access_denied', 'proxy_unavailable'}) ACCOUNT_FAILURE_STATES = {'needs_auth': 'cooldown', 'challenge': 'cooldown', 'credentials_invalid': 'disabled', 'account_disabled': 'disabled'} LEGACY_RECOVERY_DEFAULTS = {'auto_recovery_rounds': 12, 'auto_recovery_cooldown': 300.0} class StopRequested(KeyboardInterrupt): def __init__(self, signum): self.signum = signum super().__init__('Stop requested by signal ' + str(signum)) class ProjectLogFormatter(logging.Formatter): def __init__(self, timezone_name): super().__init__('%(asctime)s %(levelname)s %(message)s') self.zone = ZoneInfo(timezone_name) def formatTime(self, record, datefmt=None): return datetime.fromtimestamp(record.created, self.zone).isoformat(timespec='milliseconds') class Runner: """Sequential parent control flow; all durable changes have one owner.""" def __init__(self, config, *, worker_factory=None): self.config = copy.deepcopy(config) self.output = Path(config.get('output') or Path(__file__).resolve().parent / 'data').resolve() self.worker_factory = worker_factory or WorkerClient self.worker = None self.alias = None self.pool = None self.store = None self.control = {} self.control_path = None self.generation = 0 self.completed_with_worker = 0 self.stop_requested = False self.stop_signal = signal.SIGINT self.logger = logging.getLogger('ctrip') def save(self): atomic_json(self.control_path, self.control) def _record_failure(self, error, stage, task_index=None): current = self.control.get('current') or {} diagnostic = make_diagnostic(error, stage=stage, config=self.config) self.control['last_error'] = { 'code': error.code, 'task_index': task_index if task_index is not None else current.get('index'), 'at': utc_now(), 'attempt_id': current.get('attempt_id'), 'worker_generation': self.generation, 'diagnostic': diagnostic, } if stage == 'collect' and error.code in ACCOUNT_FAILURE_STATES and self.alias is not None: self.control['last_error']['account_failure'] = { 'alias': self.alias, 'pool_revision': self.pool.record(self.alias)['pool_revision']} if (current and self.config['auto_recovery_rounds'] and (error.code in PROXY_FAILURES or (stage == 'parent.prepare' and error.code in RECOVERABLE_FAILURES))): current['pending_recovery'] = {'code': error.code} self.logger.warning('operation_failed index=%s attempt=%s code=%s diagnostic=%s', self.control['last_error']['task_index'], current.get('attempt_count'), error.code, json.dumps(diagnostic, ensure_ascii=False, separators=(',', ':'))) self.save() def _task_budget(self): current = self.control.get('current') or {} extra = current.get('extra_work_budget', 0.0) if (isinstance(extra, bool) or not isinstance(extra, (int, float)) or not math.isfinite(extra) or extra < 0): raise CrawlerError('state_invalid', '追加的任务预算无效') total = self.config['task_budget'] + extra if not math.isfinite(total): raise CrawlerError('state_invalid', '任务累计预算超出有效范围') return total def _grant_manual_retry(self, token, reason): match = re.fullmatch(r'([0-9]+):([0-9]+)', token) if isinstance(token, str) else None if (match is None or not isinstance(reason, str) or not reason.strip() or len(reason) > 256): raise CrawlerError('config_invalid', '人工恢复需要 TASK:ATTEMPT 和不超过256字符的非空原因') try: index, count = map(int, match.groups()) except ValueError as error: raise CrawlerError('config_invalid', '人工恢复任务标识无效') from error token = f'{index}:{count}' current = self.control.get('current') if (not isinstance(current, dict) or type(self.control.get('cursor')) is not int or type(current.get('index')) is not int or self.control['cursor'] != index or current['index'] != index or type(current.get('attempt_count')) is not int or current['attempt_count'] != count): raise CrawlerError('state_invalid', '人工恢复标识与当前任务及尝试次数不符') if self.control.get('staging') is not None or self.control.get('publish_intent') is not None: raise CrawlerError('state_invalid', '必须先恢复未完成的结果发布,不能同时追加任务额度') maximum, used = current.get('max_attempts'), current.get('work_used') if (type(maximum) is not int or maximum < 1 or count < 0 or isinstance(used, bool) or not isinstance(used, (int, float)) or not math.isfinite(used) or used < 0): raise CrawlerError('state_invalid', '当前任务预算记录无效') records = current.get('manual_recoveries', []) if not isinstance(records, list) or any(not isinstance(record, dict) for record in records): raise CrawlerError('state_invalid', '人工恢复记录格式无效') if any(record.get('token') == token for record in records): return False budget = self._task_budget() if count < maximum and used < budget and self.control.get('pause_reason') != 'recovery_exhausted': raise CrawlerError('state_invalid', '当前任务仍有自动恢复额度,不能提前追加') self._record_recovery('manual_recoveries', {'token': token, 'reason': safe_message(reason, config=self.config)[:256]}, extend=True) return True def _record_recovery(self, history_key, details, *, extend, not_before=None): """Publish one recovery decision and its limits in the same state write.""" current = self.control['current'] budget = self._task_budget() records = current.get(history_key, []) if not isinstance(records, list) or any(not isinstance(item, dict) for item in records): raise CrawlerError('state_invalid', '恢复记录格式无效') increment = self.config['task_budget'] if extend else 0.0 new_budget = budget + increment if not math.isfinite(new_budget): raise CrawlerError('state_invalid', '追加后的累计预算超出有效范围') maximum = current['max_attempts'] new_maximum = maximum + (max(3, len(self.config['accounts']) or 1) if extend else 0) auth = self.control.get('auth') record = {**details, 'at': utc_now(), 'attempt_count': current['attempt_count'], 'work_used': current['work_used'], 'auth_used': auth.get('used') if isinstance(auth, dict) else current.get('auth_used'), 'old_max_attempts': maximum, 'new_max_attempts': new_maximum, 'old_task_budget': budget, 'new_task_budget': new_budget} candidate = copy.deepcopy(self.control) candidate['current'].update(max_attempts=new_maximum, extra_work_budget=current.get('extra_work_budget', 0.0) + increment) candidate['current'][history_key] = copy.deepcopy(records) + [record] candidate['current'].pop('pending_recovery', None) if history_key == 'manual_recoveries' and self.control.get('pause_reason') == 'recovery_exhausted': extra = current.get('extra_recovery_rounds', 0) candidate['current']['extra_recovery_rounds'] = extra + self.config['auto_recovery_rounds'] record.update(old_recovery_rounds=self.config['auto_recovery_rounds'] + extra, new_recovery_rounds=self.config['auto_recovery_rounds'] + candidate['current']['extra_recovery_rounds']) candidate.pop('pause_reason', None) candidate.pop('pause_diagnostic', None) if not_before is not None: candidate.update(status='waiting', next_attempt_at=not_before) if candidate.get('startup') and not candidate['startup'].get('complete'): candidate.pop('startup') previous = self.control self.control = candidate try: self.save() except BaseException: self.control = previous raise def _schedule_recovery(self, code): current = self.control['current'] records = current.get('automatic_recoveries', []) if not isinstance(records, list): raise CrawlerError('state_invalid', '自动恢复记录格式无效') extra = current.get('extra_recovery_rounds', 0) if type(extra) is not int or extra < 0: raise CrawlerError('state_invalid', '追加的自动恢复额度无效') limit = self.config['auto_recovery_rounds'] + extra if len(records) >= limit: self.control.update(status='paused', pause_reason='recovery_exhausted') self.save() raise CrawlerError('recovery_exhausted', '当前任务的自动冷却恢复次数已耗尽,请检查最后的具体错误') exhausted = current['attempt_count'] >= current['max_attempts'] or current['work_used'] >= self._task_budget() until = (datetime.now(timezone.utc) + timedelta(seconds=self.config['auto_recovery_cooldown'])).isoformat() self._record_recovery('automatic_recoveries', {'error_code': code, 'not_before': until}, extend=exhausted, not_before=until) self.logger.warning('recovery_wait index=%s round=%s/%s code=%s until=%s', current['index'], len(records) + 1, limit, code, until) def _last_task_failure(self): error = self.control.get('last_error') or {} current = self.control.get('current') or {} return error.get('code') if error.get('task_index') == current.get('index') else None def _recover_account_failure(self): current = self.control['current'] error = self.control.get('last_error') or {} code, alias = error.get('code'), current.get('account_alias') if not self.config['login_allowed'] or alias not in self.pool.config: return None self.pool.reconcile(control=self.control, control_path=self.control_path) blocked = self.control.get('blocked_accounts', {}) record = self.pool.record(alias) mutation = record.get('mutation') or {} source, effect = mutation.get('source', {}), mutation.get('effect', {}) if (alias in blocked and effect.get('block') is True and source.get('run_id') == self.control.get('run_id') and source.get('task_index') == current['index'] and source.get('attempt_id') == current.get('attempt_id')): # The completed block is the switch decision. A later error can # replace the diagnostic while this decision retains its identity. return alias if (code not in ACCOUNT_FAILURE_STATES or error.get('task_index') != current['index'] or error.get('attempt_id') != current.get('attempt_id')): return None evidence = error.get('account_failure') if evidence is None: # Existing batches can prove the completed mark through their block. phase = (error.get('diagnostic') or {}).get('stage', '') if (alias not in blocked or blocked[alias].get('reason') != code or not (phase == 'collect' or phase.startswith('collect.'))): return None else: if (not isinstance(evidence, dict) or evidence.get('alias') != alias or type(evidence.get('pool_revision')) is not int or evidence['pool_revision'] < 0): raise CrawlerError('state_invalid', '账号失败的恢复证据无效') authenticated = record.get('last_explicit_login') or {} if authenticated.get('pool_revision', -1) > evidence['pool_revision']: return None if alias not in blocked: # Replay a failure interrupted before AccountPool's own journal # published the block. A completed mark is never refreshed. self._mark_account_failure(code, alias=alias) return alias def _check_stop(self): if self.stop_requested: raise StopRequested(self.stop_signal) def _disk_check(self): if shutil.disk_usage(self.output).free < self.config['disk_reserve_mb'] * 1024 * 1024: raise CrawlerError('storage_error', '输出目录可用空间不足,停止派发') def _site_deadline(self): path = self.output / '.site.json' state = read_json(path) if path.exists() else {'schema_version': SCHEMA_VERSION} if not isinstance(state, dict) or state.get('schema_version') != SCHEMA_VERSION: raise CrawlerError('state_invalid', '站点冷却状态格式不兼容') candidates = [value for value in (state.get('server_not_before'), self.control.get('server_not_before')) if value] try: deadline = max(candidates, key=parse_utc) if candidates else None if deadline: parse_utc(deadline) except (AttributeError, TypeError, ValueError) as exc: raise CrawlerError('state_invalid', '站点冷却时间无效') from exc if deadline and deadline != state.get('server_not_before'): atomic_json(path, {'schema_version': SCHEMA_VERSION, 'server_not_before': deadline}) return deadline def _site_gate(self): deadline = self._site_deadline() if deadline and parse_utc(deadline) > datetime.now(timezone.utc): raise CrawlerError('rate_limited', '站点的服务端等待尚未结束,新批次和登录不能绕过') def _handle_site_limit(self, error, *, allow_wait=True): try: seconds = float(error.retry_after) if error.retry_after is not None else 600.0 if not math.isfinite(seconds) or seconds < 0: raise ValueError('retry_after') except (TypeError, ValueError) as exc: raise CrawlerError('protocol_changed', '服务端等待时间无效') from exc until = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat() previous = self._site_deadline() if previous: until = max((previous, until), key=parse_utc) # Publish output-wide policy first. A crash before progress.save cannot # allow another batch or an independent login to bypass the wait. atomic_json(self.output / '.site.json', {'schema_version': SCHEMA_VERSION, 'server_not_before': until}) self.control['server_not_before'] = until self.save() remaining = max(0, (parse_utc(until) - datetime.now(timezone.utc)).total_seconds()) if not allow_wait or self.control.get('rate_limit_recoveries', 0) >= 1 or remaining > 600: raise CrawlerError('rate_limited', '站点已限流,最早恢复时间已保存') self.control['rate_limit_recoveries'] = 1 self.save() self._wait_until(until) self._site_gate() def _session_file(self, alias): return self.pool.session_path(alias) if alias is not None else self.output / 'sessions' / 'anonymous.json' def _recover_owner(self, owner_path): """Retire only exact process identities recorded by this operation.""" owner_path = Path(owner_path) if not owner_path.exists(): return if not owner_path.resolve().is_relative_to(self.output): raise CrawlerError('process_cleanup', '进程归属记录不在当前输出目录内') record = read_json(owner_path) identities = record.get('processes') if (type(record.get('owner_pid')) is not int or record['owner_pid'] <= 0 or not isinstance(identities, dict)): raise CrawlerError('process_cleanup', '进程归属记录不完整,拒绝推测清理目标') import psutil try: protected = {os.getpid(), *(process.pid for process in psutil.Process().parents())} matching = {} for raw_pid, created in identities.items(): if (not re.fullmatch(r'[1-9][0-9]*', str(raw_pid)) or isinstance(created, bool) or not isinstance(created, (int, float)) or not math.isfinite(created) or created <= 0): raise CrawlerError('process_cleanup', '进程身份记录无效') pid = int(raw_pid) try: process = psutil.Process(pid) if process.create_time() != created: # The recorded resource ended; a reused PID belongs to # another process and grants no cleanup authority. continue if pid in protected: raise CrawlerError('process_cleanup', '归属记录指向当前父进程或其祖先,拒绝清理') matching[pid] = created except psutil.NoSuchProcess: continue # Inspect every entry before terminating any process. Inspection # denial is not evidence that a resource is absent. _terminate_owned_processes(matching) except psutil.AccessDenied as exc: raise CrawlerError('process_cleanup', '无法确认或清理已记录进程的权限') from exc atomic_json(owner_path, dict(record, processes={}, recovered_at=utc_now())) def _load_session(self, alias): path = self._session_file(alias) return read_json(path) if path.exists() else None def _save_identity(self, identity): current = self._load_session(self.alias) if current: if stable_hash(current['identity']) != stable_hash(identity): raise CrawlerError('session_incompatible', '浏览器身份发生变化,请使用独立输出目录重新认证') return snapshot = {'schema_version': SCHEMA_VERSION, 'session_identity_id': uuid.uuid4().hex, 'session_revision': 0, 'identity': identity, 'state': None} if self.alias is None: atomic_json(self._session_file(None), snapshot) else: self.pool.initialize_session(self.alias, snapshot) def _save_session(self, value): previous = self._load_session(self.alias) if not previous or stable_hash(previous['identity']) != stable_hash(value['identity']): raise CrawlerError('session_incompatible', '拒绝不匹配身份的认证快照') snapshot = dict(previous, state=value['state'], session_revision=previous['session_revision'] + 1, updated_at=utc_now()) if self.alias is None: atomic_json(self._session_file(None), snapshot) else: self.pool.commit_session(self.alias, snapshot, control_path=self.control_path, control=self.control) def _save_auth_candidate(self, value): previous = self._load_session(self.alias) if self.alias is None or not previous or not isinstance(value.get('state'), dict): raise CrawlerError('state_invalid', '认证候选状态没有合法身份') path = self.pool.session_path(self.alias).with_name('auth-candidate.json') atomic_json(path, {'schema_version': SCHEMA_VERSION, 'account_alias': self.alias, 'session_identity_id': previous['session_identity_id'], 'state': value['state'], 'confirmed': False, 'challenge_visible': bool(value.get('challenge_visible')), 'saved_at': utc_now()}) if value.get('challenge_visible') and not self.control.get('challenge_notified'): self.logger.warning('需要在当前浏览器中完成手机验证;账号=%s,程序不会自动发送短信。', self.alias) self.control['challenge_notified'] = True self.save() def _close_worker(self): if self.worker is not None: worker, self.worker = self.worker, None worker.close() self.completed_with_worker = 0 def _recover_budgets(self): interrupted = bool((self.control.get('current') or {}).get('reserved', 0)) recover_attempt_budget(self.control) auth = self.control.setdefault('auth', {'used': 0.0, 'reserved': 0.0}) auth['used'] += auth.get('reserved', 0) auth['reserved'] = 0 startup = self.control.get('startup') if startup and startup.get('reserved'): if self.control.get('current'): self.control['current']['work_used'] += startup['reserved'] startup['used'] = startup.get('used', 0) + startup['reserved'] startup['reserved'] = 0 self.save() if interrupted: self._record_failure(CrawlerError('process_interrupted', '上次已派发尝试未完成结算;保留次数并计入预留预算,终止原因未知'), 'parent.recovery') def _ensure_worker(self, alias): self._check_stop() self._site_gate() if self.worker is not None and self.alias == alias: return self._close_worker() self.alias = alias startup = self.control.get('startup') if not startup or startup.get('complete') or startup.get('alias') != alias: startup = {'id': uuid.uuid4().hex, 'alias': alias, 'attempts': 0, 'used': 0.0, 'reserved': 0.0, 'complete': False} self.control['startup'] = startup while startup['attempts'] < 3: self._check_stop() saved = self._load_session(alias) state = saved.get('state') if saved else None if self.config.get('explicit_login') and saved: candidate_path = self._session_file(alias).with_name('auth-candidate.json') if candidate_path.exists(): candidate = read_json(candidate_path) if candidate.get('session_identity_id') != saved['session_identity_id'] or candidate.get('account_alias') != alias: raise CrawlerError('session_incompatible', '认证候选状态与账号身份不符') if parse_utc(candidate['saved_at']) > parse_utc(saved.get('updated_at', '0001-01-01T00:00:00+00:00')): state = candidate['state'] current = self.control.get('current') remaining = self._task_budget() - current['work_used'] if current else self.config['startup_timeout'] * 3 - startup['used'] if remaining <= 0: raise CrawlerError('task_exhausted', '浏览器恢复时间预算已耗尽') timeout = min(self.config['startup_timeout'], remaining) self.generation = max(self.generation, self.control.get('generation', 0)) + 1 self.control['generation'] = self.generation startup['attempts'] += 1 startup['reserved'] = timeout self.save() began = time.monotonic() worker_config = dict(self.config, account_alias=alias) if alias is not None: worker_config['account'] = account_credentials(self.pool.config[alias]) worker = self.worker_factory(worker_config, saved.get('identity') if saved else None, state, generation=self.generation, alias=alias, on_profile=self._save_identity, on_session=self._save_session, on_checkpoint=self._save_auth_candidate, owner_path=self.control_path.parent / 'owner.json') self.worker = worker try: worker.start(timeout=timeout) elapsed = min(timeout, time.monotonic() - began) startup['used'] += elapsed startup['reserved'] = 0 startup['complete'] = True if current: current['work_used'] += elapsed self.save() return except CrawlerError as exc: elapsed = min(timeout, time.monotonic() - began) startup['used'] += elapsed startup['reserved'] = 0 if current: current['work_used'] += elapsed self.save() self._record_failure(exc, 'worker.start') self._close_worker() if exc.code not in ('worker_timeout', 'worker_crashed', 'ipc_closed', 'browser_startup'): raise raise CrawlerError('worker_startup_exhausted', '浏览器启动次数已耗尽,进度已保存') def _mark_account(self, state, reason, *, seconds=None, alias=None): alias = self.alias if alias is None else alias if alias is None: raise CrawlerError('needs_auth', '匿名会话需要认证,请配置账号池') until = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat() if seconds else None self.pool.mark(alias, state, reason, cooldown_until=until, control_path=self.control_path, control=self.control, source={'run_id': self.control.get('run_id'), 'task_index': self.control.get('cursor'), 'attempt_id': (self.control.get('current') or {}).get('attempt_id')}) def _mark_account_failure(self, code, *, alias=None): state = ACCOUNT_FAILURE_STATES[code] self._mark_account(state, code, alias=alias, seconds=self.config['cooldown_seconds'] if state == 'cooldown' else None) def _select_account(self): self.pool.reconcile(control=self.control, control_path=self.control_path) return self.pool.select(self.alias or self.control.get('preferred_alias'), self.control.get('blocked_accounts', {})) def _choose_account(self): if not self.config['login_allowed']: return None alias = self._select_account() if alias is None: reasons = {a: self.pool.record(a)['state'] for a in self.pool.config} self.control['pool_summary'] = reasons self.save() raise CrawlerError('account_pool_exhausted', '当前任务没有可用账号,请完成 --login 后恢复;任务预算不会重置') self.control['preferred_alias'] = alias self.save() return alias def _authenticate(self, *, explicit=False, manual=False): self._check_stop() self._site_gate() if self.alias is None: raise CrawlerError('needs_auth', '匿名运行无法自动登录') used = self.control.setdefault('auth_used_aliases', []) retry_identity = {'alias': self.alias, 'task_index': (self.control.get('current') or {}).get('index')} transport_retry = self.control.get('auth_transport_retry') == retry_identity if self.alias in used and not explicit and not transport_retry: self._mark_account('cooldown', 'authentication_budget', seconds=self.config['cooldown_seconds']) raise CrawlerError('account_unavailable', '此任务对该账号的认证机会已用完') auth = self.control.setdefault('auth', {'used': 0.0, 'reserved': 0.0}) total = self.config['standalone_auth_timeout'] if explicit else self.config['auth_budget'] timeout = self.config['standalone_auth_timeout'] if explicit else ( self.config['challenge_timeout'] if manual else self.config['login_timeout']) timeout = min(timeout, total - auth['used']) if timeout <= 0: raise CrawlerError('auth_exhausted', '认证总预算已耗尽') if self.alias not in used: used.append(self.alias) self.control.pop('auth_transport_retry', None) auth.update(id=uuid.uuid4().hex, reserved=timeout, alias=self.alias) self.save() began = time.monotonic() account = account_credentials(self.pool.config[self.alias]) try: value = self.worker.call('auth', {'account': account}, timeout=timeout, auth_id=auth['id']) if not isinstance(value, dict) or not value.get('authenticated'): raise CrawlerError('auth_failed', '浏览器未确认登录成功') snapshot = self._load_session(self.alias) if explicit: self.pool.commit_session(self.alias, snapshot, explicit_auth=True, auth_id=auth['id'], control_path=self.control_path, control=self.control) else: self.pool.mark(self.alias, 'ready', 'authenticated', control_path=self.control_path, control=self.control) except CrawlerError as exc: if exc.code in PROXY_FAILURES or exc.code == 'network_error': # Transport failure is not a rejected login. Preserve the used # time/history and permit one same-task continuation after the # caller's bounded network cooldown; never unblock an account. self.control['auth_transport_retry'] = retry_identity self._record_failure(exc, 'auth') if exc.code == 'rate_limited': self._handle_site_limit(exc, allow_wait=False) elif exc.code in ('credentials_invalid', 'account_disabled'): self._mark_account('disabled', exc.code) elif exc.code in ('needs_auth', 'challenge', 'auth_failed', 'auth_timeout', 'response_timeout', 'worker_timeout'): self._mark_account('cooldown', exc.code, seconds=self.config['cooldown_seconds']) raise finally: auth = self.control.setdefault('auth', auth) auth['used'] += min(timeout, time.monotonic() - began) auth['reserved'] = 0 self.save() def _prepare_account(self): while True: self._check_stop() alias = self._choose_account() self._ensure_worker(alias) if alias is None or self.pool.record(alias)['state'] == 'ready': return try: self._authenticate() return except CrawlerError as exc: if exc.code not in ('account_unavailable', 'needs_auth', 'challenge', 'auth_failed', 'auth_timeout', 'credentials_invalid', 'account_disabled', 'response_timeout', 'worker_timeout'): raise self._close_worker() def _initialize(self, run_id, resume=False): self.store = FileStore(self.output, run_id) self.control_path = self.store.run_dir / 'initialization.json' self._recover_owner(self.store.run_dir / 'owner.json') if resume: self.control = read_json(self.control_path) saved_config = self.control.get('config') runtime_overrides = {'headless', 'challenge_policy', 'proxy_id', 'proxy_identity_version'} current_config = public_config(self.config) if (isinstance(saved_config, dict) and 'comfort_timeout' not in saved_config and current_config.get('comfort_timeout') == 15.0): current_config.pop('comfort_timeout') for key, fallback in LEGACY_RECOVERY_DEFAULTS.items(): if isinstance(saved_config, dict) and key not in saved_config: current_config.pop(key, None) self.config[key] = fallback if (not isinstance(saved_config, dict) or {key: value for key, value in saved_config.items() if key not in runtime_overrides} != {key: value for key, value in current_config.items() if key not in runtime_overrides}): raise CrawlerError('config_invalid', '初始化恢复配置与固定配置不同') binding = validate_proxy_binding(saved_config, self.config['proxy'], self.control.get('proxy_binding_override'), refresh=getattr(self, 'refresh_proxy_credentials', False), reason=getattr(self, 'recovery_reason', None)) if binding != self.control.get('proxy_binding_override'): self.control['proxy_binding_override'] = binding self.save() else: self.control = {'schema_version': SCHEMA_VERSION, 'run_id': run_id, 'operation_id': uuid.uuid4().hex, 'config': public_config(self.config), 'dates': flight_dates(self.config), 'phase': 'initializing', 'resolve_attempts': 0, 'resolve_used': 0.0, 'resolve_reserved': 0.0, 'blocked_accounts': {}, 'auth_used_aliases': [], 'account_ack': {}} self.save() self.pool.reconcile(control=self.control, control_path=self.control_path) self._recover_budgets() self.control['resolve_used'] += self.control.get('resolve_reserved', 0) self.control['resolve_reserved'] = 0 self.save() plan = None while self.control['resolve_attempts'] < 3: self._prepare_account() self._check_stop() timeout = min(self.config['attempt_timeout'], 180 - self.control['resolve_used']) if timeout <= 0: break self.control['resolve_attempts'] += 1 self.control['resolve_reserved'] = timeout self.save() began = time.monotonic() try: self._site_gate() cities = self.worker.call('resolve', {'names': self.config['crawl_citys']}, timeout=timeout) if not isinstance(cities, list) or len(cities) != len(self.config['crawl_citys']): raise CrawlerError('protocol_changed', '城市解析结果数量不一致') codes = [c['code'] for c in cities] if len(set(codes)) != len(codes) or any(not re.fullmatch(r'[A-Z]{3}', c) for c in codes): raise CrawlerError('config_invalid', '城市身份重复或无效') for city in cities: _files_safe_name(city['name']) plan = {'run_id': run_id, 'created_at': utc_now(), 'cities': cities, 'dates': self.control['dates'], 'config': public_config(self.config), 'options': {key: self.config[key] for key in ('direct_flight', 'comft_flight', 'rename_col')}} self.control['resolve_used'] += min(timeout, time.monotonic() - began) self.control['resolve_reserved'] = 0 self.save() break except CrawlerError as exc: self.control['resolve_used'] += min(timeout, time.monotonic() - began) self.control['resolve_reserved'] = 0 self.save() self._record_failure(exc, 'resolve') if exc.code == 'rate_limited': self._handle_site_limit(exc) continue if exc.code in ('needs_auth', 'challenge') and self.alias is not None: self._mark_account('cooldown', exc.code, seconds=self.config['cooldown_seconds']) self._close_worker() continue raise if plan is None: raise CrawlerError('initialization_exhausted', '城市解析预算已耗尽') rate_limit_recoveries = self.control.get('rate_limit_recoveries', 0) try: progress = self.store.create(plan) except BaseException: # FileStore may already have published plan_complete before its # progress write failed. Never overwrite that recovery evidence # with the pre-publication in-memory initialization snapshot. self.control = read_json(self.control_path) raise self.control_path = self.store.progress_path self.control = progress self.control['rate_limit_recoveries'] = rate_limit_recoveries self.save() return plan def _resume(self, run_id): self.store = FileStore(self.output, run_id) if not self.store.plan_path.exists(): return self._initialize(run_id, resume=True) self._recover_owner(self.store.run_dir / 'owner.json') plan, self.control = self.store.load() self.control_path = self.store.progress_path saved_config = plan['config'] aliases = [a['alias'] for a in self.config['accounts']] if aliases != saved_config.get('account_aliases', []): raise CrawlerError('config_invalid', '恢复时账号池别名顺序不能改变') binding = validate_proxy_binding(saved_config, self.config['proxy'], self.control.get('proxy_binding_override'), refresh=getattr(self, 'refresh_proxy_credentials', False), reason=getattr(self, 'recovery_reason', None)) if binding != self.control.get('proxy_binding_override'): self.control['proxy_binding_override'] = binding self.save() runtime_overrides = {'headless', 'challenge_policy'} for key, value in saved_config.items(): if key in self.config and key not in runtime_overrides: self.config[key] = value self.config['comfort_timeout'] = saved_config.get('comfort_timeout', 15.0) for key, fallback in LEGACY_RECOVERY_DEFAULTS.items(): self.config[key] = saved_config.get(key, fallback) self.pool.reconcile(control=self.control, control_path=self.control_path) self.store.recover(self.control) self._recover_budgets() return plan def _wait_until(self, value): self._check_stop() next_log = 0.0 while value and parse_utc(value) > datetime.now(timezone.utc): remaining = (parse_utc(value) - datetime.now(timezone.utc)).total_seconds() self._check_stop() if time.monotonic() >= next_log: self.logger.info('waiting until=%s remaining_seconds=%.1f', value, remaining) next_log = time.monotonic() + 60 time.sleep(max(0.0, min(0.25, remaining))) self._check_stop() def _collect_plan(self, plan): total = len(plan['cities']) * (len(plan['cities']) - 1) * len(plan['dates']) if self.control['cursor'] > total: raise CrawlerError('state_invalid', '恢复点超出固定计划') if self.control['cursor'] == total: self.control['status'] = 'completed' self.save() return 0 if self.control.get('pause_reason') == 'recovery_exhausted': raise CrawlerError('recovery_exhausted', '自动恢复已耗尽,需要先处理故障并显式人工恢复') pending_wait = self.control.get('next_attempt_at') self.control['status'] = ('waiting' if pending_wait and parse_utc(pending_wait) > datetime.now(timezone.utc) else 'running') self.control.pop('pause_reason', None) self.control.pop('pause_diagnostic', None) self.save() self._site_gate() for task in iter_tasks(plan): if task['index'] < self.control['cursor']: continue self._check_stop() self._disk_check() if date.fromisoformat(task['departure_date']) < datetime.now(ZoneInfo(self.config['timezone'])).date(): raise CrawlerError('expired', '当前任务出发日期已过去,固定计划不会自动改日') if self.control.get('current') is None: new = new_task_control(task['index'], len(self.config['accounts']) or 1) self.control.update(new) self.control['auth'] = {'used': 0.0, 'reserved': 0.0} self.save() while True: self._check_stop() failed_alias = self._recover_account_failure() current = self.control['current'] pending = current.get('pending_recovery') if pending: if not isinstance(pending, dict) or pending.get('code') not in RECOVERABLE_FAILURES: raise CrawlerError('state_invalid', '未决恢复记录无效') self._schedule_recovery(pending['code']) current = self.control['current'] code = self._last_task_failure() # A completed cooldown is consumed only by the next dispatch. # Restarting during the wait must not append a second round. if current['attempt_count'] >= current['max_attempts'] or current['work_used'] >= self._task_budget(): recoverable = code in RECOVERABLE_FAILURES if self.config['auto_recovery_rounds'] and not recoverable and failed_alias is not None: candidate = self._select_account() recoverable = candidate is not None and candidate != failed_alias if self.config['auto_recovery_rounds'] and recoverable: self._schedule_recovery(code) else: raise CrawlerError('task_exhausted', '当前任务预算已耗尽;resume 不会重置预算') self._wait_until(self.control.get('next_attempt_at')) self.control['status'] = 'running' self._prepare_account() self._wait_until(self.control.get('next_search_at')) self._site_gate() current = reserve_attempt(self.control, self.alias, self.generation, self.config['attempt_timeout'], self._task_budget()) self.control['next_search_at'] = (datetime.now(timezone.utc) + timedelta(seconds=self.config['crawl_interval'])).isoformat() self.save() began = time.monotonic() committed = False try: task['account_alias'] = self.alias task['binding_epoch'] = self.generation result = self.worker.call('collect', {'task': task}, timeout=current['reserved'], attempt_id=current['attempt_id']) settle_attempt(self.control, time.monotonic() - began) self.save() result.setdefault('columns', list(CSV_FIELDS)) self.store.publish(task, result, self.control) committed = True self.completed_with_worker += 1 self.logger.info('task_done index=%s/%s status=%s rows=%s price_status=%s', task['index'] + 1, total, result['status'], len(result['rows']), result['price_status']) if self.completed_with_worker >= self.config['recycle_tasks']: self._close_worker() break except CrawlerError as exc: if (committed or self.control.get('current') is None or self.control.get('staging') or self.control.get('publish_intent')): raise settle_attempt(self.control, time.monotonic() - began) self._record_failure(exc, 'collect', task['index']) if exc.code in ACCOUNT_FAILURE_STATES and self.alias is not None: if (ACCOUNT_FAILURE_STATES[exc.code] == 'cooldown' and self.config['challenge_policy'] == 'wait_then_switch'): try: self._authenticate(manual=True) continue except CrawlerError as auth_error: if auth_error.code not in ('needs_auth', 'auth_timeout', 'auth_failed', 'worker_timeout', 'response_timeout', 'account_unavailable'): raise else: self._mark_account_failure(exc.code) self._close_worker() continue if exc.code == 'rate_limited': self._handle_site_limit(exc) continue if exc.code not in RECOVERABLE_FAILURES: raise self._close_worker() if exc.code in PROXY_FAILURES: if not self.config['auto_recovery_rounds']: raise self._schedule_recovery(exc.code) continue count = self.control['current']['attempt_count'] if count >= self.control['current']['max_attempts'] or self.control['current']['work_used'] >= self._task_budget(): continue delays = self.config.get('retry_delays', [5, 15]) delay = delays[min(count - 1, len(delays) - 1)] self.control['current']['work_used'] += delay self.control['next_attempt_at'] = (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat() self.save() self.control['status'] = 'completed' self.save() return 0 def run(self, *, resume=None, login=None, run_id=None, retry_current=None, refresh_proxy_credentials=False, recovery_reason=None): action = retry_current is not None or refresh_proxy_credentials if run_id is not None and (resume is not None or login is not None): raise CrawlerError('config_invalid', '固定批次入口不能与 resume 或 login 同时使用') if action and (not resume or login is not None): raise CrawlerError('config_invalid', '人工恢复选项只能配合 --resume 使用') if action and (not isinstance(recovery_reason, str) or not recovery_reason.strip() or len(recovery_reason) > 256): raise CrawlerError('config_invalid', '人工恢复必须提供不超过256字符的 --recovery-reason') if recovery_reason is not None and not action: raise CrawlerError('config_invalid', '恢复原因必须对应一个明确的人工恢复操作') self.refresh_proxy_credentials = refresh_proxy_credentials self.recovery_reason = safe_message(recovery_reason, config=self.config)[:256] if action else None from filelock import FileLock, Timeout self.output.mkdir(parents=True, exist_ok=True) try: lock = FileLock(str(self.output / '.run.lock'), timeout=0) with lock: self.pool = AccountPool(self.output, self.config['accounts']) self.pool.reconcile() self._disk_check() self._site_gate() try: if login: if login not in self.pool.config: raise CrawlerError('config_invalid', '未知的账号别名') record = self.pool.record(login) if record.get('server_not_before') and parse_utc(record['server_not_before']) > datetime.now(timezone.utc): raise CrawlerError('rate_limited', '账号的服务端等待尚未结束') self.config['headless'] = False self.config['challenge_policy'] = 'wait_then_switch' self.config['explicit_login'] = True self.control_path = self.pool.session_path(login).parent / 'auth_control.json' self._recover_owner(self.control_path.parent / 'owner.json') self.control = {'operation_id': uuid.uuid4().hex, 'auth_used_aliases': [], 'blocked_accounts': {}, 'account_ack': {}} self.save() self._ensure_worker(login) self._authenticate(explicit=True, manual=True) return 0 selected_id = (run_id if run_id is not None else resume or datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ_') + uuid.uuid4().hex[:8]) store = FileStore(self.output, selected_id) existing = store.plan_path.exists() or store.initialization_path.exists() self.logger.info('run=%s output=%s pid=%s parent_pid=%s', selected_id, self.output, os.getpid(), os.getppid()) plan = self._resume(selected_id) if resume or (run_id and existing) else self._initialize(selected_id) if retry_current is not None: granted = self._grant_manual_retry(retry_current, self.recovery_reason) if granted: self.control.pop('pause_reason', None) self.logger.warning('manual_retry token=%s granted=%s reason=%s', retry_current, granted, self.recovery_reason) while True: try: return self._collect_plan(plan) except CrawlerError as error: if (error.code not in RECOVERABLE_FAILURES or not self.config['auto_recovery_rounds'] or not self.control.get('current') or self.control.get('staging') or self.control.get('publish_intent')): raise self._record_failure(error, 'parent.prepare') self._close_worker() self._schedule_recovery(error.code) except BaseException as exc: if self.control_path and self.control_path.exists(): self.control['status'] = 'interrupted' if isinstance(exc, KeyboardInterrupt) else 'paused' self.control['pause_reason'] = getattr(exc, 'code', type(exc).__name__) self.control['pause_diagnostic'] = make_diagnostic(exc, stage='parent.run', config=self.config) current = self.control.get('current') or {} self.logger.warning('run_paused code=%s index=%s attempts=%s/%s work_used=%s/%s diagnostic=%s', self.control['pause_reason'], current.get('index'), current.get('attempt_count'), current.get('max_attempts'), current.get('work_used'), self._task_budget(), json.dumps(self.control['pause_diagnostic'], ensure_ascii=False, separators=(',', ':'))) self.save() raise finally: self._close_worker() except Timeout as exc: raise CrawlerError('output_locked', '输出目录正被另一个实例使用') from exc def _resume_cli_config(config, run_id, output): """Read frozen non-secret settings before validating local credentials.""" store = FileStore(output, run_id) if store.plan_path.exists(): plan = read_json(store.plan_path) check = dict(plan) digest = check.pop('plan_hash', None) if (plan.get('run_id') != run_id or plan.get('schema_version') != SCHEMA_VERSION or digest != stable_hash(check)): raise CrawlerError('state_invalid', '恢复计划的版本、身份或摘要不符') frozen = plan.get('config') else: initialization = read_json(store.initialization_path) if initialization.get('run_id') != run_id or initialization.get('schema_version') != SCHEMA_VERSION: raise CrawlerError('state_invalid', '初始化恢复记录的版本或身份不符') frozen = initialization.get('config') if not isinstance(frozen, dict) or not isinstance(frozen.get('account_aliases'), list): raise CrawlerError('state_invalid', '恢复记录缺少规范配置或账号别名') local_accounts = config['accounts'] if not isinstance(local_accounts, list) or any(not isinstance(item, dict) for item in local_accounts): raise CrawlerError('config_invalid', '本地账号配置必须为列表') by_alias = {} for account in local_accounts: alias = account.get('alias') if alias in by_alias: raise CrawlerError('config_invalid', '本地账号别名不能重复') by_alias[alias] = account accounts = [] for alias in frozen['account_aliases']: if alias not in by_alias: raise CrawlerError('config_invalid', '恢复此批次需要在脚本中配置账号别名 ' + str(alias)) accounts.append(copy.deepcopy(by_alias[alias])) for key, value in frozen.items(): if key in config and key not in ('accounts', 'proxy', 'output'): config[key] = copy.deepcopy(value) config['accounts'] = accounts config['comfort_timeout'] = frozen.get('comfort_timeout', 15.0) for key, fallback in LEGACY_RECOVERY_DEFAULTS.items(): config[key] = frozen.get(key, fallback) return config def command_line(argv=None): parser = argparse.ArgumentParser(description='携程航班采集:Camoufox、独立单文件、账号池与可恢复文件输出', epilog='第三方安装:python -m pip install ' + ' '.join(f'{k}=={v}' for k, v in RUNTIME_REQUIREMENTS.items()) + '\n浏览器:python -m camoufox fetch ' + BROWSER_BUILD) operation = parser.add_mutually_exclusive_group() operation.add_argument('--resume', metavar='RUN_ID') operation.add_argument('--run-id', metavar='RUN_ID', help='幂等创建或恢复固定批次,适用于进程托管') operation.add_argument('--login', metavar='ALIAS') operation.add_argument('--check-environment', action='store_true') parser.add_argument('--retry-current', metavar='TASK:ATTEMPT', help='随 --resume 为已耗尽的指定当前任务追加一轮有限额度') parser.add_argument('--refresh-proxy-credentials', action='store_true', help='随 --resume 显式迁移旧批次代理凭据绑定;须确认连接配置未变') parser.add_argument('--recovery-reason', metavar='TEXT', help='人工恢复原因,必填且不超过256字符') parser.add_argument('--output', type=Path) parser.add_argument('--cities', nargs='+', metavar='CITY') parser.add_argument('--begin-date') parser.add_argument('--days', type=int) parser.add_argument('--anonymous', action='store_true', help='显式匿名运行;需要认证时停止') mode = parser.add_mutually_exclusive_group() mode.add_argument('--headed', action='store_true') mode.add_argument('--headless', action='store_true') parser.add_argument('--version', action='version', version=VERSION) args = parser.parse_args(argv) check_environment() if args.check_environment: browser_environment_check() print('运行依赖与指定 Camoufox 构建检查通过。') return 0 config = copy.deepcopy(DEFAULT_CONFIG) if args.output: config['output'] = str(args.output.resolve()) output = Path(config['output'] or Path(__file__).resolve().parent / 'data').resolve() fixed_store = FileStore(output, args.run_id) if args.run_id is not None else None resuming = args.resume or (args.run_id if fixed_store and (fixed_store.plan_path.exists() or fixed_store.initialization_path.exists()) else None) if resuming: if args.resume and (args.cities or args.begin_date is not None or args.days is not None): raise CrawlerError('config_invalid', '恢复使用固定城市和日期;修改业务条件请创建新批次') output = Path(config['output'] or Path(__file__).resolve().parent / 'data').resolve() config = _resume_cli_config(config, resuming, output) if args.anonymous and config['login_allowed']: raise CrawlerError('config_invalid', '恢复不能将账号批次改为匿名批次') if args.cities and not resuming: config['crawl_citys'] = args.cities if args.begin_date and not resuming: config['begin_date'] = args.begin_date if args.days is not None and not resuming: config['crawl_days'] = args.days if args.anonymous: config['login_allowed'] = False config['accounts'] = [] if args.headed: config['headless'] = False if args.headless: config['headless'] = True if args.login: config['headless'] = False config['challenge_policy'] = 'wait_then_switch' config = validate_config(config) browser_environment_check() output = Path(config['output'] or Path(__file__).resolve().parent / 'data').resolve() output.mkdir(parents=True, exist_ok=True) logger = logging.getLogger('ctrip') logger.setLevel(logging.INFO) formatter = ProjectLogFormatter(config['timezone']) console = logging.StreamHandler() console.setFormatter(formatter) rotating = logging.handlers.RotatingFileHandler(output / 'crawler.log', maxBytes=10 * 1024 * 1024, backupCount=9, encoding='utf-8') rotating.setFormatter(formatter) logger.handlers[:] = [console, rotating] runner = Runner(config) interrupts = 0 def stop(signum, frame): nonlocal interrupts interrupts += 1 if interrupts == 1: runner.stop_requested = True runner.stop_signal = signum logger.warning('stop_requested signal=%s pid=%s;停止派发,等待当前有界操作结束。', signum, os.getpid()) else: raise StopRequested(signum) previous = {number: signal.signal(number, stop) for number in (signal.SIGINT, signal.SIGTERM)} try: result = runner.run(resume=args.resume, login=args.login, run_id=args.run_id, retry_current=args.retry_current, refresh_proxy_credentials=args.refresh_proxy_credentials, recovery_reason=args.recovery_reason) logger.info('finished status=%s stats=%s', result, runner.control.get('stats', {})) return result finally: for number, handler in previous.items(): signal.signal(number, handler) for handler in logger.handlers: handler.close() logger.handlers.clear() def main(argv=None): try: return command_line(argv) except StopRequested as exc: print(f'运行已中断,signal={exc.signum};固定批次可继续恢复。', file=sys.stderr) return 128 + exc.signum except KeyboardInterrupt: print('运行已中断,使用 --resume 恢复固定批次。', file=sys.stderr) return 130 except CrawlerError as exc: print(f'{exc.code}: {safe_message(exc)}', file=sys.stderr) if exc.code in ('config_invalid', 'config_error', 'unsupported_mode', 'environment_invalid', 'browser_missing', 'browser_unavailable'): return 2 if exc.code in ('needs_auth', 'account_pool_exhausted', 'rate_limited', 'protocol_changed', 'expired', 'session_incompatible', 'task_exhausted', 'recovery_exhausted', 'proxy_access_denied', 'proxy_unavailable', 'initialization_exhausted'): return 3 if exc.code.startswith(('storage', 'ipc', 'process', 'worker_startup')) or exc.code in ('output_locked', 'state_invalid', 'worker_error'): return 4 return 1 if exc.code in RECOVERABLE_FAILURES else 4 except Exception as exc: diagnostic = make_diagnostic(exc, stage='cli', config=DEFAULT_CONFIG) print('unexpected_error: ' + json.dumps(diagnostic, ensure_ascii=False, separators=(',', ':')), file=sys.stderr) return 4 if __name__ == '__main__': multiprocessing.freeze_support() raise SystemExit(main())