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:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,181 @@
<#
.SYNOPSIS
Register the test/prod RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Worker as a background scheduled task with NO visible console and NO
visible Edge (the Worker launches Playwright headless via -Headless). Deliberately
ASCII-only so it parses identically under any Windows console code page.
Differences vs the standard "visible" scheduled task (README step 11 / 2.3):
- powershell.exe gets -WindowStyle Hidden -> no console window to close by accident.
- start_onhand_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
Shape constraints (same as README 2.3):
- 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 (README 2.3.1):
set $env:FREIGHT_RPA_WORKER_HEADLESS="true" then run
dsv_login_smoke.py / crane_login_smoke.py.
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\onhand\register_onhand_worker_tasks.ps1 # register test+prod
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Scope test # register only test
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Start # start both now
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Status -Scope test # only test
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\freight_rpa\onhand\register_onhand_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 Onhand RPA Worker TEST"
$ProdTask = "HXOPS Freight Onhand 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\onhand\start_onhand_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\onhand\start_onhand_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 Onhand 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,75 @@
"""Run one database-generated onhand batch trigger without starting the polling worker."""
from __future__ import annotations
import importlib.util
import os
import sys
from pathlib import Path
def _repo_root() -> Path:
"""Return the HXOPS repository root for relative operational directories."""
for _p in Path(__file__).resolve().parents:
if (_p / "backend").is_dir() and (_p / "frontend").is_dir() and (_p / "scripts").is_dir():
return _p
return Path(__file__).resolve().parents[2]
def _load_dotenv_dev() -> None:
"""Load missing local runtime variables without exposing or overwriting credentials."""
env_path = _repo_root() / ".env.dev"
if not env_path.is_file():
return
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
if key.strip() and key.strip() not in os.environ:
os.environ[key.strip()] = value.strip().strip('"').strip("'")
def _load_worker():
"""Load the polling worker module so manual runs share the production trigger contract."""
module_path = _repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_batch_runner", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
"""Execute a complete, database-generated batch trigger and post its normal callback."""
if len(sys.argv) < 2:
print("usage: python scripts/freight_rpa/onhand/run_onhand_batch_trigger.py <trigger.json>")
return 1
trigger_path = Path(sys.argv[1]).expanduser()
if not trigger_path.is_file():
trigger_path = _repo_root() / sys.argv[1]
if not trigger_path.is_file():
print(f"[batch-run] trigger not found: {sys.argv[1]}")
return 1
_load_dotenv_dev()
os.environ.setdefault("FREIGHT_RPA_WORKER_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/freight_rpa/common/browser_profile")
# 不默认 msedge:Edge 152 + 持久 Profile 下载会原生崩溃;未设置 CHANNEL 时走 Playwright Chromium。
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"):
print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required")
return 1
drop_dir = Path(os.environ.get("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR") or "backend/data/freight_rpa/onhand/drop")
if not drop_dir.is_absolute():
drop_dir = _repo_root() / drop_dir
processed_dir = trigger_path.parent / "processed"
processed_dir.mkdir(parents=True, exist_ok=True)
drop_dir.mkdir(parents=True, exist_ok=True)
worker = _load_worker()
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,125 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树中启动指定环境的 RPA Worker。
.DESCRIPTION
该脚本只写入 Process 级环境变量,绝不调用 User/Machine 环境变量 API。
test/prod 可由同一 Windows 用户、同一交互式桌面、两个独立计划任务同时运行。
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
不从本机 Secret 文件读取。
默认开启库存会话复用(SESSION_REUSE,长期保留 Profile;站点会话失效才重登);
需要每次全新登录时传 -NoSessionReuse。
默认启用本机磁盘保留清理(7 天归档 / 每小时一轮 / 24h 孤儿 run_* Profile)。
#>
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\onhand\onhand_rpa_worker.py"
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
throw "Worker 不存在:$workerScript"
}
if ($Environment -eq "test") {
$scopeId = "hxops-rpa-test-data"
} else {
$scopeId = "hxops-rpa-prod-data"
}
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
# (data 即 SMB 共享 hxops-rpa-*-data 的根,代码包 scripts 不进共享;2026-10-16 批次 R 起
# inventory/receipt 目录名切换为 onhand/inbound,upload 域迁至独立 outbound/)。
$rpaRoot = Join-Path $WorkerRoot "data\freight_rpa"
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"
}
}
# 库存 Profile 默认按 connector+rpa_profile 长期复用;-NoSessionReuse 可关闭。
$sessionReuse = if ($NoSessionReuse) { "false" } else { "true" }
if ($ReuseSession) {
$sessionReuse = "true"
}
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
$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
# 稳定 Worker 身份:监控端心跳卡片不再随进程重启漂移(缺省回退 <hostname>-<pid>);
# onhand 固定后缀 -onhand,与 inbound Worker 的 -inbound 区分(后端就绪检查按后缀判定)。
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-onhand"
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = "20"
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。
# Edge 152 + 持久 Profile 下载会原生崩溃(TargetClosed / .crdownload),禁止默认 msedge。
FREIGHT_RPA_WORKER_POLL_SECONDS = "3"
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = Join-Path $rpaRoot "onhand\triggers"
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = Join-Path $rpaRoot "onhand\drop"
# 上传与 onhand/inbound/outbound 同级:freight_rpa/upload/{triggers,queue}。
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaRoot "upload\triggers"
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaRoot "upload\queue"
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot "common\browser_profile"
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot "onhand\logs\worker.log"
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760"
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5"
# 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 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"
FREIGHT_RPA_WORKER_UPLOAD_ENABLED = "false"
FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false"
}
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, "Process")
}
Write-Host "Starting RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot"
try {
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, $null, "Process")
}
}