refactor(rpa): 重构 scripts/rpa 目录结构与命名
按 common/connectors/inventory/receipt 分层并重命名 - common/: rpa_common, rpa_heartbeat, download_artifact_fallback, new_rpa_worker_secret - connectors/dsv|crane/: 登录网站连接器,库存与收料共用 - inventory/: inventory_rpa_worker, run_inventory_batch_trigger, start_inventory_worker, register_inventory_worker_tasks - receipt/: receipt_rpa_worker, receipt_crane/dbs_export, start_receipt_worker 保留裸 import + sys.path 引导;修正懒加载路径; 按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks; 同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。
This commit is contained in:
1 parent
09deada712
commit
f3050164d0
40 files changed
+384
-172
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_inventory_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:SHIPPING_NOTICE_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\rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\rpa\inventory\register_inventory_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 Inventory RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Inventory 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\rpa\inventory\start_inventory_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\rpa\inventory\start_inventory_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 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,76 @@
|
||||
"""Run one database-generated inventory 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" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_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/rpa/run_inventory_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("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true")
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile")
|
||||
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
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("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_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_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,102 @@
|
||||
<#
|
||||
.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 文件读取。
|
||||
#>
|
||||
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,
|
||||
[switch]$ReuseDsvSession
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
|
||||
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
|
||||
}
|
||||
$workerScript = Join-Path $WorkerRoot "scripts\rpa\inventory\inventory_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"
|
||||
}
|
||||
$dataRoot = Join-Path $WorkerRoot "data"
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
|
||||
$processVars = [ordered]@{
|
||||
HXOPS_API_BASE = $ApiBase
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
|
||||
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = $scopeId
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
|
||||
# 仅显式启用时让 DSV 库存任务复用专属 profile;默认继续使用一次性会话。
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE = $(if ($ReuseDsvSession) { "true" } else { "false" })
|
||||
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"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop"
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $dataRoot "upload_triggers"
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $dataRoot "upload_queue"
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $dataRoot "browser_profile"
|
||||
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"
|
||||
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false"
|
||||
SHIPPING_NOTICE_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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user