Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
7329ccd179
17 files changed
+1195
-184
No files matched your search
@@ -2,12 +2,13 @@
|
||||
services/shipping_notice/line_inventory_match_projection.py
|
||||
|
||||
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
|
||||
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
|
||||
ready+not_found→available=0;result_missing 不得转 0;
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
||||
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
|
||||
load_current_match_facts_by_task 在同一 HTTP 请求内按 task_id memo。
|
||||
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
|
||||
禁止按行重复查库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +16,11 @@ from __future__ import annotations
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
|
||||
|
||||
MATCH_NOT_FOUND = 'not_found'
|
||||
@@ -415,6 +420,55 @@ def resolve_allowed_actions(
|
||||
return [*inv, *line]
|
||||
|
||||
|
||||
def inventory_rpa_is_running(task: Any) -> bool:
|
||||
"""
|
||||
仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
|
||||
|
||||
核心逻辑:查 (task_no, status in queued|running) 是否存在;阶段推进 Job 的
|
||||
queued/running 不得冒充本结果。同一 HTTP 请求内按 task_no memo,供 Case 投影
|
||||
与工作台 stage_context 共享,禁止逐行或重复入口各查一次。
|
||||
|
||||
Args:
|
||||
task: 含 task_no 的正式 OT(或等价命名空间);无 task_no 时返回 False。
|
||||
|
||||
Returns:
|
||||
True 表示存在活动库存 RPA Attempt。
|
||||
"""
|
||||
task_no = str(getattr(task, 'task_no', None) or '').strip()
|
||||
if not task_no:
|
||||
return False
|
||||
try:
|
||||
from flask import g, has_app_context, has_request_context
|
||||
if has_app_context() and has_request_context():
|
||||
cache = getattr(g, '_shipping_inventory_rpa_running_by_task_no', None)
|
||||
if cache is None:
|
||||
cache = {}
|
||||
g._shipping_inventory_rpa_running_by_task_no = cache
|
||||
if task_no in cache:
|
||||
return bool(cache[task_no])
|
||||
else:
|
||||
cache = None
|
||||
except Exception:
|
||||
cache = None
|
||||
|
||||
try:
|
||||
running = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
|
||||
running = False
|
||||
if cache is not None:
|
||||
cache[task_no] = running
|
||||
return running
|
||||
|
||||
|
||||
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
加载 OT 当前行匹配事实,键为冻结订单行 ID。
|
||||
|
||||
@@ -59,7 +59,9 @@ from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
inventory_rpa_is_running as _inventory_rpa_is_running,
|
||||
)
|
||||
|
||||
|
||||
@@ -69,30 +71,6 @@ def _safe_filename(value: Any) -> str | None:
|
||||
return name[:255] or None
|
||||
|
||||
|
||||
def _inventory_rpa_is_running(task: Any) -> bool:
|
||||
"""仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
|
||||
|
||||
自动推进 Job(shipping_notice_run)的 queued/running 只表示阶段推进,
|
||||
不代表库存 RPA 已创建或正在执行;两者必须隔离,避免把明细行伪装成 acquiring_inventory。
|
||||
"""
|
||||
task_no = str(getattr(task, 'task_no', None) or '').strip()
|
||||
if not task_no:
|
||||
return False
|
||||
try:
|
||||
return (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
|
||||
return False
|
||||
|
||||
|
||||
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
|
||||
"""
|
||||
投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。
|
||||
|
||||
@@ -3,8 +3,8 @@ services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、
|
||||
query_service、constants.POSITION_*、process_gate_contract.derive_*、process_gate_projection、
|
||||
line_inventory_match_projection、inventory_candidate_projection、
|
||||
query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、
|
||||
process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、
|
||||
order_review_fulfillment_decision_service(短缺放行模板字段)、
|
||||
order_review_workbench_projection、inventory_source_repository(preparation.source_options)。
|
||||
逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode);
|
||||
@@ -12,8 +12,8 @@ services/shipping_notice/ui_state.py
|
||||
stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT),
|
||||
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
|
||||
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
|
||||
下发 source_options 供行级 override;用户动作统一由 Gate 授权;
|
||||
build_task_ui_state 同请求内复用一次 Gate 摘要(禁止 resolve 再查一遍);
|
||||
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
|
||||
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
|
||||
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
|
||||
"""
|
||||
|
||||
@@ -688,6 +688,75 @@ def _preparation_editable(task: ShippingNotice) -> bool:
|
||||
return status not in _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES
|
||||
|
||||
|
||||
def _stage_capabilities_for_task(
|
||||
task: Any,
|
||||
*,
|
||||
lifecycle_stage: str | None,
|
||||
preparation: dict[str, Any],
|
||||
source_locked: bool,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按阶段能力契约计算通知准备阶段的常驻能力(enabled / disabled_reason)。
|
||||
|
||||
核心逻辑:可用性 = 阶段 + Excel 未生成 + 数据谓词,不由门禁通过与否决定。
|
||||
预条件:改源→有候选源;重抓→有候选源或失败源;重读→已有抓取结果;
|
||||
重匹配→已有匹配结果。右卡展示仍只读处理投影 A;本列表仅供点击后
|
||||
``stageCapabilityBypass`` 查找(见 display-and-button-contract §3.2)。
|
||||
|
||||
Args:
|
||||
task: Notice 或 OT(能力计算不读实体字段,保留形参供调用方透传)。
|
||||
lifecycle_stage: 五阶段码;仅 ``fulfillment_prep`` 下发库存能力。
|
||||
preparation: 已装配的 preparation 摘要(含 source_options / failed /
|
||||
resolved / has_match_result)。
|
||||
source_locked: Excel 已生成时全部能力禁用。
|
||||
|
||||
Returns:
|
||||
能力列表,每项含 code/scope/action_code/enabled/disabled_reason。
|
||||
"""
|
||||
del task # 能力谓词只读 preparation 摘要,避免再查库。
|
||||
from app.services.shipping_notice.process_gate_contract import STAGE_CAPABILITY_DEFINITIONS
|
||||
|
||||
result: list[dict[str, Any]] = []
|
||||
source_options = preparation.get('source_options') or []
|
||||
has_candidates = bool(source_options)
|
||||
failed_codes = preparation.get('failed_source_codes') or []
|
||||
resolved_codes = preparation.get('resolved_source_codes') or []
|
||||
has_match_result = bool(preparation.get('has_match_result'))
|
||||
|
||||
def disabled(reason: str) -> dict[str, Any]:
|
||||
return {'enabled': False, 'disabled_reason': reason}
|
||||
|
||||
for code, definition in STAGE_CAPABILITY_DEFINITIONS.items():
|
||||
if definition.get('stage') != lifecycle_stage:
|
||||
continue
|
||||
cap: dict[str, Any] = {
|
||||
'code': code,
|
||||
'scope': definition.get('scope'),
|
||||
'action_code': definition.get('action_code'),
|
||||
'enabled': False,
|
||||
'disabled_reason': None,
|
||||
}
|
||||
if source_locked:
|
||||
cap.update(disabled('excel_locked'))
|
||||
elif code == 'retry_inventory_preparation':
|
||||
# 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。
|
||||
retry_available = has_candidates or bool(failed_codes)
|
||||
cap['enabled'] = retry_available
|
||||
cap['disabled_reason'] = None if retry_available else 'no_candidates'
|
||||
elif code == 'override_line_inventory_source':
|
||||
cap['enabled'] = has_candidates
|
||||
cap['disabled_reason'] = None if has_candidates else 'no_candidates'
|
||||
elif code == 'reload_inventory_result':
|
||||
has_prior = bool(resolved_codes)
|
||||
cap['enabled'] = has_prior
|
||||
cap['disabled_reason'] = None if has_prior else 'no_prior_result'
|
||||
elif code == 'retry_inventory_matching':
|
||||
cap['enabled'] = has_match_result
|
||||
cap['disabled_reason'] = None if has_match_result else 'no_match_result'
|
||||
result.append(cap)
|
||||
return result
|
||||
|
||||
|
||||
def _build_stage_context(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
@@ -703,7 +772,9 @@ def _build_stage_context(
|
||||
source_code=Match 正式匹配源(禁止用候选回填,避免与匹配结论混淆);
|
||||
短缺行另投影发货模板放行字段;匹配成功无短缺行投影 can_fulfill_complete_line;
|
||||
preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉;
|
||||
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询。
|
||||
preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染);
|
||||
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询;
|
||||
inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
|
||||
@@ -712,6 +783,7 @@ def _build_stage_context(
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
inventory_rpa_is_running,
|
||||
load_current_match_facts_by_task,
|
||||
project_line_inventory_view,
|
||||
)
|
||||
@@ -741,6 +813,8 @@ def _build_stage_context(
|
||||
if snapshot is not None else []
|
||||
)
|
||||
match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None))
|
||||
# [STEP] 与 Case 投影同源:库存 RPA 运行态只查一次 Attempt(请求内 memo),再传入各行纯函数。
|
||||
inventory_rpa_running = inventory_rpa_is_running(order_task)
|
||||
candidate_codes_by_line_no: dict[int, list[str]] = {}
|
||||
if getattr(order_task, 'id', None) is not None and isinstance(order_task, ShippingOrderTask):
|
||||
for candidate_line in get_active_candidate_lines(order_task):
|
||||
@@ -780,6 +854,7 @@ def _build_stage_context(
|
||||
stored_line_status=None,
|
||||
decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
inventory_rpa_running=inventory_rpa_running,
|
||||
)
|
||||
allowed = list((fact or {}).get('allowed_source_codes_snapshot') or [])
|
||||
candidate_codes = candidate_codes_by_line_no.get(int(line_no), []) if line_no is not None else []
|
||||
@@ -920,33 +995,47 @@ def _build_stage_context(
|
||||
'not_started'
|
||||
)
|
||||
source_locked = latest_export_artifact(task) is not None or latest_export_artifact(order_task) is not None
|
||||
return {
|
||||
'preparation': {
|
||||
'status': preparation_status,
|
||||
'reason_code': gate.get('blocking_reason_code') or None,
|
||||
'editable': _preparation_editable(task),
|
||||
'source_locked': source_locked,
|
||||
'frozen_order': {
|
||||
'task_no': getattr(order_task, 'task_no', None) or task.task_no,
|
||||
'snapshot_id': snapshot_id,
|
||||
},
|
||||
'inventory_source_code': facts.get('inventory_source_code'),
|
||||
'match_status': facts.get('match_status'),
|
||||
'frozen_order_lines': frozen_order_lines,
|
||||
'lines': preparation_lines,
|
||||
'has_match_result': has_match_result,
|
||||
# 任务级 inventory_sources 只说明取数进度;行级看 selected_source_code / source_code。
|
||||
'inventory_sources': inventory_sources,
|
||||
'source_options': source_options,
|
||||
'inventory_file': {
|
||||
'available': downloadable_inventory is not None,
|
||||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||||
},
|
||||
'artifact': {
|
||||
'file_name': artifact.file_name if artifact is not None else None,
|
||||
'status': artifact.status if artifact is not None else 'not_generated',
|
||||
},
|
||||
# [STEP] 先装配 preparation 再追加 capabilities,避免字面量自引用。
|
||||
preparation = {
|
||||
'status': preparation_status,
|
||||
'reason_code': gate.get('blocking_reason_code') or None,
|
||||
'editable': _preparation_editable(task),
|
||||
'source_locked': source_locked,
|
||||
'frozen_order': {
|
||||
'task_no': getattr(order_task, 'task_no', None) or task.task_no,
|
||||
'snapshot_id': snapshot_id,
|
||||
},
|
||||
'inventory_source_code': facts.get('inventory_source_code'),
|
||||
'match_status': facts.get('match_status'),
|
||||
'frozen_order_lines': frozen_order_lines,
|
||||
'lines': preparation_lines,
|
||||
'has_match_result': has_match_result,
|
||||
# 任务级 inventory_sources 只说明取数进度;行级看 selected_source_code / source_code。
|
||||
'inventory_sources': inventory_sources,
|
||||
# 供阶段能力预条件:失败可重试源 / 已有抓取结果。
|
||||
'failed_source_codes': [
|
||||
item['source_code'] for item in inventory_sources
|
||||
if str(item.get('status') or '').strip().lower() == 'failed'
|
||||
],
|
||||
'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []),
|
||||
'source_options': source_options,
|
||||
'inventory_file': {
|
||||
'available': downloadable_inventory is not None,
|
||||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||||
},
|
||||
'artifact': {
|
||||
'file_name': artifact.file_name if artifact is not None else None,
|
||||
'status': artifact.status if artifact is not None else 'not_generated',
|
||||
},
|
||||
}
|
||||
preparation['capabilities'] = _stage_capabilities_for_task(
|
||||
task,
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
preparation=preparation,
|
||||
source_locked=source_locked,
|
||||
)
|
||||
return {
|
||||
'preparation': preparation,
|
||||
'upload': {
|
||||
'outcome': upload_outcome,
|
||||
# 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能
|
||||
|
||||
@@ -623,6 +623,155 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
|
||||
assert not log_path.exists()
|
||||
|
||||
|
||||
def _load_worker_disk_cleanup():
|
||||
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
|
||||
spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# dataclass 在装饰阶段会查 sys.modules;动态加载须先登记。
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypatch, tmp_path):
|
||||
"""
|
||||
超过保留期的归档应删除;进行中的 trigger、会话 Profile、cleanup_queue 必须保留。
|
||||
|
||||
断言意图:验证磁盘清理只碰“归档/临时物”,不误删业务进行中文件。
|
||||
"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
now = time.time()
|
||||
old = now - (10 * 86400)
|
||||
recent = now - 3600
|
||||
|
||||
inv_trigger = tmp_path / "inventory_triggers"
|
||||
upload_trigger = tmp_path / "upload_triggers"
|
||||
drop = tmp_path / "inventory_drop"
|
||||
queue = tmp_path / "upload_queue"
|
||||
profiles = tmp_path / "browser_profile"
|
||||
logs = tmp_path / "logs"
|
||||
for path in (
|
||||
inv_trigger / "processed",
|
||||
inv_trigger / "failed",
|
||||
upload_trigger / "processed",
|
||||
drop / "processed",
|
||||
drop / ".hxops_quarantine",
|
||||
drop / ".cleanup_queue",
|
||||
drop / ".cleanup_failed",
|
||||
queue,
|
||||
profiles,
|
||||
logs,
|
||||
):
|
||||
path.mkdir(parents=True)
|
||||
|
||||
active_trigger = inv_trigger / "inventory_export_SN-ACTIVE.json"
|
||||
active_trigger.write_text("{}", encoding="utf-8")
|
||||
os.utime(active_trigger, (old, old))
|
||||
|
||||
stale_processed = inv_trigger / "processed" / "inventory_export_SN-OLD.json"
|
||||
stale_processed.write_text("{}", encoding="utf-8")
|
||||
os.utime(stale_processed, (old, old))
|
||||
|
||||
fresh_processed = inv_trigger / "processed" / "inventory_export_SN-NEW.json"
|
||||
fresh_processed.write_text("{}", encoding="utf-8")
|
||||
os.utime(fresh_processed, (recent, recent))
|
||||
|
||||
stale_drop = drop / "processed" / "inventory_OLD.xlsx"
|
||||
stale_drop.write_bytes(b"xlsx")
|
||||
os.utime(stale_drop, (old, old))
|
||||
|
||||
stale_root_drop = drop / "inventory_STALE.xlsx"
|
||||
stale_root_drop.write_bytes(b"xlsx")
|
||||
os.utime(stale_root_drop, (old, old))
|
||||
|
||||
cleanup_job = drop / ".cleanup_queue" / "move_abc.json"
|
||||
cleanup_job.write_text("{}", encoding="utf-8")
|
||||
os.utime(cleanup_job, (old, old))
|
||||
|
||||
stale_queue = queue / "upload_OLD.xlsx"
|
||||
stale_queue.write_bytes(b"xlsx")
|
||||
os.utime(stale_queue, (old, old))
|
||||
|
||||
log_path = logs / "worker.log"
|
||||
log_path.write_text("current", encoding="utf-8")
|
||||
stale_backup = Path(f"{log_path}.1")
|
||||
stale_backup.write_text("old-backup", encoding="utf-8")
|
||||
os.utime(stale_backup, (old, old))
|
||||
|
||||
session_profile = profiles / "dsv360__DEFAULT_session"
|
||||
session_profile.mkdir()
|
||||
(session_profile / "Cookies").write_text("keep", encoding="utf-8")
|
||||
os.utime(session_profile, (old, old))
|
||||
|
||||
orphan_run = profiles / "run_orphan"
|
||||
orphan_run.mkdir()
|
||||
(orphan_run / "Cookies").write_text("drop", encoding="utf-8")
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
stats = cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
upload_trigger_dir=upload_trigger,
|
||||
drop_dir=drop,
|
||||
upload_queue_dir=queue,
|
||||
browser_profile_dir=profiles,
|
||||
log_file=log_path,
|
||||
now_unix=now,
|
||||
)
|
||||
|
||||
assert not stale_processed.exists()
|
||||
assert fresh_processed.exists()
|
||||
assert active_trigger.exists()
|
||||
assert not stale_drop.exists()
|
||||
assert not stale_root_drop.exists()
|
||||
assert cleanup_job.exists()
|
||||
assert not stale_queue.exists()
|
||||
assert log_path.exists()
|
||||
assert not stale_backup.exists()
|
||||
assert session_profile.exists()
|
||||
assert not orphan_run.exists()
|
||||
assert stats.deleted_files >= 4
|
||||
assert stats.deleted_dirs >= 1
|
||||
|
||||
|
||||
def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path):
|
||||
"""DISK_RETENTION_DAYS<=0 时不删归档;孤儿 Profile 仍可按独立配置清理。"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
now = time.time()
|
||||
old = now - (10 * 86400)
|
||||
|
||||
inv_trigger = tmp_path / "inventory_triggers"
|
||||
processed = inv_trigger / "processed"
|
||||
profiles = tmp_path / "browser_profile"
|
||||
processed.mkdir(parents=True)
|
||||
profiles.mkdir(parents=True)
|
||||
|
||||
stale_processed = processed / "old.json"
|
||||
stale_processed.write_text("{}", encoding="utf-8")
|
||||
os.utime(stale_processed, (old, old))
|
||||
|
||||
orphan_run = profiles / "run_orphan"
|
||||
orphan_run.mkdir()
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
browser_profile_dir=profiles,
|
||||
now_unix=now,
|
||||
)
|
||||
|
||||
assert stale_processed.exists()
|
||||
assert not orphan_run.exists()
|
||||
|
||||
|
||||
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1483,8 +1632,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
|
||||
|
||||
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
|
||||
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
|
||||
def test_prepare_reusable_session_profile_keeps_existing_dir(tmp_path):
|
||||
"""持久 Profile 不按本地时间清空;已有内容应保留供站点会话继续复用。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
profile_dir = tmp_path / "dsv360__OLD_session"
|
||||
profile_dir.mkdir(parents=True)
|
||||
@@ -1495,7 +1644,6 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
|
||||
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
|
||||
|
||||
prepared = worker._prepare_reusable_session_profile(
|
||||
profile_dir,
|
||||
@@ -1504,9 +1652,11 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
|
||||
)
|
||||
|
||||
assert prepared == profile_dir
|
||||
assert not stale_marker.exists()
|
||||
assert stale_marker.exists()
|
||||
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
|
||||
assert float(meta["created_at_unix"]) > created
|
||||
assert float(meta["created_at_unix"]) == created
|
||||
assert "ttl_hours" not in meta
|
||||
|
||||
|
||||
def test_is_dsv_username_page_ignores_login_method_page_text():
|
||||
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
|
||||
|
||||
@@ -612,6 +612,65 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
|
||||
|
||||
def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
|
||||
"""库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。
|
||||
|
||||
与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。
|
||||
"""
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='ui-rpa-running', email='ui-rpa-running@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='inventory_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||||
reservation_id='RSV-RPA', part_number='PN-RPA', qty='10', field_values_json={},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
required_qty='10',
|
||||
available_qty='7',
|
||||
matched_qty='7',
|
||||
shortage_qty='3',
|
||||
reservation_id='RSV-RPA',
|
||||
part_number='PN-RPA',
|
||||
inventory_source_code='DBS_DUB',
|
||||
is_current=True,
|
||||
))
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code='DBS_DUB',
|
||||
attempt_no=1,
|
||||
source_run_no='PSR-UI-RPA-1',
|
||||
status='running',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||||
line = preparation['lines'][0]
|
||||
# 关键断言:RPA 运行中必须清空库存动作,前端 Bot 不得渲染/触发。
|
||||
assert line['user_line_status'] == 'acquiring_inventory'
|
||||
assert line['inventory_allowed_actions'] == []
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
|
||||
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -59,7 +59,7 @@ def test_inventory_running_is_not_inferred_from_stage_automation_job():
|
||||
"""阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。"""
|
||||
task = SimpleNamespace(task_no='OT-TEST-1')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
) as query:
|
||||
query.filter.return_value.first.return_value = None
|
||||
assert _inventory_rpa_is_running(task) is False
|
||||
@@ -69,7 +69,7 @@ def test_inventory_running_requires_queued_or_running_attempt():
|
||||
"""只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。"""
|
||||
task = SimpleNamespace(task_no='OT-TEST-2')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
) as query:
|
||||
query.filter.return_value.first.return_value = SimpleNamespace(status='queued')
|
||||
assert _inventory_rpa_is_running(task) is True
|
||||
|
||||
@@ -243,6 +243,10 @@ services:
|
||||
volumes:
|
||||
- ./oracle_client:/app/oracle_client:ro
|
||||
- hxops_runtime_data:/app/data
|
||||
# 按需库存准备由 shipping-worker 写 RPA trigger,必须与 backend/schedule-worker 同挂 CIFS;
|
||||
# 否则容器本地 mkdir /mnt/hxops-rpa-*-data 成功、DB 记 trigger_written,但 Windows 共享盘无文件。
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
|
||||
@@ -253,7 +253,10 @@ release_required_fields, release_field_resolution_error, decision}` 驱动,**
|
||||
> `user_line_status`/`is_shortage` 等(零逐行 SQL,见 §6 落地清单)。短缺行另复用
|
||||
> `_shortage_release_required_fields` 下发 `release_template_fields`/`release_required_fields`;
|
||||
> 解析失败时写 `release_field_resolution_error`(fail-closed,禁止只填原因)。`decision` 仍为 `null`。
|
||||
|
||||
>
|
||||
> **RPA 运行中(与 Case 同源)**:行循环外调用一次 `inventory_rpa_is_running(order_task)`(请求级 memo),
|
||||
> 再传入各行 `project_line_inventory_view`;禁止逐行查 Attempt,也禁止用阶段 Job / 右卡
|
||||
> `userStatus` 推断。运行中 `inventory_allowed_actions=[]`。
|
||||
---
|
||||
|
||||
## 4. 前后端如何配合(冻结)
|
||||
|
||||
@@ -2064,6 +2064,9 @@ $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\brow
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24"
|
||||
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码"
|
||||
@@ -2302,21 +2305,24 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
sudo systemctl restart hxops-backend
|
||||
```
|
||||
|
||||
如果使用 Docker Compose,需把挂载目录映射进容器:
|
||||
如果使用 Docker Compose,需把挂载目录映射进**写 RPA trigger 的容器**(`hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker`;按需库存准备由 shipping-worker 写入):
|
||||
|
||||
```yaml
|
||||
# 三个服务均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。
|
||||
容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。变更挂载后须 `--force-recreate` 相关服务,否则旧容器仍写本地假目录。
|
||||
|
||||
#### 1.5.10 Windows RPA 主机:进程级环境与自启动
|
||||
|
||||
同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。
|
||||
|
||||
库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,默认 TTL 24 小时(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` / `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`)。会话过期或站点侧失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`;旧参数 `-ReuseDsvSession` 仍兼容。
|
||||
库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`;旧参数 `-ReuseDsvSession` 仍兼容。
|
||||
|
||||
Worker 本机磁盘保留(`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。
|
||||
|
||||
Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass:
|
||||
|
||||
@@ -2477,14 +2483,15 @@ Get-ChildItem "$rpaDataRoot\inventory_drop"
|
||||
|
||||
##### 1.5.13.2 Linux 测试服务器:部署、启动与停止
|
||||
|
||||
以下操作在**测试服务器的项目根目录**执行。首次部署按 `1.5.6` 至 `1.5.9` 完成 Windows 测试共享 `hxops-rpa-test-data` 的访问、`/mnt/hxops-rpa-test-data` 挂载及 `.env.test` 配置;不应使用正式共享目录。启动前确认 `docker-compose.yml` 的 `hxops-backend` 已 bind mount 测试目录到同一路径,否则宿主机虽已挂载,容器内仍无法写入 trigger 或读取导出文件。
|
||||
以下操作在**测试服务器的项目根目录**执行。首次部署按 `1.5.6` 至 `1.5.9` 完成 Windows 测试共享 `hxops-rpa-test-data` 的访问、`/mnt/hxops-rpa-test-data` 挂载及 `.env.test` 配置;不应使用正式共享目录。启动前确认 `docker-compose.yml` 的 `hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker` 均已 bind mount 测试目录到同一路径;只挂 backend 时,按需库存 Gate Job(shipping-worker)会写到容器本地假目录,Windows 共享盘看不到 trigger。
|
||||
|
||||
```yaml
|
||||
# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
```
|
||||
|
||||
确认挂载、设置 Compose 环境文件并启动后端及知识库 Worker:
|
||||
确认挂载、设置 Compose 环境文件并启动后端、shipping-worker 及知识库 Worker:
|
||||
|
||||
```bash
|
||||
mountpoint -q /mnt/hxops-rpa-test-data
|
||||
@@ -2492,10 +2499,12 @@ test -d /mnt/hxops-rpa-test-data/inventory_triggers
|
||||
|
||||
export COMPOSE_ENV_BASENAME=.env.test
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker
|
||||
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker
|
||||
docker compose --env-file .env.test ps
|
||||
docker compose --env-file .env.test exec -T hxops-backend \
|
||||
sh -lc 'test -d /mnt/hxops-rpa-test-data/inventory_triggers && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
docker compose --env-file .env.test exec -T hxops-shipping-worker \
|
||||
sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
```
|
||||
|
||||
随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=test`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。
|
||||
@@ -2512,9 +2521,10 @@ docker compose --env-file .env.test stop hxops-kb-worker hxops-backend
|
||||
|
||||
##### 1.5.13.3 Linux 正式服务器:部署、启动与停止
|
||||
|
||||
正式环境步骤与测试环境相同,但全部路径、scope、Windows Worker、API Base 和密钥必须是正式环境值。首次部署按 `1.5.6` 至 `1.5.9` 配置 Windows 正式共享 `hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data`;仅在测试导出、账号、文件结构和回调均验收后才开启正式 RPA。启动前确认 `docker-compose.yml` 的 `hxops-backend` 具有正式共享的 bind mount:
|
||||
正式环境步骤与测试环境相同,但全部路径、scope、Windows Worker、API Base 和密钥必须是正式环境值。首次部署按 `1.5.6` 至 `1.5.9` 配置 Windows 正式共享 `hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data`;仅在测试导出、账号、文件结构和回调均验收后才开启正式 RPA。启动前确认 `docker-compose.yml` 的 `hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker` 均具有正式共享的 bind mount:
|
||||
|
||||
```yaml
|
||||
# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
@@ -2527,10 +2537,12 @@ test -d /mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
|
||||
export COMPOSE_ENV_BASENAME=.env.prod
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker
|
||||
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker
|
||||
docker compose --env-file .env.prod ps
|
||||
docker compose --env-file .env.prod exec -T hxops-backend \
|
||||
sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
docker compose --env-file .env.prod exec -T hxops-shipping-worker \
|
||||
sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
```
|
||||
|
||||
再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`;该参考仅作为受信 RPA 成功回调的外部参考,不要求人工录入或上传回执。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false`、`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工按业务单号确认已上传作为受控降级路径。
|
||||
|
||||
@@ -149,6 +149,24 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows stage needs_action once even when backend also reports failed for the same files', async () => {
|
||||
// 后端对失败文件会同时写入 needs_action 与 failed;阶段卡只能读 needs_action,禁止再加 failed。
|
||||
const processing = processingProjection({
|
||||
lifecycle_nodes: [
|
||||
{ code: 'intake_parse', status: 'pending', summary: { total: 0, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'order_review', status: 'blocked', summary: { total: 3, completed: 0, needs_action: 3, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'fulfillment_prep', status: 'blocked', summary: { total: 2, completed: 0, needs_action: 2, processing: 0, failed: 2, blocking_reason: null } },
|
||||
{ code: 'freight_upload', status: 'pending', summary: { total: 0, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'upload_complete', status: 'pending', summary: { total: 0, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection()]);
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-stage-filter-fulfillment_prep"]').text()).toBe('通知准备2 待处理');
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-stage-filter-order_review"]').text()).toBe('订单复核3 待处理');
|
||||
});
|
||||
|
||||
it('separates ignored Excel attachments from order-file progress totals', async () => {
|
||||
const ignoredExcel = fileProjection({
|
||||
workItemNo: 'PLAN:EML-EXCEL:report',
|
||||
|
||||
@@ -162,12 +162,13 @@ function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillm
|
||||
}
|
||||
/**
|
||||
* 阶段卡优先展示后端统计中的最高关注状态,避免仅显示数字而无法辨识处理中或待处理。
|
||||
* 核心逻辑:后端已把 failed 计入 needs_action,前端只读 needs_action,禁止再加 failed,否则会翻倍。
|
||||
* @param node - 后端五阶段节点及其汇总。
|
||||
* @returns 国际化状态摘要。
|
||||
*/
|
||||
function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
|
||||
const summary = node.summary;
|
||||
const needsAction = Number(summary?.needs_action || 0) + Number(summary?.failed || 0);
|
||||
const needsAction = Number(summary?.needs_action || 0);
|
||||
if (needsAction > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.needsAction', { count: needsAction });
|
||||
if (Number(summary?.processing || 0) > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.processing', { count: summary?.processing });
|
||||
if (Number(summary?.completed || 0) > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.completed', { count: summary?.completed });
|
||||
|
||||
@@ -1471,6 +1471,71 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).not.toContain('自动处理失败');
|
||||
});
|
||||
|
||||
it('submits retry_inventory_preparation from A even when B.actions lacks the code', async () => {
|
||||
// 回归:右卡只读 A.primary_action 展示「重新获取库存(RPA)」;若仍按 B.actions
|
||||
// 授权,会落到「未识别的动作」。A 展示即写路径授权;capabilities 可作 bypass。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 905, confirmed_task_no: 'SN-RPA-A-ONLY',
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-RPA-A-ONLY',
|
||||
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
|
||||
progressVersion: 3, currentGate: { status: 'blocked_retryable' },
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
|
||||
primary_action: { code: 'retry_inventory_preparation' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
} as any;
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-RPA-A-ONLY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
// B.actions 故意为空:模拟展示单源收敛后 B 滞后 / 无同码。
|
||||
actions: { primary: null, secondary: [] },
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-RPA-A-ONLY',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
|
||||
},
|
||||
allowed_actions: ['retry_inventory_preparation'],
|
||||
recovery_targets: [{ action_code: 'retry_inventory_preparation' }],
|
||||
},
|
||||
stage_context: {
|
||||
preparation: {
|
||||
status: 'blocked', source_locked: false, source_options: [{ source_code: 'DSV' }],
|
||||
capabilities: [{
|
||||
code: 'retry_inventory_preparation', scope: 'task',
|
||||
action_code: 'retry_inventory_preparation', enabled: true,
|
||||
}],
|
||||
frozen_order_lines: [], lines: [],
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
submitProcessGatePrimaryActionMock.mockClear();
|
||||
messageMocks.info.mockClear();
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(messageMocks.info).not.toHaveBeenCalledWith(
|
||||
expect.stringMatching(/未识别的动作|Unrecognized action/),
|
||||
);
|
||||
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
expect.objectContaining({
|
||||
actionCode: 'retry_inventory_preparation',
|
||||
stageCapabilityBypass: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
|
||||
@@ -1829,16 +1829,26 @@ async function handleCurrentTaskAction(
|
||||
) {
|
||||
const params = (parameters || {}) as Record<string, unknown>;
|
||||
const normalizedCode = String(code || '').trim();
|
||||
// [AUTHORITY] 正式 OT 的所有可写动作都从任务详情的 ui_state.actions 原样委托。
|
||||
// 缺少同码的正式动作即不执行,不能降级到历史 Projection 或 Case 快照。
|
||||
// [AUTHORITY] 正式 OT:右卡按钮只读 A(shippingProcessingProjection.ui_state),
|
||||
// 点击必须与展示同源授权;capabilities 供 stageCapabilityBypass,B.actions
|
||||
// 仅作兼容回退。禁止「A 已展示、B 无同码」时落到 actionUnknown。
|
||||
if (hasFormalOt.value) {
|
||||
// [STAGE_CAPABILITY] 阶段能力(重抓/重读/改源)从右侧卡点击时,走 submitFormalGateAction
|
||||
// 的能力分支——绕过门禁 gate-membership 守卫并直达后端 request_gate_action。
|
||||
if (!(await ensureFormalTaskDetailReady())) return;
|
||||
// [STAGE_CAPABILITY] 命中能力(含 disabled)走 submitFormalGateAction,
|
||||
// 由能力分支展示 disabled_reason 或 stageCapabilityBypass 提交。
|
||||
const capability = formalPreparationContext.value?.capabilities?.find(
|
||||
(cap) => cap.enabled && String(cap.action_code || '').trim() === normalizedCode,
|
||||
(cap) => String(cap.action_code || '').trim() === normalizedCode,
|
||||
);
|
||||
if (capability) {
|
||||
if (!(await ensureFormalTaskDetailReady())) return;
|
||||
await submitFormalGateAction(normalizedCode);
|
||||
return;
|
||||
}
|
||||
// [§2.4 单源] A 已下发的主/侧路动作与展示同源,直接提交 Gate,不要求 B.actions。
|
||||
const aPrimary = String(currentTaskUiState.value?.primary_action?.code || '').trim();
|
||||
const aSecondaryHit = (currentTaskUiState.value?.secondary_actions || []).some(
|
||||
(action) => action.enabled && String(action.code || '').trim() === normalizedCode,
|
||||
);
|
||||
if (normalizedCode && (normalizedCode === aPrimary || aSecondaryHit)) {
|
||||
await submitFormalGateAction(normalizedCode);
|
||||
return;
|
||||
}
|
||||
@@ -1849,7 +1859,6 @@ async function handleCurrentTaskAction(
|
||||
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code: normalizedCode }));
|
||||
return;
|
||||
}
|
||||
if (!(await ensureFormalTaskDetailReady())) return;
|
||||
await executeFormalTaskAction(formalAction, params);
|
||||
return;
|
||||
}
|
||||
@@ -3548,8 +3557,16 @@ const submitFormalGateAction = async (
|
||||
const authorized = formalTaskActions.value.some((action) => (
|
||||
action.enabled && String(action.code || '').trim() === normalizedCode
|
||||
));
|
||||
// [§2.4 单源] A 已展示的主/侧路动作与右卡同源,允许作为写路径授权(B.actions 可能滞后)。
|
||||
const aPrimary = String(currentTaskUiState.value?.primary_action?.code || '').trim();
|
||||
const aAuthorized = Boolean(normalizedCode) && (
|
||||
normalizedCode === aPrimary
|
||||
|| (currentTaskUiState.value?.secondary_actions || []).some(
|
||||
(action) => action.enabled && String(action.code || '').trim() === normalizedCode,
|
||||
)
|
||||
);
|
||||
// [STEP] 阶段能力分支:capability 命中优先按 enabled/disabled_reason 裁决,
|
||||
// 仅在未命中能力时回退到通用 Gate noAction 校验(Task 5)。
|
||||
// 仅在未命中能力时回退到 A 展示授权或 B.actions / Gate noAction 校验。
|
||||
const capability = formalPreparationContext.value?.capabilities?.find(
|
||||
(c) => String(c.action_code || '') === normalizedCode,
|
||||
);
|
||||
@@ -3560,7 +3577,7 @@ const submitFormalGateAction = async (
|
||||
: t('workspace.shippingNotice.processGate.noAction'));
|
||||
return;
|
||||
}
|
||||
} else if (!normalizedCode || !gate || !authorized) {
|
||||
} else if (!normalizedCode || !gate || !(authorized || aAuthorized)) {
|
||||
msg.info(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return;
|
||||
}
|
||||
|
||||
+49
-33
@@ -38,6 +38,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `common/rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 |
|
||||
| `common/download_artifact_fallback.py` | 浏览器已落盘但 Playwright 未返回 Download 时的下载适配器 |
|
||||
| `common/rpa_heartbeat.py` | 向后端上报心跳 + 共享目录哨兵(原 `freight_rpa_heartbeat.py`) |
|
||||
| `common/worker_disk_cleanup.py` | Worker 本机磁盘保留清理(日志备份 / trigger·drop 归档 / 孤儿 run_* Profile) |
|
||||
| `common/new_rpa_worker_secret.ps1` | 生成当前用户可解密的 DPAPI Secret 文件 |
|
||||
| `connectors/` | **登录网站 / 报表系统自动化**(库存与收料共用) |
|
||||
| `connectors/dsv/` | DSV 360 连接器:`dsv_driver` / `dsv_auth` / `dsv_auth_login_flow` / `dsv_session` / `dsv_navigation` / `dsv_report_export` / `dsv_debug` / `dsv_report_parameters` / `dsv_login_smoke` / `dsv_export_timeout_diagnostics` |
|
||||
@@ -77,8 +78,13 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
|
||||
| `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS` | 持久 Profile 最长保留小时数,默认 `24`;超时后清空目录并重新登录 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响;站点会话失效时自动重登 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | Worker 文件日志路径(stdout/stderr tee) |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES` | 单日志文件大小上限(默认 10MB);启动与周期清理时按大小轮转 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT` | 日志备份个数(默认 5) |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS` | 本机归档保留天数(默认 7);`<=0` 禁用按天清理。覆盖 trigger `processed/failed`、drop 归档/隔离、upload_queue、日志备份 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS` | 磁盘清理周期秒数(默认 3600);Worker 启动时会立即清一轮 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS` | 孤儿临时 `run_*` Profile 最大存活小时(默认 24);`*_session` 会话 Profile 永不删除 |
|
||||
|
||||
|
||||
新部署只使用 `new_rpa_worker_secret.ps1` + `start_rpa_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。
|
||||
@@ -88,11 +94,16 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。
|
||||
|
||||
DSV/Crane 库存导出默认复用浏览器 Profile(按 `connector + rpa_profile_code` 隔离目录,
|
||||
默认保留 24 小时)。同一 WorkerRoot 只跑一个 Worker,任务串行消费;会话过期或站点踢登
|
||||
仍回落现有登录流程。上传任务保持一次性 Profile。若需强制每次全新登录,启动时加
|
||||
`-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`
|
||||
长期保留)。同一 WorkerRoot 只跑一个 Worker,任务串行消费;是否免登取决于货代站点会话
|
||||
是否仍有效,失效时回落现有登录流程。上传任务保持一次性 Profile。若需强制每次全新登录,
|
||||
启动时加 `-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`
|
||||
仍兼容,但请改用 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`。
|
||||
|
||||
Worker 默认启用本机磁盘保留清理(`scripts/rpa/common/worker_disk_cleanup.py`):启动与每小时
|
||||
清理超过保留期的 `processed/failed` trigger、drop 归档(含 `processed` /
|
||||
`.hxops_quarantine` / `.cleanup_failed`)、过期 drop 根导出文件、upload_queue 残留、
|
||||
日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile。**不删除**进行中的 trigger 根 JSON、
|
||||
可复用会话 Profile、以及活跃的 `.cleanup_queue`。
|
||||
### DSV WMS Upload Tool
|
||||
|
||||
已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和
|
||||
@@ -521,20 +532,21 @@ SHIPPING_NOTICE_TOOL_API_KEY
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
|
||||
```
|
||||
|
||||
如使用 Docker Compose,容器必须挂载对应目录:
|
||||
如使用 Docker Compose,**写 RPA trigger 的容器都必须挂载**对应目录:`hxops-backend`、`hxops-schedule-worker`(定时导出)、`hxops-shipping-worker`(按需库存准备 Gate Job)。只挂 backend 时,shipping-worker 会在容器本地假目录写 JSON,DB 记 `trigger_written`,但 Windows 共享盘无文件。
|
||||
|
||||
```yaml
|
||||
services:
|
||||
hxops-backend:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
重建/启动后端容器后验证:
|
||||
重建相关容器后验证:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.test up -d --force-recreate hxops-shipping-worker
|
||||
docker compose --env-file .env.test exec -T hxops-backend sh -lc 'ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
docker compose --env-file .env.test exec -T hxops-shipping-worker sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
docker compose --env-file .env.prod exec -T hxops-backend sh -lc 'ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
```
|
||||
|
||||
@@ -861,6 +873,9 @@ $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\brow
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24"
|
||||
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号"
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码"
|
||||
@@ -1022,14 +1037,13 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
sudo systemctl restart hxops-backend
|
||||
```
|
||||
|
||||
如使用 Docker Compose,必须将宿主机挂载目录 bind mount 到容器内相同路径:
|
||||
如使用 Docker Compose,必须将宿主机挂载目录 bind mount 到**写 trigger 的容器**内相同路径(`hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker`):
|
||||
|
||||
```yaml
|
||||
services:
|
||||
hxops-backend:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
|
||||
@@ -1188,13 +1202,12 @@ sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/linux_write_test
|
||||
sudo -u hxops rm /mnt/hxops-rpa-test-data/inventory_triggers/linux_write_test.txt
|
||||
```
|
||||
|
||||
`.env.test` 必须指向 `/mnt/hxops-rpa-test-data`,scope 必须为 `hxops-rpa-test-data`。此外,`docker-compose.yml` 的 `hxops-backend` 必须将宿主机挂载目录 bind mount 到容器**同一路径**,否则容器内无法看到 RPA 文件:
|
||||
`.env.test` 必须指向 `/mnt/hxops-rpa-test-data`,scope 必须为 `hxops-rpa-test-data`。此外,`docker-compose.yml` 的 `hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker` 都必须将宿主机挂载目录 bind mount 到容器**同一路径**(按需库存 trigger 由 shipping-worker 写入),否则容器内写到本地假目录、Windows 看不到:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
hxops-backend:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
```
|
||||
|
||||
在测试服务器项目根目录启动并验证容器:
|
||||
@@ -1203,16 +1216,18 @@ services:
|
||||
export COMPOSE_ENV_BASENAME=.env.test
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
|
||||
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker
|
||||
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker
|
||||
docker compose --env-file .env.test ps
|
||||
docker compose --env-file .env.test exec -T hxops-backend \
|
||||
sh -lc 'test -d /mnt/hxops-rpa-test-data/inventory_triggers && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
docker compose --env-file .env.test exec -T hxops-shipping-worker \
|
||||
sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
|
||||
```
|
||||
|
||||
若这是首次把 bind mount 加入 Compose,必须在变更后重新创建后端容器:
|
||||
若这是首次把 bind mount 加入 Compose,必须在变更后重新创建相关容器:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.test up -d --force-recreate hxops-backend
|
||||
docker compose --env-file .env.test up -d --force-recreate hxops-backend hxops-shipping-worker hxops-schedule-worker
|
||||
```
|
||||
|
||||
|
||||
@@ -1485,13 +1500,12 @@ cd C:\HxopsRpaProd
|
||||
|
||||
#### 2. 启动正式 Linux 后端并验证共享
|
||||
|
||||
在正式服务器项目根目录执行。前提是 `/mnt/hxops-rpa-prod-data` 已经通过受控 SMB 凭据挂载,且 `docker-compose.yml` 已有如下 bind mount:
|
||||
在正式服务器项目根目录执行。前提是 `/mnt/hxops-rpa-prod-data` 已经通过受控 SMB 凭据挂载,且 `docker-compose.yml` 中 `hxops-backend` / `hxops-schedule-worker` / `hxops-shipping-worker` 均已 bind mount:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
hxops-backend:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
# 三个服务均需:
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -1501,10 +1515,12 @@ test -d /mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
export COMPOSE_ENV_BASENAME=.env.prod
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
|
||||
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker
|
||||
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker
|
||||
docker compose --env-file .env.prod ps
|
||||
docker compose --env-file .env.prod exec -T hxops-backend \
|
||||
sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
docker compose --env-file .env.prod exec -T hxops-shipping-worker \
|
||||
sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
|
||||
cat /mnt/hxops-rpa-prod-data/inventory_triggers/.hxops_rpa_shared_mount
|
||||
```
|
||||
|
||||
@@ -1595,7 +1611,7 @@ $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "<Crane密码>"
|
||||
python scripts/rpa/inventory/inventory_rpa_worker.py
|
||||
```
|
||||
|
||||
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 是浏览器 Profile 根目录。库存导出默认开启会话复用:目录形如 `{connector}__{rpa_profile_code}_session`,跨任务保留登录态,默认 TTL 24 小时(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`);关闭复用或上传任务仍使用 `run_*` 一次性子目录并在结束后清理。同一 WorkerRoot 不要并发启动第二个库存 Worker。
|
||||
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 是浏览器 Profile 根目录。库存导出默认开启会话复用:目录形如 `{connector}__{rpa_profile_code}_session`,跨任务长期保留登录态,不以本地 TTL 强制清空;站点会话失效时由登录流程重登。关闭复用或上传任务仍使用 `run_*` 一次性子目录并在结束后清理。同一 WorkerRoot 不要并发启动第二个库存 Worker。
|
||||
|
||||
如果登录框默认识别不稳定,可覆盖登录 selector:
|
||||
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
"""
|
||||
scripts/rpa/common/worker_disk_cleanup.py
|
||||
|
||||
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
|
||||
依赖:rpa_common.env、pathlib、shutil、time。
|
||||
逻辑:由 inventory(及可复用的 receipt)Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。
|
||||
"""
|
||||
|
||||
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 / "inventory").is_dir()
|
||||
and (_c / "receipt").is_dir()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import shutil
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from rpa_common import env as _env
|
||||
|
||||
_PROTECTED_DROP_DIRNAMES = frozenset(
|
||||
{
|
||||
"processed",
|
||||
".hxops_quarantine",
|
||||
".cleanup_queue",
|
||||
".cleanup_failed",
|
||||
".hxops_rpa_shared_mount",
|
||||
}
|
||||
)
|
||||
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
|
||||
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
|
||||
_DEFAULT_RETENTION_DAYS = 7
|
||||
_DEFAULT_INTERVAL_SECONDS = 3600
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
|
||||
|
||||
|
||||
class DiskCleanupStats:
|
||||
"""单次清理统计,便于日志汇总与单测断言。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.deleted_files = 0
|
||||
self.deleted_dirs = 0
|
||||
self.skipped = 0
|
||||
self.errors = 0
|
||||
self.details: list[str] = []
|
||||
|
||||
def record_file(self, path: Path) -> None:
|
||||
self.deleted_files += 1
|
||||
self.details.append(f"file:{path}")
|
||||
|
||||
def record_dir(self, path: Path) -> None:
|
||||
self.deleted_dirs += 1
|
||||
self.details.append(f"dir:{path}")
|
||||
|
||||
def record_error(self, path: Path, exc: BaseException) -> None:
|
||||
self.errors += 1
|
||||
self.details.append(f"error:{path}:{type(exc).__name__}")
|
||||
|
||||
|
||||
def retention_days() -> int:
|
||||
"""
|
||||
读取归档保留天数。
|
||||
|
||||
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7;
|
||||
`<=0` 表示禁用按天清理(仍可单独清理孤儿临时 Profile,见 orphan 配置)。
|
||||
|
||||
Returns:
|
||||
int: 保留天数;禁用时为 0。
|
||||
"""
|
||||
return _int_env("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS, min_value=0)
|
||||
|
||||
|
||||
def cleanup_interval_seconds() -> int:
|
||||
"""
|
||||
读取清理周期秒数。
|
||||
|
||||
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`,默认 3600;
|
||||
最小值 60,避免主循环过于频繁扫盘。
|
||||
|
||||
Returns:
|
||||
int: 清理间隔秒数。
|
||||
"""
|
||||
return _int_env(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS",
|
||||
_DEFAULT_INTERVAL_SECONDS,
|
||||
min_value=60,
|
||||
)
|
||||
|
||||
|
||||
def orphan_profile_max_age_seconds() -> int:
|
||||
"""
|
||||
读取孤儿临时 Profile(run_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
|
||||
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
|
||||
|
||||
Returns:
|
||||
int: 最大存活秒数;禁用时为 0。
|
||||
"""
|
||||
hours = _int_env(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS",
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS,
|
||||
min_value=0,
|
||||
)
|
||||
return hours * 3600
|
||||
|
||||
|
||||
def _int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取整数环境变量;非法值回退默认,并钳制下限。"""
|
||||
try:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
def _mtime_unix(path: Path) -> float | None:
|
||||
"""读取 mtime;失败返回 None。"""
|
||||
try:
|
||||
return path.stat().st_mtime
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _is_older_than(path: Path, *, cutoff_unix: float) -> bool:
|
||||
"""路径 mtime 早于 cutoff 时视为过期。"""
|
||||
mtime = _mtime_unix(path)
|
||||
if mtime is None:
|
||||
return False
|
||||
return mtime < cutoff_unix
|
||||
|
||||
|
||||
def _safe_unlink(path: Path, stats: DiskCleanupStats) -> None:
|
||||
"""best-effort 删除文件。"""
|
||||
try:
|
||||
if path.is_file() or path.is_symlink():
|
||||
path.unlink(missing_ok=True)
|
||||
stats.record_file(path)
|
||||
else:
|
||||
stats.skipped += 1
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
|
||||
|
||||
def _safe_rmtree(path: Path, stats: DiskCleanupStats) -> None:
|
||||
"""best-effort 删除目录树。"""
|
||||
try:
|
||||
if path.is_dir():
|
||||
shutil.rmtree(path, ignore_errors=False)
|
||||
stats.record_dir(path)
|
||||
else:
|
||||
stats.skipped += 1
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
|
||||
|
||||
def cleanup_files_older_than(
|
||||
directory: Path,
|
||||
*,
|
||||
cutoff_unix: float,
|
||||
stats: DiskCleanupStats,
|
||||
recursive: bool = False,
|
||||
name_predicate: Callable[[Path], bool] | None = None,
|
||||
suffix_allowlist: frozenset[str] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
删除目录中超过 cutoff 的文件(可选递归、文件名/后缀过滤)。
|
||||
|
||||
核心逻辑:只处理普通文件;目录本身不删(由调用方决定是否 rmtree)。
|
||||
匹配失败或权限错误计入 stats,不中断整轮清理。
|
||||
|
||||
Args:
|
||||
directory: 目标目录;不存在则跳过。
|
||||
cutoff_unix: 早于此 Unix 时间戳的文件可删。
|
||||
stats: 累计统计。
|
||||
recursive: 是否递归子目录。
|
||||
name_predicate: 可选文件名过滤;返回 False 则跳过。
|
||||
suffix_allowlist: 可选后缀白名单(小写,含点);None 表示不限制。
|
||||
"""
|
||||
if not directory.is_dir():
|
||||
return
|
||||
iterator = directory.rglob("*") if recursive else directory.iterdir()
|
||||
for path in iterator:
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
if name_predicate is not None and not name_predicate(path):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if suffix_allowlist is not None and path.suffix.lower() not in suffix_allowlist:
|
||||
# 兼容 sidecar:`.xlsx.hxops_consumed` 的 suffix 是 `.hxops_consumed`
|
||||
if path.name.endswith(".hxops_consumed") and ".hxops_consumed" in suffix_allowlist:
|
||||
pass
|
||||
else:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_trigger_archives(trigger_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 trigger 下 processed/failed 归档 JSON。
|
||||
|
||||
核心逻辑:绝不触碰 trigger 根目录进行中的 `*.json`。
|
||||
"""
|
||||
if trigger_dir is None or not trigger_dir.is_dir():
|
||||
return
|
||||
for dirname in _TRIGGER_ARCHIVE_DIRNAMES:
|
||||
cleanup_files_older_than(
|
||||
trigger_dir / dirname,
|
||||
cutoff_unix=cutoff_unix,
|
||||
stats=stats,
|
||||
recursive=False,
|
||||
suffix_allowlist=frozenset({".json"}),
|
||||
)
|
||||
|
||||
|
||||
def cleanup_drop_archives(drop_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 drop 区归档与隔离目录,以及根目录过期导出文件。
|
||||
|
||||
核心逻辑:
|
||||
- 清理 `processed` / `.hxops_quarantine` / `.cleanup_failed` 中过期文件;
|
||||
- 清理 drop 根目录过期的 Excel/CSV 与 `.hxops_consumed` sidecar;
|
||||
- 不碰 `.cleanup_queue`(活跃重试队列)。
|
||||
"""
|
||||
if drop_dir is None or not drop_dir.is_dir():
|
||||
return
|
||||
for dirname in ("processed", ".hxops_quarantine", ".cleanup_failed"):
|
||||
cleanup_files_older_than(
|
||||
drop_dir / dirname,
|
||||
cutoff_unix=cutoff_unix,
|
||||
stats=stats,
|
||||
recursive=False,
|
||||
)
|
||||
# [STEP 1] drop 根:仅清理导出产物与消费标记,跳过受保护子目录与其它文件
|
||||
for path in drop_dir.iterdir():
|
||||
try:
|
||||
if path.is_dir():
|
||||
if path.name in _PROTECTED_DROP_DIRNAMES or path.name.startswith("."):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
suffix = path.suffix.lower()
|
||||
is_consumed_sidecar = path.name.endswith(".hxops_consumed")
|
||||
if suffix not in _DROP_ROOT_SUFFIXES and not is_consumed_sidecar:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_upload_queue(queue_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 upload_queue 中过期文件。
|
||||
|
||||
核心逻辑:待上传文件正常应在数分钟内被消费;超过保留期视为残留,可删。
|
||||
"""
|
||||
if queue_dir is None or not queue_dir.is_dir():
|
||||
return
|
||||
cleanup_files_older_than(queue_dir, cutoff_unix=cutoff_unix, stats=stats, recursive=False)
|
||||
|
||||
|
||||
def cleanup_log_backups(log_file: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None:
|
||||
"""
|
||||
清理 worker 日志轮转备份(worker.log.1 / .2 ...)。
|
||||
|
||||
核心逻辑:不删当前 `worker.log`(由大小轮转负责);只删过期备份。
|
||||
"""
|
||||
if log_file is None:
|
||||
return
|
||||
parent = log_file.parent
|
||||
if not parent.is_dir():
|
||||
return
|
||||
prefix = f"{log_file.name}."
|
||||
for path in parent.iterdir():
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
if path.name == log_file.name:
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not path.name.startswith(prefix):
|
||||
continue
|
||||
suffix = path.name[len(prefix) :]
|
||||
if not suffix.isdigit():
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_unlink(path, stats)
|
||||
|
||||
|
||||
def cleanup_orphan_runtime_profiles(
|
||||
profile_root: Path | None,
|
||||
*,
|
||||
cutoff_unix: float,
|
||||
stats: DiskCleanupStats,
|
||||
) -> None:
|
||||
"""
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` 临时目录,避免异常中断后残留撑盘。
|
||||
"""
|
||||
if profile_root is None or not profile_root.is_dir():
|
||||
return
|
||||
for path in profile_root.iterdir():
|
||||
try:
|
||||
if not path.is_dir():
|
||||
continue
|
||||
except OSError as exc:
|
||||
stats.record_error(path, exc)
|
||||
continue
|
||||
name = path.name
|
||||
if name.endswith("_session") or name == "dsv360_session":
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not name.startswith("run_"):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
_safe_rmtree(path, stats)
|
||||
|
||||
|
||||
def run_worker_disk_cleanup(
|
||||
*,
|
||||
inventory_trigger_dir: Path | None = None,
|
||||
upload_trigger_dir: Path | None = None,
|
||||
drop_dir: Path | None = None,
|
||||
upload_queue_dir: Path | None = None,
|
||||
browser_profile_dir: Path | None = None,
|
||||
log_file: Path | None = None,
|
||||
now_unix: float | None = None,
|
||||
) -> DiskCleanupStats:
|
||||
"""
|
||||
执行一轮 Worker 本机磁盘保留清理。
|
||||
|
||||
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
|
||||
|
||||
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` Profile。全部 best-effort。
|
||||
|
||||
Args:
|
||||
inventory_trigger_dir: 库存 trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
browser_profile_dir: 浏览器 Profile 根目录。
|
||||
log_file: 当前 worker 日志文件路径。
|
||||
now_unix: 可选当前时间(单测注入)。
|
||||
|
||||
Returns:
|
||||
DiskCleanupStats: 本轮删除/跳过/错误统计。
|
||||
"""
|
||||
stats = DiskCleanupStats()
|
||||
now = float(now_unix if now_unix is not None else time.time())
|
||||
days = retention_days()
|
||||
if days > 0:
|
||||
cutoff = now - (days * 86400)
|
||||
cleanup_trigger_archives(inventory_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(upload_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_drop_archives(drop_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_upload_queue(upload_queue_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_log_backups(log_file, cutoff_unix=cutoff, stats=stats)
|
||||
orphan_age = orphan_profile_max_age_seconds()
|
||||
if orphan_age > 0:
|
||||
cleanup_orphan_runtime_profiles(
|
||||
browser_profile_dir,
|
||||
cutoff_unix=now - orphan_age,
|
||||
stats=stats,
|
||||
)
|
||||
return stats
|
||||
|
||||
|
||||
def format_cleanup_summary(stats: DiskCleanupStats) -> str:
|
||||
"""
|
||||
将清理统计格式化为单行日志。
|
||||
|
||||
Args:
|
||||
stats: 清理结果。
|
||||
|
||||
Returns:
|
||||
str: 适合 print 的摘要。
|
||||
"""
|
||||
stamp = datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
return (
|
||||
f"[disk-cleanup] at={stamp} deleted_files={stats.deleted_files} "
|
||||
f"deleted_dirs={stats.deleted_dirs} skipped={stats.skipped} errors={stats.errors}"
|
||||
)
|
||||
@@ -20,7 +20,6 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS=24
|
||||
# legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
|
||||
@@ -28,6 +27,9 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5
|
||||
SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS=7
|
||||
SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS=3600
|
||||
SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS=24
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
|
||||
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false
|
||||
@@ -83,6 +85,7 @@ import dsv_report_export # noqa: E402
|
||||
from dsv_report_export import NoInventoryDataError # noqa: E402
|
||||
import dsv_session # noqa: E402
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
@@ -144,7 +147,7 @@ class _TeeStream:
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
|
||||
保留最后几行排障信息。
|
||||
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
@@ -153,6 +156,23 @@ class _TeeStream:
|
||||
self._pending = ""
|
||||
self.encoding = getattr(console, "encoding", "utf-8")
|
||||
|
||||
def replace_log_file(self, log_file: TextIO) -> TextIO:
|
||||
"""
|
||||
替换底层日志文件句柄(用于运行中轮转)。
|
||||
|
||||
核心逻辑:先 flush 缓冲,再切换句柄;调用方负责关闭旧句柄与打开新文件。
|
||||
|
||||
Args:
|
||||
log_file: 新的追加写日志句柄。
|
||||
|
||||
Returns:
|
||||
TextIO: 被替换下来的旧日志句柄。
|
||||
"""
|
||||
self.flush()
|
||||
previous = self._log_file
|
||||
self._log_file = log_file
|
||||
return previous
|
||||
|
||||
def _emit_line(self, line: str, *, newline: bool) -> None:
|
||||
"""将单行(可含时间戳前缀)写入控制台与日志文件。"""
|
||||
if line:
|
||||
@@ -182,6 +202,13 @@ class _TeeStream:
|
||||
return bool(getattr(self._console, "isatty", lambda: False)())
|
||||
|
||||
|
||||
# 运行中日志轮转需要持有 Tee 与路径;仅由 _configure_file_logging / _maybe_rotate_open_log 维护。
|
||||
_ACTIVE_LOG_PATH: Path | None = None
|
||||
_ACTIVE_STDOUT_TEE: _TeeStream | None = None
|
||||
_ACTIVE_STDERR_TEE: _TeeStream | None = None
|
||||
_ACTIVE_LOG_HANDLE: TextIO | None = None
|
||||
|
||||
|
||||
def _configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
|
||||
@@ -193,6 +220,7 @@ def _configure_file_logging() -> Path | None:
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
@@ -204,19 +232,71 @@ def _configure_file_logging() -> Path | None:
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
sys.stdout = _TeeStream(original_stdout, log_file) # type: ignore[assignment]
|
||||
sys.stderr = _TeeStream(original_stderr, log_file) # type: ignore[assignment]
|
||||
stdout_tee = _TeeStream(original_stdout, log_file)
|
||||
stderr_tee = _TeeStream(original_stderr, log_file)
|
||||
sys.stdout = stdout_tee # type: ignore[assignment]
|
||||
sys.stderr = stderr_tee # type: ignore[assignment]
|
||||
_ACTIVE_LOG_PATH = path
|
||||
_ACTIVE_STDOUT_TEE = stdout_tee
|
||||
_ACTIVE_STDERR_TEE = stderr_tee
|
||||
_ACTIVE_LOG_HANDLE = log_file
|
||||
|
||||
def _close_log() -> None:
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
sys.stdout = original_stdout
|
||||
sys.stderr = original_stderr
|
||||
log_file.close()
|
||||
handle = _ACTIVE_LOG_HANDLE or log_file
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_PATH = None
|
||||
_ACTIVE_STDOUT_TEE = None
|
||||
_ACTIVE_STDERR_TEE = None
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
|
||||
atexit.register(_close_log)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return path
|
||||
|
||||
|
||||
def _maybe_rotate_open_log() -> None:
|
||||
"""
|
||||
常驻 Worker 运行中按大小轮转当前日志。
|
||||
|
||||
核心逻辑:Windows 下无法对仍打开的文件 rename,须先关闭句柄 → 调用既有
|
||||
`_rotate_log_file_if_needed` → 再以追加模式打开新文件并挂回 TeeStream。
|
||||
未启用文件日志或未超限时 no-op。
|
||||
"""
|
||||
global _ACTIVE_LOG_HANDLE
|
||||
path = _ACTIVE_LOG_PATH
|
||||
stdout_tee = _ACTIVE_STDOUT_TEE
|
||||
stderr_tee = _ACTIVE_STDERR_TEE
|
||||
handle = _ACTIVE_LOG_HANDLE
|
||||
if path is None or stdout_tee is None or stderr_tee is None or handle is None:
|
||||
return
|
||||
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
if max_bytes <= 0:
|
||||
return
|
||||
try:
|
||||
handle.flush()
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
_rotate_log_file_if_needed(path)
|
||||
new_handle = path.open("a", encoding="utf-8", buffering=1)
|
||||
stdout_tee.replace_log_file(new_handle)
|
||||
stderr_tee.replace_log_file(new_handle)
|
||||
_ACTIVE_LOG_HANDLE = new_handle
|
||||
print(f"[logging] rotated open log path={path}")
|
||||
|
||||
|
||||
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取日志相关整数环境变量;非法值回退默认值。"""
|
||||
try:
|
||||
@@ -879,21 +959,6 @@ def _dsv_session_reuse_enabled() -> bool:
|
||||
return _session_reuse_enabled()
|
||||
|
||||
|
||||
def _session_reuse_ttl_seconds() -> int:
|
||||
"""
|
||||
返回持久 Profile 最长保留秒数。
|
||||
|
||||
核心逻辑:读取 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`,默认 24 小时;
|
||||
下限 1 小时,避免误配成 0 导致每次都重建。
|
||||
"""
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24") or "24"
|
||||
try:
|
||||
hours = int(raw)
|
||||
except ValueError:
|
||||
hours = 24
|
||||
return max(1, hours) * 3600
|
||||
|
||||
|
||||
def _sanitize_profile_dir_segment(value: str) -> str:
|
||||
"""
|
||||
将 connector / RPA Profile 编码成可作目录名的安全片段。
|
||||
@@ -915,7 +980,7 @@ def _session_profile_dir(connector_type: str, profile_code: str = "") -> Path:
|
||||
|
||||
核心逻辑:目录形如 `{connector}__{profile_code}_session`,不同货代账号绝不共用;
|
||||
若仍存在历史 `dsv360_session` 且目标目录尚未创建、profile 为 default,则沿用旧目录
|
||||
以保留已有登录态,待 TTL 过期后自然重建到新命名。
|
||||
以保留已有登录态。本地不按时间强制清空;站点会话失效时由登录流程兜底重登。
|
||||
|
||||
Args:
|
||||
connector_type: Worker 连接器名(如 dsv360 / crane_footprint)。
|
||||
@@ -972,7 +1037,6 @@ def _write_session_meta(
|
||||
"last_used_at": datetime.fromtimestamp(now, tz=UTC).isoformat(),
|
||||
"connector_type": connector_type,
|
||||
"profile_code": profile_code,
|
||||
"ttl_hours": max(1, _session_reuse_ttl_seconds() // 3600),
|
||||
}
|
||||
meta_path = profile_dir / _SESSION_META_FILENAME
|
||||
meta_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
@@ -985,10 +1049,10 @@ def _prepare_reusable_session_profile(
|
||||
profile_code: str,
|
||||
) -> Path:
|
||||
"""
|
||||
准备可复用 Profile 目录:超 TTL 则清空重建,否则刷新 last_used。
|
||||
准备可复用 Profile 目录:确保存在并刷新 last_used,不按本地时间强制过期。
|
||||
|
||||
核心逻辑:以 meta 的 `created_at_unix` 起算;无 meta 时用目录 mtime。超过
|
||||
`SESSION_REUSE_TTL_HOURS`(默认 24h)则整目录删除后重建,迫使重新登录。
|
||||
核心逻辑:目录长期保留 Cookie/登录态;是否免登由货代站点会话是否仍有效决定,
|
||||
失效时各 connector 的 ensure_session / 登录流程会自动重登。
|
||||
|
||||
Args:
|
||||
profile_dir: 目标持久目录。
|
||||
@@ -996,47 +1060,21 @@ def _prepare_reusable_session_profile(
|
||||
profile_code: RPA Profile 编码,写入 meta。
|
||||
|
||||
Returns:
|
||||
Path: 已确保存在且未过期的 profile 目录。
|
||||
Path: 已确保存在的 profile 目录。
|
||||
"""
|
||||
ttl_seconds = _session_reuse_ttl_seconds()
|
||||
now = time.time()
|
||||
if profile_dir.exists():
|
||||
meta = _read_session_meta(profile_dir)
|
||||
created_at = meta.get("created_at_unix")
|
||||
try:
|
||||
created_ts = float(created_at) if created_at is not None else profile_dir.stat().st_mtime
|
||||
except (TypeError, ValueError, OSError):
|
||||
created_ts = now
|
||||
age_seconds = max(0.0, now - created_ts)
|
||||
if age_seconds >= ttl_seconds:
|
||||
print(
|
||||
"[browser] session_reuse expired "
|
||||
f"ageHours={age_seconds / 3600:.1f} ttlHours={ttl_seconds / 3600:.0f} "
|
||||
f"dir={profile_dir.name!r}; recreating"
|
||||
)
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=created_ts,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
meta = _read_session_meta(profile_dir)
|
||||
created_at = meta.get("created_at_unix")
|
||||
try:
|
||||
created_ts = float(created_at) if created_at is not None else now
|
||||
except (TypeError, ValueError):
|
||||
created_ts = now
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
created_at_unix=created_ts,
|
||||
)
|
||||
return profile_dir
|
||||
|
||||
@@ -1086,8 +1124,8 @@ def _open_browser(
|
||||
打开用于库存 / 上传 RPA 的浏览器上下文。
|
||||
|
||||
核心逻辑:库存导出在 `reuse_session=True` 且 `SESSION_REUSE` 开启时,使用
|
||||
`{connector}__{profile_code}_session` 持久目录并按 TTL 失效重建;关闭复用或上传
|
||||
任务则创建 `run_*` 一次性目录。会话失效仍由各 connector 登录流程兜底。
|
||||
`{connector}__{profile_code}_session` 持久目录长期保留登录态;关闭复用或上传
|
||||
任务则创建 `run_*` 一次性目录。站点会话失效时由各 connector 登录流程兜底。
|
||||
|
||||
Args:
|
||||
download_dir: 当前任务下载目录,浏览器 downloads_path 指向此处。
|
||||
@@ -2479,8 +2517,60 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
rpa_heartbeat.set_worker_runtime_status("idle")
|
||||
|
||||
|
||||
def _run_periodic_disk_cleanup(
|
||||
*,
|
||||
inv_trigger_dir: Path,
|
||||
upload_trigger_dir: Path,
|
||||
drop_dir: Path,
|
||||
upload_queue_dir: Path,
|
||||
force: bool = False,
|
||||
last_cleanup_mono: float = 0.0,
|
||||
) -> float:
|
||||
"""
|
||||
按间隔执行本机磁盘保留清理,并尝试运行中日志轮转。
|
||||
|
||||
核心逻辑:默认每 `DISK_CLEANUP_INTERVAL_SECONDS` 跑一轮;清理归档 trigger/drop、
|
||||
日志备份、upload_queue 残留与孤儿 `run_*` Profile;同时按大小轮转打开中的 worker.log。
|
||||
|
||||
Args:
|
||||
inv_trigger_dir: 库存 trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
force: True 时忽略间隔立即执行(启动时)。
|
||||
last_cleanup_mono: 上次清理的 monotonic 时间戳。
|
||||
|
||||
Returns:
|
||||
float: 更新后的 last_cleanup_mono(未执行则原样返回)。
|
||||
"""
|
||||
interval = worker_disk_cleanup.cleanup_interval_seconds()
|
||||
now_mono = time.monotonic()
|
||||
if not force and (now_mono - last_cleanup_mono) < interval:
|
||||
return last_cleanup_mono
|
||||
try:
|
||||
_maybe_rotate_open_log()
|
||||
stats = worker_disk_cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
browser_profile_dir=_browser_profile_root(),
|
||||
log_file=_ACTIVE_LOG_PATH,
|
||||
)
|
||||
print(worker_disk_cleanup.format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f"[disk-cleanup] failed: {exc}", file=sys.stderr)
|
||||
return now_mono
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_configure_file_logging()
|
||||
"""
|
||||
库存 RPA Worker 入口:启日志、心跳、周期磁盘清理,并串行消费 trigger。
|
||||
|
||||
核心逻辑:主循环扫描库存/上传 trigger;空闲时按间隔清理本机归档与临时文件,
|
||||
防止长期运行撑爆 RPA 主机盘符。
|
||||
"""
|
||||
log_path = _configure_file_logging()
|
||||
drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
|
||||
upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
@@ -2506,6 +2596,14 @@ def main() -> None:
|
||||
print(f" upload_triggers={upload_trigger_dir}")
|
||||
print(f" drop={drop_dir}")
|
||||
print(f" queue={upload_queue_dir}")
|
||||
print(f" log={log_path or 'disabled'}")
|
||||
print(
|
||||
" disk_retention_days="
|
||||
f"{worker_disk_cleanup.retention_days()} "
|
||||
f"cleanup_interval_seconds={worker_disk_cleanup.cleanup_interval_seconds()} "
|
||||
f"orphan_profile_max_age_hours="
|
||||
f"{max(0, worker_disk_cleanup.orphan_profile_max_age_seconds() // 3600)}"
|
||||
)
|
||||
|
||||
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
@@ -2522,9 +2620,25 @@ def main() -> None:
|
||||
interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
|
||||
# [STEP 1] 启动即清一轮,避免重启前长期堆积的归档立刻撑盘
|
||||
last_cleanup_mono = _run_periodic_disk_cleanup(
|
||||
inv_trigger_dir=inv_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
force=True,
|
||||
)
|
||||
|
||||
while True:
|
||||
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
|
||||
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
|
||||
last_cleanup_mono = _run_periodic_disk_cleanup(
|
||||
inv_trigger_dir=inv_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
last_cleanup_mono=last_cleanup_mono,
|
||||
)
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
|
||||
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
|
||||
不从本机 Secret 文件读取。
|
||||
默认开启库存会话复用(SESSION_REUSE + 24h TTL);需要每次全新登录时传 -NoSessionReuse。
|
||||
默认开启库存会话复用(SESSION_REUSE,长期保留 Profile;站点会话失效才重登);
|
||||
需要每次全新登录时传 -NoSessionReuse。
|
||||
默认启用本机磁盘保留清理(7 天归档 / 每小时一轮 / 24h 孤儿 run_* Profile)。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
@@ -65,7 +67,7 @@ foreach ($required in @("ToolApiKey", "CredentialKey")) {
|
||||
}
|
||||
}
|
||||
|
||||
# 库存 Profile 默认按 connector+rpa_profile 复用,TTL 24h;-NoSessionReuse 可关闭。
|
||||
# 库存 Profile 默认按 connector+rpa_profile 长期复用;-NoSessionReuse 可关闭。
|
||||
$sessionReuse = if ($NoSessionReuse) { "false" } else { "true" }
|
||||
if ($ReuseSession -or $ReuseDsvSession) {
|
||||
$sessionReuse = "true"
|
||||
@@ -82,7 +84,6 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS = "24"
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
|
||||
@@ -93,6 +94,10 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot "logs\worker.log"
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760"
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5"
|
||||
# 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 Profile 不删。
|
||||
SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7"
|
||||
SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600"
|
||||
SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24"
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false"
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user