feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
scripts/freight_rpa/inbound/inbound_crane_export.py
|
||||
|
||||
用途:Crane 收料报表导出适配器——固定 Inbound Details,委托共享 crane_report_export。
|
||||
依赖:crane_report_export、crane_session。
|
||||
逻辑:inbound_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
|
||||
driver 在 Playwright 未返回 Download 时做目录兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
import crane_report_export
|
||||
import crane_session
|
||||
|
||||
|
||||
def _inbound_details_entry_url(login_url: str) -> str:
|
||||
"""将复用的 Crane Profile 登录地址固定到收料 Inbound Details 路由。"""
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise RuntimeError('Crane inbound unit requires an absolute login_url')
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, '/inbound-details-query'))
|
||||
|
||||
|
||||
def export_inbound_report(
|
||||
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
|
||||
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
|
||||
) -> Any:
|
||||
"""
|
||||
创建并下载唯一 Description 对应的 Crane Inbound Details 文件。
|
||||
|
||||
核心逻辑:固定 scheduled_report_name=Inbound Details;把 unit.__download_dir
|
||||
写入 source,供共享 crane_report_export 目录兜底(对齐库存)。
|
||||
"""
|
||||
report_path = dict(unit.get('report_path_json') or {})
|
||||
if str(report_path.get('report_name') or '').strip() != 'Inbound Details':
|
||||
raise RuntimeError('Crane inbound report must be Inbound Details')
|
||||
entry_url = _inbound_details_entry_url(str(unit.get('login_url') or '').strip())
|
||||
if first_in_profile:
|
||||
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
|
||||
crane_session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||||
crane_session.wait_for_crane_app_ready(page, entry_url, env=env, browser_timeout_ms=browser_timeout_ms)
|
||||
# 旧 Crane driver 的 Scheduled Reports 匹配名来自 source;收料固定为
|
||||
# Inbound Details,不能沿用库存的 OnHandDetails.xlsx 默认值。
|
||||
source = {
|
||||
'entry_url': entry_url,
|
||||
'scheduled_report_name': 'Inbound Details',
|
||||
# 与库存/DBS 同构:供 crane_report_export 在 Playwright 未返回 Download 时目录兜底。
|
||||
'__download_dir': str(unit.get('__download_dir') or ''),
|
||||
}
|
||||
return crane_report_export.export_crane_inventory_report(
|
||||
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
|
||||
browser_timeout_ms=browser_timeout_ms, select_or_fill=select_or_fill, click_text=click_text,
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
scripts/freight_rpa/inbound/inbound_dbs_export.py
|
||||
|
||||
用途:DBS 收料报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
|
||||
依赖:connectors/dsv/dsv_report_export。
|
||||
逻辑:inbound_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
|
||||
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
|
||||
source 写入 __export_kind__=inbound,共享驱动用 Receipt Detail 就绪/行探针。
|
||||
query_parameters 原样下发;仅当 unit.warehouse_id 有值时追加单值 Warehouse
|
||||
(兼容旧 trigger);空条件表示使用页面默认,不强制 Warehouse。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from typing import Any
|
||||
|
||||
import dsv_report_export
|
||||
|
||||
|
||||
def build_inbound_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
将收料 unit 组装为共享 dsv_report_export 可消费的 source。
|
||||
|
||||
核心逻辑:report_path_json → navigation(驱动只读 navigation/query);
|
||||
parameters 取自 query_parameters_json;有 warehouse_id 时追加单值 Warehouse。
|
||||
|
||||
Args:
|
||||
unit: 收料 trigger 单元(含 report_path_json / query_parameters_json 等)。
|
||||
entry_url: 该 Profile 分组的登录入口 URL。
|
||||
|
||||
Returns:
|
||||
与库存 trigger source 同构的 dict,可供 prepare_dsv_batch_export_step 与导出使用。
|
||||
"""
|
||||
report_path = dict(unit.get('report_path_json') or {})
|
||||
source: dict[str, Any] = {
|
||||
'entry_url': entry_url,
|
||||
'report_path_json': report_path,
|
||||
# 与库存 trigger 同构:Source.report_path_json → navigation,供菜单导航使用。
|
||||
'navigation': report_path,
|
||||
'parameters': list(unit.get('query_parameters_json') or []),
|
||||
'__download_dir': str(unit.get('__download_dir') or ''),
|
||||
# 显式标记收料导出:共享 dsv_report_export 用 Receipt Detail 就绪/行探针,不用库存字段。
|
||||
'__export_kind__': 'inbound',
|
||||
}
|
||||
# 兼容旧 trigger:仅当排程曾写入 warehouse_id 时追加,避免与参数里已有 Warehouse 双写需由旧载荷保证互斥。
|
||||
warehouse_id = str(unit.get('warehouse_id') or '').strip()
|
||||
if warehouse_id:
|
||||
source['parameters'].append({
|
||||
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
|
||||
'required': True, 'select_all': False,
|
||||
})
|
||||
return source
|
||||
|
||||
|
||||
def export_inbound_report(
|
||||
page: Any,
|
||||
unit: dict[str, Any],
|
||||
*,
|
||||
entry_url: str,
|
||||
skip_navigation: bool = False,
|
||||
) -> Any:
|
||||
"""
|
||||
在既有 DBS 登录态内执行收料路径与受控非日期条件。
|
||||
|
||||
核心逻辑:组装 source 后委托 export_dsv_inventory_source;会话登录与参数页复用
|
||||
由 Worker 侧 prepare_dsv_batch_export_step 完成。skip_navigation=True 时跳过菜单导航,
|
||||
直接在已就绪的参数页填参导出(同导航批内复用)。
|
||||
|
||||
Args:
|
||||
page: 当前 Playwright Page(批内复用同一 tab,禁止每源 new_page)。
|
||||
unit: 收料 trigger 单元。
|
||||
entry_url: 登录入口 URL。
|
||||
skip_navigation: 为 True 时跳过报表菜单导航(参数页已由 prepare 就绪)。
|
||||
|
||||
Returns:
|
||||
Playwright Download 对象。
|
||||
"""
|
||||
source = build_inbound_dsv_source(unit, entry_url=entry_url)
|
||||
return dsv_report_export.export_dsv_inventory_source(
|
||||
page,
|
||||
{'action': 'inbound_export_batch'},
|
||||
source,
|
||||
skip_navigation=skip_navigation,
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
scripts/freight_rpa/inbound/inbound_excel_empty.py
|
||||
|
||||
用途:收料 Excel「有表头无明细」判空(真相源,对齐库存 Excel 判空)。
|
||||
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
|
||||
逻辑:inbound_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail)
|
||||
不得当成表头,否则真表头会被误判为明细导致假 success。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class NoInboundDataError(RuntimeError):
|
||||
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
|
||||
|
||||
|
||||
def _normalize_row_joined(row: tuple | list) -> str:
|
||||
"""
|
||||
将一行单元格规范为小写比较串。
|
||||
|
||||
核心逻辑:换行压成空格(SSRS 表头常为 External\\nASN #),去空白后用 | 拼接。
|
||||
"""
|
||||
parts: list[str] = []
|
||||
for cell in row:
|
||||
if cell is None:
|
||||
continue
|
||||
text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip()
|
||||
if text:
|
||||
parts.append(text.lower())
|
||||
return ' | '.join(parts)
|
||||
|
||||
|
||||
def is_inbound_excel_header_row(joined: str) -> bool:
|
||||
"""
|
||||
判断是否为收料列标题行(非报表标题行)。
|
||||
|
||||
核心逻辑:要求 External ASN / WMS Receipt / Supplier ID+AWS Sku 等组合特征;
|
||||
单独含 receipt(如「AWS Receipt Detail」)不得命中。
|
||||
"""
|
||||
if not joined:
|
||||
return False
|
||||
if 'external asn' in joined and (
|
||||
'wms receipt' in joined
|
||||
or 'aws sku' in joined
|
||||
or 'supplier id' in joined
|
||||
or 'supplier' in joined
|
||||
):
|
||||
return True
|
||||
if 'warehouse' in joined and 'external asn' in joined:
|
||||
return True
|
||||
if 'supplier id' in joined and 'aws sku' in joined:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def inbound_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
"""
|
||||
判断收料 Excel 列标题之后是否有明细行。
|
||||
|
||||
核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None
|
||||
(不强制 empty,由结构校验兜底)。
|
||||
|
||||
Returns:
|
||||
True: 有明细;False: 有表头无明细;None: 未识别表头形态。
|
||||
"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
worksheet = workbook.active
|
||||
if worksheet is None:
|
||||
return None
|
||||
header_idx: int | None = None
|
||||
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
|
||||
joined = _normalize_row_joined(row or ())
|
||||
if not joined:
|
||||
continue
|
||||
if header_idx is None:
|
||||
if is_inbound_excel_header_row(joined):
|
||||
header_idx = idx
|
||||
continue
|
||||
if idx > header_idx:
|
||||
return True
|
||||
if header_idx is None:
|
||||
return None
|
||||
return False
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def enforce_inbound_excel_not_empty(path: Path) -> None:
|
||||
"""
|
||||
有表头无明细时记为无收料(NoInboundDataError → empty / no_receipt_data)。
|
||||
|
||||
Raises:
|
||||
NoInboundDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
|
||||
"""
|
||||
if inbound_excel_has_detail_rows(path) is False:
|
||||
raise NoInboundDataError('no_receipt_data')
|
||||
@@ -0,0 +1,843 @@
|
||||
"""
|
||||
scripts/freight_rpa/inbound/inbound_rpa_worker.py
|
||||
|
||||
用途:独立货代收料 RPA Worker——仅消费 inbound trigger,不触及库存 Worker 的目录或 callback。
|
||||
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
|
||||
inbound_excel_empty、inbound_dbs_export、inbound_crane_export、connectors/dsv/dsv_report_export。
|
||||
逻辑:排程写入 inbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
|
||||
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
|
||||
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
|
||||
import rpa_callbacks # noqa: E402
|
||||
from rpa_callbacks import ( # noqa: E402
|
||||
INBOUND_BATCH_PROGRESS,
|
||||
INBOUND_BATCH_READY,
|
||||
INBOUND_UNIT_PROGRESS,
|
||||
)
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_logging # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
|
||||
import dsv_report_export # noqa: E402
|
||||
import inbound_crane_export # noqa: E402
|
||||
import inbound_dbs_export # noqa: E402
|
||||
from inbound_excel_empty import ( # noqa: E402
|
||||
NoInboundDataError,
|
||||
enforce_inbound_excel_not_empty as _enforce_inbound_excel_not_empty,
|
||||
)
|
||||
|
||||
_EXPORT_UNIT_MAX_ATTEMPTS = 2
|
||||
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
|
||||
_INBOUND_EXCEL_MIN_BYTES = 512
|
||||
# 结构校验可用较宽标记;「有表头无明细」判空见 inbound_excel_empty(禁止用单字 receipt 当表头)。
|
||||
_INBOUND_EXCEL_HEADER_MARKERS = (
|
||||
'receipt',
|
||||
'inbound',
|
||||
'asn',
|
||||
'po number',
|
||||
'po #',
|
||||
'supplier id',
|
||||
'aws sku',
|
||||
'sku',
|
||||
'quantity',
|
||||
'received',
|
||||
)
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
|
||||
return _RPA_ROOT.parents[1] / 'backend'
|
||||
|
||||
|
||||
def _mask_secret(value: str | None) -> str:
|
||||
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
|
||||
value = str(value or '').strip()
|
||||
if len(value) <= 8:
|
||||
return '***' if value else 'missing'
|
||||
return f'{value[:4]}....{value[-4:]}'
|
||||
|
||||
|
||||
def _require_dir(variable: str) -> Path:
|
||||
"""读取 inbound 专用目录;不回退至 onhand 共享路径。"""
|
||||
value = env(variable)
|
||||
if not value:
|
||||
raise SystemExit(f'Missing env: {variable}')
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / value).resolve()
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
|
||||
"""向 HXOPS 入站(原收料)RPA 回调 API 上报(薄封装,统一走 /api/freight-rpa/*)。
|
||||
|
||||
核心逻辑:鉴权、脱敏日志与 HTTP 错误处理收拢到 common/rpa_callbacks.post_callback;
|
||||
保留 (path, payload, timeout) 签名,便于测试 monkeypatch 与既有调用点零改动。
|
||||
"""
|
||||
rpa_callbacks.post_callback(path, payload, timeout=timeout)
|
||||
|
||||
|
||||
def _post_callback(payload: dict[str, Any]) -> None:
|
||||
"""向独立收料 callback 上报一个单元终态结果。"""
|
||||
_post_rpa(INBOUND_BATCH_READY, payload)
|
||||
|
||||
|
||||
def _mark_unit_processing(unit: dict[str, Any]) -> None:
|
||||
"""开始导出前标记 processing;失败不影响导出主链路。"""
|
||||
try:
|
||||
_post_rpa(
|
||||
INBOUND_UNIT_PROGRESS,
|
||||
{
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'processing',
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[inbound-unit] processing progress failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
|
||||
"""每完成一笔导出回传累计进度(对齐 onhand-batch-progress)。"""
|
||||
schedule_run_id = body.get('schedule_run_id')
|
||||
if schedule_run_id is None:
|
||||
return
|
||||
try:
|
||||
_post_rpa(
|
||||
INBOUND_BATCH_PROGRESS,
|
||||
{
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'schedule_run_id': schedule_run_id,
|
||||
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
|
||||
'success_count': int(counts.get('success') or 0),
|
||||
'skipped_count': int(counts.get('empty') or 0),
|
||||
'failed_count': int(counts.get('failed') or 0),
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[inbound-batch] progress callback failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _profile_credentials(unit: dict[str, Any]):
|
||||
"""在单个 Profile 分组内临时解密凭据并清理环境,绝不输出明文。"""
|
||||
envelope = unit.get('credential_envelope') or {}
|
||||
username_ciphertext = str(envelope.get('username_ciphertext') or '').strip()
|
||||
password_ciphertext = str(envelope.get('password_ciphertext') or '').strip()
|
||||
if not username_ciphertext and not password_ciphertext:
|
||||
yield
|
||||
return
|
||||
if not username_ciphertext or not password_ciphertext:
|
||||
raise RuntimeError('RPA Profile credentials are incomplete')
|
||||
key = env('FREIGHT_RPA_CREDENTIAL_KEY')
|
||||
if not key:
|
||||
raise RuntimeError('FREIGHT_RPA_CREDENTIAL_KEY is required')
|
||||
try:
|
||||
fernet = Fernet(key.encode('ascii'))
|
||||
username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8')
|
||||
password = fernet.decrypt(password_ciphertext.encode('ascii')).decode('utf-8')
|
||||
except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc
|
||||
connector = str(unit.get('connector_type') or '').lower()
|
||||
names = ('FREIGHT_RPA_WORKER_DSV_USERNAME', 'FREIGHT_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('FREIGHT_RPA_WORKER_CRANE_USERNAME', 'FREIGHT_RPA_WORKER_CRANE_PASSWORD')
|
||||
before = {name: os.environ.get(name) for name in names}
|
||||
os.environ[names[0]], os.environ[names[1]] = username, password
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name, old_value in before.items():
|
||||
if old_value is None:
|
||||
os.environ.pop(name, None)
|
||||
else:
|
||||
os.environ[name] = old_value
|
||||
|
||||
|
||||
def _session_reuse_enabled() -> bool:
|
||||
"""
|
||||
收料是否复用持久浏览器 Profile。
|
||||
|
||||
核心逻辑:对齐库存——未设置或空值时默认开启;仅显式 false 时关闭。
|
||||
"""
|
||||
raw = env('FREIGHT_RPA_WORKER_SESSION_REUSE')
|
||||
if raw is None or str(raw).strip() == '':
|
||||
return True
|
||||
return str(raw).strip().strip("\"'").lower() == 'true'
|
||||
|
||||
|
||||
def _sanitize_profile_dir_segment(value: str) -> str:
|
||||
"""将 connector / profile_code 收成可作目录名的安全片段。"""
|
||||
text = str(value or '').strip()
|
||||
cleaned = ''.join(ch if (ch.isalnum() or ch in '-_') else '_' for ch in text)
|
||||
return (cleaned[:96] or 'default')
|
||||
|
||||
|
||||
def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
|
||||
"""
|
||||
按 connector + RPA Profile 隔离的持久收料会话目录。
|
||||
|
||||
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
|
||||
命名空间分离,避免串 Cookie);禁止所有收料源共用单一 inbound_session。
|
||||
"""
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
|
||||
code = _sanitize_profile_dir_segment(profile_code)
|
||||
return profile_root / f'{connector}__{code}_session'
|
||||
|
||||
|
||||
def _open_browser(
|
||||
download_dir: Path,
|
||||
*,
|
||||
reuse_session: bool = False,
|
||||
connector_type: str = '',
|
||||
profile_code: str = '',
|
||||
):
|
||||
"""为一个 inbound Profile 分组创建浏览器上下文,组内登录一次、串行导出。
|
||||
|
||||
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
|
||||
否则一次性临时 Profile(inbound_* 前缀),批次结束即删。
|
||||
"""
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('Playwright is required for real inbound RPA') from exc
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
|
||||
if use_reused:
|
||||
runtime_profile = _session_profile_dir(connector_type, profile_code)
|
||||
runtime_profile.mkdir(parents=True, exist_ok=True)
|
||||
profile_mode = 'session_reuse'
|
||||
else:
|
||||
runtime_profile = Path(tempfile.mkdtemp(prefix='inbound_', dir=str(profile_root)))
|
||||
profile_mode = 'temporary'
|
||||
print(
|
||||
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
|
||||
f'profile={profile_code or "-"} dir={runtime_profile.name!r}'
|
||||
)
|
||||
playwright = sync_playwright().start()
|
||||
options: dict[str, Any] = {
|
||||
'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true',
|
||||
'accept_downloads': True,
|
||||
'downloads_path': str(download_dir),
|
||||
}
|
||||
channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
|
||||
if channel:
|
||||
options['channel'] = channel
|
||||
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options)
|
||||
page = context.pages[0] if context.pages else context.new_page()
|
||||
page.set_default_timeout(browser_timeout_ms())
|
||||
return playwright, context, page, runtime_profile
|
||||
|
||||
|
||||
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
|
||||
"""
|
||||
在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
|
||||
|
||||
核心逻辑:对齐库存 Worker——新开空白页并关闭旧页;Cookie 仍在 context 内,
|
||||
仅用于会话准备失败后的一次完整登录重试,禁止作为常态「每源新开空白页」。
|
||||
|
||||
Args:
|
||||
context: 已建立登录态的 Playwright browser context。
|
||||
current_page: 上一站页面;关闭以避免报表 iframe / 下载菜单残留。
|
||||
|
||||
Returns:
|
||||
可重新进入收料报表的空白页面。
|
||||
"""
|
||||
next_page = context.new_page()
|
||||
next_page.set_default_timeout(browser_timeout_ms())
|
||||
if current_page is not None:
|
||||
try:
|
||||
current_page.close()
|
||||
except Exception as exc:
|
||||
print(f'[inbound-batch] close previous page failed: {exc}', file=_sys.stderr)
|
||||
return next_page
|
||||
|
||||
|
||||
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
|
||||
"""
|
||||
导出前拍摄下载目录已有文件名,供目录兜底识别「本次新文件」。
|
||||
|
||||
核心逻辑:仅收集普通文件名;目录不可读时返回空集合(对齐库存)。
|
||||
"""
|
||||
try:
|
||||
return {path.name for path in drop_dir.iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
|
||||
"""判断是否为 Playwright 页面/上下文已关闭导致的落盘失败。"""
|
||||
message = str(exc).lower()
|
||||
return 'has been closed' in message or 'target closed' in message or 'targetclosed' in message
|
||||
|
||||
|
||||
def _persist_download_to_dest(
|
||||
download: Any,
|
||||
dest: Path,
|
||||
*,
|
||||
drop_dir: Path,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> None:
|
||||
"""
|
||||
将 Playwright Download 落到规范路径;浏览器已关闭时走 downloads_path 目录兜底。
|
||||
|
||||
核心逻辑:对齐库存 `_persist_download_to_dest`——先 save_as,TargetClosed
|
||||
再按 baseline 等待稳定新文件后搬迁。
|
||||
"""
|
||||
try:
|
||||
download.save_as(str(dest))
|
||||
return
|
||||
except Exception as exc:
|
||||
if not _is_playwright_target_closed_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[inbound-artifact] stage=download_save status=fallback '
|
||||
f'reason=browser_closed path={dest.name!r}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
artifact = _wait_for_new_download_file(
|
||||
download_dir=drop_dir,
|
||||
baseline_names=set(baseline_names or ()),
|
||||
timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if artifact is None:
|
||||
raise
|
||||
artifact.save_as(str(dest))
|
||||
|
||||
|
||||
def _inbound_download_name(
|
||||
batch_run_no: str,
|
||||
source_code: str,
|
||||
warehouse_id: str | None,
|
||||
*,
|
||||
suffix: str = '.xlsx',
|
||||
) -> str:
|
||||
"""
|
||||
收料落盘文件名,对齐库存 `_batch_download_name`。
|
||||
|
||||
核心逻辑:`inbound_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
|
||||
不写入 callback_id(关联仍靠 callback JSON)。
|
||||
|
||||
Args:
|
||||
batch_run_no: trigger 顶层批次号。
|
||||
source_code: 库存源编码(辨识用)。
|
||||
warehouse_id: 可选仓码;空则 NA。
|
||||
suffix: 扩展名,默认 .xlsx。
|
||||
|
||||
Returns:
|
||||
安全化后的文件名(不含目录)。
|
||||
"""
|
||||
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'inbound'
|
||||
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
|
||||
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
|
||||
return f'inbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
|
||||
|
||||
|
||||
def _save_download(
|
||||
download: Any,
|
||||
drop_dir: Path,
|
||||
unit: dict[str, Any],
|
||||
*,
|
||||
batch_run_no: str,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> Path:
|
||||
"""
|
||||
保存本单元下载文件到 inbound drop;必要时在浏览器关闭后走目录兜底。
|
||||
|
||||
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
|
||||
"""
|
||||
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
|
||||
if suffix != '.xlsx':
|
||||
raise RuntimeError('inbound report download must be xlsx')
|
||||
target = drop_dir / _inbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
suffix=suffix,
|
||||
)
|
||||
_persist_download_to_dest(
|
||||
download,
|
||||
target,
|
||||
drop_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if target.stat().st_size <= 0:
|
||||
raise RuntimeError('inbound report download is empty')
|
||||
return target
|
||||
|
||||
|
||||
def _validate_inbound_excel(path: Path) -> None:
|
||||
"""
|
||||
校验收料 Excel 可打开且具备报表基本结构。
|
||||
|
||||
核心逻辑:对齐 onhand `_validate_onhand_excel`——拒过小/HTML 伪装文件;
|
||||
前几行或 sheet 标题须含收料报表特征,避免错误页当 success 归档。
|
||||
"""
|
||||
size = path.stat().st_size
|
||||
if size < _INBOUND_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f'downloaded inbound Excel is too small ({size} bytes)')
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('openpyxl required to validate inbound Excel') from exc
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f'downloaded file is not valid Excel: {exc}') from exc
|
||||
try:
|
||||
worksheet = workbook.active
|
||||
if worksheet is None:
|
||||
raise RuntimeError('downloaded file is not valid Excel: missing active sheet')
|
||||
preview_lines: list[str] = []
|
||||
for row in worksheet.iter_rows(max_row=6, values_only=True):
|
||||
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
|
||||
if cells:
|
||||
preview_lines.append(' | '.join(cells).lower())
|
||||
haystack = '\n'.join(preview_lines)
|
||||
title = str(worksheet.title or '').lower().replace('_', '')
|
||||
if not any(marker in haystack for marker in _INBOUND_EXCEL_HEADER_MARKERS):
|
||||
if 'receipt' not in title and 'inbound' not in title:
|
||||
raise RuntimeError('downloaded file is not valid Excel: missing inbound report headers')
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _validate_unit(unit: dict[str, Any]) -> None:
|
||||
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
|
||||
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
|
||||
if not str(unit.get(key) or '').strip():
|
||||
raise RuntimeError(f'inbound unit missing {key}')
|
||||
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
|
||||
raise RuntimeError('unsupported inbound connector_type')
|
||||
parameters = list(unit.get('query_parameters_json') or [])
|
||||
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
|
||||
raise RuntimeError('inbound date filtering is forbidden')
|
||||
|
||||
|
||||
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
|
||||
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
|
||||
print(f'[inbound-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
def _report_empty(unit: dict[str, Any], exc: NoInboundDataError) -> None:
|
||||
"""无业务明细的合法结果:回调 empty + no_receipt_data(后端 finalize 计 skipped)。"""
|
||||
print(f'[inbound-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
|
||||
_post_callback({
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'empty',
|
||||
'error_code': 'no_receipt_data',
|
||||
'error_message': str(exc)[:2000] or 'no_receipt_data',
|
||||
})
|
||||
|
||||
|
||||
def _is_login_session_error(exc: BaseException) -> bool:
|
||||
"""登录/会话类偶发异常可干净页重试;凭据校验类不重试。"""
|
||||
message = str(exc).lower()
|
||||
login_related = any(token in message for token in ('login', 'session', 'oauth'))
|
||||
credential_mismatch = any(token in message for token in ('invalid', 'verification'))
|
||||
return login_related and not credential_mismatch
|
||||
|
||||
|
||||
def _export_unit_download(
|
||||
*,
|
||||
connector: str,
|
||||
unit: dict[str, Any],
|
||||
group: list[dict[str, Any]],
|
||||
index: int,
|
||||
login_url: str,
|
||||
page: Any,
|
||||
context: Any,
|
||||
drop_dir: Path,
|
||||
attempt: int = 1,
|
||||
) -> tuple[Any, Any]:
|
||||
"""
|
||||
导出单个收料单元的 Playwright Download;必要时干净页重试会话。
|
||||
|
||||
Args:
|
||||
attempt: 第几次尝试(1 起)。>1 时强制完整重导航(对齐库存 2026-09-20 AWSRTM
|
||||
兜底:报表页导出菜单缺失属瞬态故障,绝不在错误页上直接重试,须回入口页
|
||||
重选菜单进报表),且 prepare 的导航/会话类异常一并走干净页安全网
|
||||
(凭据校验类 invalid/verification 为确定性失败,不重试)。
|
||||
Returns:
|
||||
(download, page):download 为 Playwright Download;page 可能已切换为干净页。
|
||||
"""
|
||||
unit['__download_dir'] = str(drop_dir)
|
||||
if connector == 'dbs':
|
||||
source = inbound_dbs_export.build_inbound_dsv_source(unit, entry_url=login_url)
|
||||
# 重试尝试强制完整重导航:不携带前一单元上下文,prepare 从入口页重选菜单进报表。
|
||||
force_full_navigation = attempt > 1
|
||||
previous_unit = group[index - 1] if (index > 0 and not force_full_navigation) else None
|
||||
previous_source = (
|
||||
inbound_dbs_export.build_inbound_dsv_source(previous_unit, entry_url=login_url)
|
||||
if previous_unit is not None else None
|
||||
)
|
||||
skip_navigation = False
|
||||
try:
|
||||
skip_navigation = bool(
|
||||
dsv_report_export.prepare_dsv_batch_export_step(
|
||||
page, login_url, previous_source, source,
|
||||
index=0 if force_full_navigation else index,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
# 安全网:登录/会话与导航类瞬态异常均新开干净页重跑完整准备;
|
||||
# 仅凭据校验类(invalid/verification)确定性失败不重试(对齐库存)。
|
||||
message = str(exc).lower()
|
||||
if any(token in message for token in ('invalid', 'verification')):
|
||||
raise
|
||||
print(
|
||||
f'[inbound-batch] dbs prepare failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
skip_navigation = bool(
|
||||
dsv_report_export.prepare_dsv_batch_export_step(
|
||||
page, login_url, None, source, index=0,
|
||||
)
|
||||
)
|
||||
download = inbound_dbs_export.export_inbound_report(
|
||||
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
|
||||
)
|
||||
return download, page
|
||||
|
||||
# Crane 重试尝试同样强制完整重登导航(first_in_profile=True 走首源完整登录)。
|
||||
first_in_profile = index == 0 or attempt > 1
|
||||
try:
|
||||
download = inbound_crane_export.export_inbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=first_in_profile,
|
||||
)
|
||||
return download, page
|
||||
except Exception as exc:
|
||||
# Crane 无 DBS 式 prepare 步骤:导出期登录/会话失败时干净页 + 强制首源登录重试一次。
|
||||
if not _is_login_session_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[inbound-batch] crane session failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
download = inbound_crane_export.export_inbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=True,
|
||||
)
|
||||
return download, page
|
||||
|
||||
|
||||
def _write_mock_inbound_excel(path: Path) -> None:
|
||||
"""Mock 模式写出带表头+一行明细的合法收料 Excel,便于走校验与 success 回调。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = 'ReceiptDetail'
|
||||
sheet.append(['ASN', 'PO Number', 'AWS Sku', 'Quantity Received'])
|
||||
sheet.append(['ASN-MOCK-1', 'PO-1', 'SKU-1', 1])
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
|
||||
"""落盘成功后上报 inbound-batch-ready(归档);调用方须放在导出重试之外。
|
||||
|
||||
file_path 契约为「drop 根内文件名」:Worker(Windows)与后端(Linux 挂载根)分属
|
||||
两机、根路径不同,后端按自身挂载根拼接定位(跨机部署下发本机绝对路径必 400)。
|
||||
"""
|
||||
_post_callback({
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit['callback_id'],
|
||||
'status': 'success',
|
||||
'file_path': output.name,
|
||||
'original_filename': output.name,
|
||||
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
})
|
||||
|
||||
|
||||
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
"""
|
||||
按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。
|
||||
|
||||
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
|
||||
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
|
||||
``inbound-batch-progress``(管理端实时笔数),再调 ``inbound-batch-ready`` 归档;
|
||||
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
|
||||
"""
|
||||
units = body.get('units')
|
||||
if body.get('schema_version') != 'freight_rpa.inbound.v1' or body.get('action') != 'inbound_export_batch' or not isinstance(units, list) or not units:
|
||||
raise RuntimeError('invalid inbound trigger contract')
|
||||
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'inbound').strip() or 'inbound'
|
||||
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
|
||||
for item in units:
|
||||
if not isinstance(item, dict):
|
||||
raise RuntimeError('inbound unit must be object')
|
||||
_validate_unit(item)
|
||||
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
|
||||
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
|
||||
for (connector, profile_code, login_url), group in grouped.items():
|
||||
print(f'[inbound-batch] connector={connector} profile={profile_code} units={len(group)}')
|
||||
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
|
||||
reuse_session = _session_reuse_enabled()
|
||||
resources = (None, None, None, None)
|
||||
try:
|
||||
if not mock:
|
||||
resources = _open_browser(
|
||||
drop_dir,
|
||||
reuse_session=reuse_session,
|
||||
connector_type=connector,
|
||||
profile_code=profile_code,
|
||||
)
|
||||
playwright, context, page, profile_dir = resources
|
||||
with _profile_credentials(group[0]):
|
||||
for index, unit in enumerate(group):
|
||||
_mark_unit_processing(unit)
|
||||
output: Path | None = None
|
||||
terminal: tuple[str, BaseException] | None = None
|
||||
# [RETRY] 仅导出/落盘/校验;ready 回调禁止进入本循环。
|
||||
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if mock:
|
||||
mock_path = drop_dir / _inbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
)
|
||||
_write_mock_inbound_excel(mock_path)
|
||||
output = mock_path
|
||||
else:
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
download, page = _export_unit_download(
|
||||
connector=connector,
|
||||
unit=unit,
|
||||
group=group,
|
||||
index=index,
|
||||
login_url=login_url,
|
||||
page=page,
|
||||
context=context,
|
||||
drop_dir=drop_dir,
|
||||
attempt=attempt,
|
||||
)
|
||||
output = _save_download(
|
||||
download, drop_dir, unit, batch_run_no=batch_run_no,
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
_validate_inbound_excel(output)
|
||||
_enforce_inbound_excel_not_empty(output)
|
||||
break
|
||||
except NoInboundDataError as exc:
|
||||
terminal = ('empty', exc)
|
||||
output = None
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
|
||||
print(
|
||||
f'[inbound-batch] export failed {unit.get("source_code")} '
|
||||
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
|
||||
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
time.sleep(_EXPORT_UNIT_RETRY_WAIT_SECONDS)
|
||||
continue
|
||||
terminal = ('failed', exc)
|
||||
output = None
|
||||
|
||||
# [STEP] 导出循环外:轻量 progress + 终态回调(对齐库存 progress / 批末 ready)
|
||||
if terminal is not None and terminal[0] == 'empty':
|
||||
try:
|
||||
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[inbound-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
progress_counts['empty'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
if terminal is not None and terminal[0] == 'failed':
|
||||
try:
|
||||
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[inbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
progress_counts['failed'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
if output is None:
|
||||
continue
|
||||
print(
|
||||
f'[inbound-unit] success source={unit["source_code"]} '
|
||||
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
|
||||
)
|
||||
progress_counts['success'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
try:
|
||||
_post_unit_ready(unit, output)
|
||||
except Exception as callback_exc:
|
||||
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
|
||||
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
|
||||
print(
|
||||
f'[inbound-unit] ready callback failed source={unit.get("source_code")} '
|
||||
f'file={output.name}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
finally:
|
||||
playwright, context, _page, profile_dir = resources
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
# 会话复用模式保留 {connector}__{profile}_session;一次性临时目录批次后删除。
|
||||
if profile_dir is not None and not (reuse_session and _session_reuse_enabled()):
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
"""原子领取一个 inbound trigger;成功归档 processed,异常归档 failed。
|
||||
|
||||
领取与归档统一走 common/trigger_consumer(四态目录契约),
|
||||
本函数只保留收料批次处理与 SystemExit 兜底。
|
||||
"""
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
print(f'[inbound-trigger] claimed {claimed.name}')
|
||||
# 心跳运行态对齐库存 Worker:领取成功即 busy,处理结束(含归档 failed 后 re-raise)
|
||||
# 由 finally 恢复 idle,保证 SystemExit 兜底路径也不会让监控长期挂 busy。
|
||||
rpa_heartbeat.set_worker_runtime_status('busy')
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
archive_trigger(claimed, 'processed')
|
||||
print(f'[inbound-trigger] archived processed {claimed.name}')
|
||||
except (Exception, SystemExit):
|
||||
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
|
||||
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
|
||||
archive_trigger(claimed, 'failed')
|
||||
print(f'[inbound-trigger] archived failed {claimed.name}')
|
||||
raise
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status('idle')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
|
||||
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
|
||||
drop_dir = _require_dir('FREIGHT_RPA_SHARED_INBOUND_DROP_DIR')
|
||||
trigger_dir = _require_dir('FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR')
|
||||
poll = max(1, int(env('FREIGHT_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
int(env('FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
|
||||
)
|
||||
last_cleanup_mono = 0.0
|
||||
cleanup_interval = cleanup_interval_seconds()
|
||||
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
|
||||
print(
|
||||
'[freight_inbound_rpa_worker] started\n'
|
||||
f' mock={env("FREIGHT_RPA_WORKER_MOCK", "false")}\n'
|
||||
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
|
||||
f' poll_seconds={poll}\n'
|
||||
f' heartbeat_seconds={heartbeat_seconds}\n'
|
||||
f' headless={env("FREIGHT_RPA_WORKER_HEADLESS", "false")} '
|
||||
f'channel={env("FREIGHT_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
|
||||
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
|
||||
f' credential_key={_mask_secret(env("FREIGHT_RPA_CREDENTIAL_KEY"))}\n'
|
||||
f' trigger_dir={trigger_dir}\n'
|
||||
f' drop_dir={drop_dir}\n'
|
||||
f' browser_profile_dir={env("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
|
||||
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
|
||||
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
|
||||
)
|
||||
|
||||
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
|
||||
"""按间隔执行保留清理;启动时强制一轮。
|
||||
|
||||
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
|
||||
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
|
||||
"""
|
||||
nonlocal last_cleanup_mono
|
||||
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
|
||||
return last_cleanup_mono
|
||||
profile_root_raw = str(env('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
|
||||
try:
|
||||
stats = run_worker_disk_cleanup(
|
||||
onhand_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
drop_dir=drop_dir,
|
||||
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
|
||||
log_file=worker_logging.active_log_path(),
|
||||
)
|
||||
print(format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f'[inbound-cleanup] failed: {exc}')
|
||||
return now_mono
|
||||
|
||||
# [STEP 2] 启动即清一轮(对齐库存节奏),避免重启前堆积的归档/孤儿 Profile 撑盘。
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
|
||||
# 启动时立即上报一次心跳(对齐库存 Worker),让监控端第一时间出现独立的
|
||||
# `<hostname>-inbound` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
|
||||
)
|
||||
# 心跳节奏交由独立守护线程承担:收料批量导出会长时间阻塞主循环,
|
||||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||||
rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
while True:
|
||||
for path in sorted(trigger_dir.glob('*.json')):
|
||||
worker_logging.maybe_rotate_open_log()
|
||||
try:
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[inbound-trigger] failed {path.name}: {exc}')
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,182 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Register the test/prod Receipt RPA Worker scheduled tasks in FULL-BACKGROUND mode.
|
||||
|
||||
.DESCRIPTION
|
||||
Runs the Receipt Worker as a background scheduled task with NO visible console and
|
||||
NO visible browser (the Worker launches Playwright headless via -Headless).
|
||||
Deliberately ASCII-only so it parses identically under any Windows console code page.
|
||||
|
||||
Mirrors register_onhand_worker_tasks.ps1 one-to-one, with distinct task names so
|
||||
both Workers can be registered side by side on the same host:
|
||||
- Onhand: "HXOPS Freight Onhand RPA Worker TEST/PROD"
|
||||
- Inbound: "HXOPS Freight Inbound RPA Worker TEST/PROD"
|
||||
|
||||
Shape constraints (same as the onhand registration):
|
||||
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
|
||||
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
|
||||
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
|
||||
decrypted in a non-interactive context.
|
||||
- The RPA account should be configured for auto-logon and must not be locked
|
||||
/ logged-off, otherwise the AtLogOn task does not stay resident.
|
||||
- Before trusting headless, run the headless smoke preflight:
|
||||
set FREIGHT_RPA_WORKER_HEADLESS=true then run crane_login_smoke.py
|
||||
(the DBS portal has no smoke script - verify the first headless run visually).
|
||||
|
||||
Scope:
|
||||
All actions can target one environment or both via -Scope test|prod|all (default all).
|
||||
|
||||
Usage (run in the RPA account's PowerShell):
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Unregister # unregister both
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Register,
|
||||
[switch]$Start,
|
||||
[switch]$Stop,
|
||||
[switch]$Status,
|
||||
[switch]$Unregister,
|
||||
[ValidateSet("test", "prod", "all")]
|
||||
[string]$Scope = "all",
|
||||
[string]$TestApiBase = "http://192.168.100.192:8890",
|
||||
[string]$ProdApiBase = "http://192.168.100.230:8890",
|
||||
[string]$TestRoot = "C:\HxopsRpaTest",
|
||||
[string]$ProdRoot = "C:\HxopsRpaProd",
|
||||
[string]$SecretFile = "C:\HxopsRpaSecrets"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$TestTask = "HXOPS Freight Inbound RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Freight Inbound RPA Worker PROD"
|
||||
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
function Get-TasksForScope {
|
||||
# Return the task name(s) selected by -Scope.
|
||||
param([string]$Scope)
|
||||
switch ($Scope) {
|
||||
"test" { return @($TestTask) }
|
||||
"prod" { return @($ProdTask) }
|
||||
default { return @($TestTask, $ProdTask) }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-Launcher {
|
||||
# Validate the launcher and DPAPI Secret file required for one environment.
|
||||
param([string]$Root, [string]$Environment)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inbound\start_inbound_worker.ps1"
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
|
||||
throw "Launcher not found: $launcher"
|
||||
}
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
|
||||
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
|
||||
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
|
||||
}
|
||||
}
|
||||
|
||||
function New-TaskDefinition {
|
||||
param(
|
||||
[string]$TaskName,
|
||||
[string]$Root,
|
||||
[string]$ApiBase,
|
||||
[string]$EnvName
|
||||
)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inbound\start_inbound_worker.ps1"
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
|
||||
|
||||
# Key differences vs the visible scheduled task:
|
||||
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
|
||||
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
|
||||
$action = New-ScheduledTaskAction `
|
||||
-Execute "powershell.exe" `
|
||||
-Argument $actionArgs `
|
||||
-WorkingDirectory $Root
|
||||
|
||||
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
|
||||
$principal = New-ScheduledTaskPrincipal `
|
||||
-UserId $RunAsUser `
|
||||
-LogonType Interactive `
|
||||
-RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet `
|
||||
-StartWhenAvailable `
|
||||
-RestartCount 10 `
|
||||
-RestartInterval (New-TimeSpan -Minutes 1) `
|
||||
-ExecutionTimeLimit ([TimeSpan]::Zero) `
|
||||
-MultipleInstances IgnoreNew
|
||||
|
||||
Register-ScheduledTask `
|
||||
-TaskName $TaskName `
|
||||
-Action $action `
|
||||
-Trigger $trigger `
|
||||
-Principal $principal `
|
||||
-Settings $settings `
|
||||
-Description "HXOPS Freight Inbound RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
}
|
||||
|
||||
# Default action is Register when no switch is given.
|
||||
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
|
||||
# handled below
|
||||
} else {
|
||||
$Register = $true
|
||||
}
|
||||
|
||||
if ($Unregister) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
|
||||
Write-Host "Unregistered task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Start) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Start-ScheduledTask -TaskName $t
|
||||
Write-Host "Started task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Stop) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t
|
||||
Write-Host "Stopped task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Status) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
if ($tobj) {
|
||||
$info = Get-ScheduledTaskInfo -TaskName $t
|
||||
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
|
||||
Write-Host " (267009 / 0x41301 = running, not an error)"
|
||||
} else {
|
||||
Write-Host "Task not registered yet: $t"
|
||||
}
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Register) {
|
||||
if ($Scope -eq "test" -or $Scope -eq "all") {
|
||||
Assert-Launcher $TestRoot "test"
|
||||
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
|
||||
}
|
||||
if ($Scope -eq "prod" -or $Scope -eq "all") {
|
||||
Assert-Launcher $ProdRoot "prod"
|
||||
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
|
||||
}
|
||||
Write-Host "Registered background task(s) for scope=${Scope}:"
|
||||
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
|
||||
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
|
||||
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
|
||||
exit 0
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
在当前 PowerShell 进程树启动独立货代入站(原收料)RPA Worker。
|
||||
|
||||
.DESCRIPTION
|
||||
只设置 Process 级环境变量和 inbound 专用目录;可与 onhand Worker 并行运行,
|
||||
二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
|
||||
根(各自按 connector+profile 隔离会话目录)。
|
||||
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
|
||||
与库存同口径注入 FREIGHT_RPA_SHARED_SCOPE_ID:心跳线程据此把共享哨兵
|
||||
.hxops_rpa_shared_mount 写进收料 trigger 目录,后端写 trigger 前按
|
||||
心跳+哨兵+scope 做在线 fail-fast 检查(漏配时收料排程报 shared_sentinel_missing)。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
|
||||
[Parameter(Mandatory = $true)][string]$ApiBase,
|
||||
[Parameter(Mandatory = $true)][string]$WorkerRoot,
|
||||
[Parameter(Mandatory = $true)][string]$SecretFile,
|
||||
[string]$PythonExe = 'python.exe',
|
||||
[switch]$Mock,
|
||||
[switch]$Headless,
|
||||
# 默认开启收料会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
|
||||
[switch]$NoSessionReuse,
|
||||
# 兼容旧文档:等价于开启复用(现在默认已开启);与库存开关同名,语义完全一致。
|
||||
[switch]$ReuseSession
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" }
|
||||
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\inbound\inbound_rpa_worker.py'
|
||||
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
|
||||
|
||||
function ConvertTo-PlainText {
|
||||
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
|
||||
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
|
||||
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
|
||||
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
|
||||
}
|
||||
|
||||
$secret = Import-Clixml -LiteralPath $SecretFile
|
||||
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
|
||||
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
|
||||
}
|
||||
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
|
||||
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
|
||||
# 共享 scope 标识(与库存同口径):Windows 本地路径不含共享名,无法推导,必须显式注入;
|
||||
# 心跳线程据此把哨兵写进收料 trigger 目录,后端就绪检查按 scope 比对。
|
||||
if ($Environment -eq 'test') {
|
||||
$scopeId = 'hxops-rpa-test-data'
|
||||
} else {
|
||||
$scopeId = 'hxops-rpa-prod-data'
|
||||
}
|
||||
# 局部变量名刻意避开参数名:PS 变量名大小写不敏感,$sessionReuse 曾与旧开关
|
||||
# $SessionReuse 互为同一变量,字符串 'true'/'false' 覆盖开关值,在部分 Windows build
|
||||
# 上于启动阶段以 SwitchParameter 转换异常爆出(2026-09-30 修复)。开关现统一为
|
||||
# $ReuseSession(与库存同名),局部变量统一为 $sessionReuse(与 onhand Worker 同名,便于契约测试断言)。
|
||||
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
|
||||
if ($ReuseSession -and $NoSessionReuse) {
|
||||
Write-Warning '同时指定 -ReuseSession 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
|
||||
}
|
||||
$processVars = [ordered]@{
|
||||
HXOPS_API_BASE = $ApiBase
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
|
||||
FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
|
||||
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
|
||||
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
|
||||
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'inbound\logs\worker.log'
|
||||
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = '10485760'
|
||||
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = '5'
|
||||
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-inbound"
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
|
||||
# 共享 scope 标识(与库存同口径):缺省时收料 Worker 不写哨兵、心跳 scope 为空,
|
||||
# test/prod 后端收料就绪检查会报 shared_sentinel_missing / shared_scope_mismatch。
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = Join-Path $rpaRoot 'inbound\triggers'
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = Join-Path $rpaRoot 'inbound\drop'
|
||||
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
|
||||
# 本机磁盘保留:与 onhand Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/inbound_* Profile)。
|
||||
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
|
||||
FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = '3600'
|
||||
FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = '24'
|
||||
}
|
||||
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
|
||||
try {
|
||||
Write-Host "Starting inbound RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot sessionReuse=$sessionReuse"
|
||||
& $PythonExe $workerScript
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
finally {
|
||||
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
|
||||
}
|
||||
Reference in new issue
Block a user