tasks.py
8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""任务插件注册表 + 任务上下文(分步骤进度上报与超时)。
插件这样注册:
from edgeclient.core.tasks import task
@task("restock.scan", "补货扫描")
def scan(ctx, params): ... # 返回 dict;失败抛异常(带 error_code 的用 TaskError)
步骤:
with ctx.step("login", timeout=90): # timeout 不给就用云端下发的 _steps 里的值
sess.login()
* 进入 / 结束每一步都上报云端(连不上就进本地 outbox,不影响执行);
* 超过 timeout:立即上报「超时」(云端马上告警),执行 on_timeout(如强制结束卡住的 Chrome);
建单这类已经发出请求的步骤不传 on_timeout,等它自然结束、照实回传,绝不中途放弃结果;
* 超过 2×timeout+60 秒还没结束:看门狗判定进程卡死,退出进程,由 Windows 服务自动重启。
等人工确认(UI 登录逐步确认):
with human_wait("点击『登录』按钮", 180): # 期间暂停当前步骤的计时和看门狗,向云端上报「等待人工确认」步骤,
... # 云端相应延长任务等待时间;结束后接着算剩余时间
"""
import contextlib
import logging
import threading
import time
from .cloud import CloudError
log = logging.getLogger("edge")
REGISTRY = {}
CURRENT = {"ctx": None} # 正在执行的任务上下文(service 设置;UI 登录等深层代码用 human_wait() 找到它)
def human_wait(detail, timeout):
"""等人工确认期间暂停步骤计时(没有任务上下文时什么都不做)。"""
ctx = CURRENT.get("ctx")
if ctx is None or not hasattr(ctx, "human_wait"):
return contextlib.nullcontext() if hasattr(contextlib, "nullcontext") else _null()
return ctx.human_wait(detail, timeout)
@contextlib.contextmanager
def _null():
yield
def task(type_, title=""):
def deco(fn):
REGISTRY[type_] = (fn, title or type_)
return fn
return deco
def capabilities():
return sorted(REGISTRY)
class TaskError(Exception):
"""带结构化错误码的任务失败:login_rejected / login_failed / step_timeout / network / dms_error / unknown_result / ..."""
def __init__(self, message, code="action_error", result=None):
super(TaskError, self).__init__(message)
self.code = code
self.result = result or {}
class StepTimeout(TaskError):
def __init__(self, step, seconds, cause=""):
super(StepTimeout, self).__init__("步骤「%s」超过 %d 秒%s" % (step, seconds, (":" + cause) if cause else ""),
"step_timeout")
self.step = step
class NullSteps(object):
"""本地菜单 / 测试用:不上报,只计时打日志。"""
task_id = None
step_timeouts = {}
@contextlib.contextmanager
def step(self, name, detail="", timeout=None, on_timeout=None, scale=1):
t0 = time.time()
yield
log.debug("步骤 %s %s 用时 %.1f 秒", name, detail, time.time() - t0)
@contextlib.contextmanager
def human_wait(self, detail, timeout):
yield
def note(self, detail):
log.debug("进度:%s", detail)
def upload(self, path, kind="file"):
return None
class TaskContext(object):
"""sess 可以是会话对象,也可以是无参函数(用到时才创建会话——sys.ping 这类任务不需要 DMS 账号)。"""
def __init__(self, cfg, sess, cc, outbox, task_row, watchdog=None):
self.cfg, self.cc, self.outbox, self.watchdog = cfg, cc, outbox, watchdog
self._sess = sess
self.task_id = str(task_row["id"])
self.type = task_row["type"]
self.params = dict(task_row.get("params") or {})
self.step_timeouts = self.params.pop("_steps", None) or {}
self.evidence = []
self.current = None
self.timed_out = []
self._timer = None # 当前步骤的 {"timer", "deadline", "fire", "name", "t"}(human_wait 暂停 / 恢复用)
@property
def sess(self):
if callable(self._sess):
self._sess = self._sess()
return self._sess
# ---------------- 进度 ----------------
def _report(self, step, status, detail="", timeout=None, error=""):
payload = {"task_id": self.task_id, "step": step, "status": status, "detail": detail, "timeout": timeout,
"error": error}
try:
self.cc.progress(self.task_id, step, status, detail, timeout, error)
except CloudError as e:
if e.retryable:
self.outbox.put("progress", self.task_id, payload)
else:
log.warning("步骤进度被云端拒绝:%s", e)
def note(self, detail):
"""当前步骤内的进度说明(如「取明细 35 / 120 张」):云端只更新说明,不结束步骤。"""
if self.current:
self._report(self.current[0], "note", detail)
@contextlib.contextmanager
def step(self, name, detail="", timeout=None, on_timeout=None, scale=1):
t = float(timeout or self.step_timeouts.get(name) or 0) * scale
fired = {"v": False}
def fire():
fired["v"] = True
self.timed_out.append(name)
log.error("步骤超时:%s %s(超过 %d 秒)", name, detail, t)
self._report(name, "timeout", detail, t, "超过 %d 秒" % t)
if on_timeout:
try:
on_timeout()
except Exception as e: # noqa: BLE001
log.error("超时处理出错:%s", e)
timer = threading.Timer(t, fire) if t > 0 else None
if timer:
timer.daemon = True
timer.start()
self._timer = {"timer": timer, "deadline": time.time() + t, "fire": fire, "name": name, "t": t}
self.current = (name, time.time(), t)
if self.watchdog and t > 0:
self.watchdog.arm(self.task_id, name, t * 2 + 60)
self._report(name, "start", detail, t or None)
try:
yield
except Exception as e:
timer = self._timer["timer"] if self._timer else timer
if timer:
timer.cancel()
if fired["v"] and not isinstance(e, TaskError): # 已结构化的错误(如建单结果未知)保持原样
raise StepTimeout(name, t, "%s: %s" % (type(e).__name__, e))
if not fired["v"]:
self._report(name, "failed", detail, t or None, "%s: %s" % (type(e).__name__, e))
raise
else:
timer = self._timer["timer"] if self._timer else timer
if timer:
timer.cancel()
# 超时后才完成的(如建单):照实上报成功,结果照常回传
self._report(name, "ok", detail + ("(超时后完成)" if fired["v"] else ""), t or None)
finally:
self.current = None
self._timer = None
if self.watchdog:
self.watchdog.disarm(self.task_id)
@contextlib.contextmanager
def human_wait(self, detail, timeout):
"""等人工确认:暂停当前步骤计时 / 看门狗,上报 confirm 步骤(云端延长等待),结束后按剩余时间继续计时。"""
st = self._timer
left = None
if st:
st["timer"].cancel()
left = max(5.0, st["deadline"] - time.time())
if self.watchdog:
self.watchdog.arm(self.task_id, "confirm", float(timeout) + 120)
self._report("confirm", "start", detail, timeout)
ok = False
try:
yield
ok = True
finally:
self._report("confirm", "ok" if ok else "failed", detail, timeout, "" if ok else "未确认 / 已取消")
if st:
nt = threading.Timer(left, st["fire"])
nt.daemon = True
nt.start()
st.update(timer=nt, deadline=time.time() + left)
if self.watchdog:
self.watchdog.arm(self.task_id, st["name"], left * 2 + 60)
elif self.watchdog:
self.watchdog.disarm(self.task_id)
# ---------------- 文件 ----------------
def upload(self, path, kind="file"):
info = self.cc.upload_file(self.task_id, path, kind)
if info and info.get("id"):
self.evidence.append(int(info["id"]))
return int(info["id"])
return None