flowdeck 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. flowdeck/__init__.py +65 -0
  2. flowdeck/_version.py +1 -0
  3. flowdeck/api/__init__.py +216 -0
  4. flowdeck/api/routers/__init__.py +1 -0
  5. flowdeck/api/routers/dashboard.py +73 -0
  6. flowdeck/api/routers/health.py +26 -0
  7. flowdeck/api/routers/notifications.py +92 -0
  8. flowdeck/api/routers/pipelines.py +274 -0
  9. flowdeck/api/routers/runs.py +227 -0
  10. flowdeck/api/routers/schedule_exceptions.py +141 -0
  11. flowdeck/api/routers/system.py +386 -0
  12. flowdeck/api/routers/ui_pipelines.py +507 -0
  13. flowdeck/api/routers/ui_task_tools.py +275 -0
  14. flowdeck/api/routers/webhooks.py +115 -0
  15. flowdeck/auth/__init__.py +0 -0
  16. flowdeck/auth/basic.py +65 -0
  17. flowdeck/cli.py +40 -0
  18. flowdeck/config.py +240 -0
  19. flowdeck/database/__init__.py +0 -0
  20. flowdeck/database/base.py +91 -0
  21. flowdeck/database/models.py +218 -0
  22. flowdeck/database/repository.py +1231 -0
  23. flowdeck/logger/__init__.py +122 -0
  24. flowdeck/logger/formatter.py +112 -0
  25. flowdeck/logger/web_socket_handler.py +85 -0
  26. flowdeck/notifications/__init__.py +13 -0
  27. flowdeck/notifications/email_sender.py +79 -0
  28. flowdeck/notifications/engine.py +412 -0
  29. flowdeck/notifications/rules.py +22 -0
  30. flowdeck/notifications/table_image.py +273 -0
  31. flowdeck/notifications/task_result.py +478 -0
  32. flowdeck/notifications/templates.py +224 -0
  33. flowdeck/orchestrator/__init__.py +380 -0
  34. flowdeck/orchestrator/executor.py +661 -0
  35. flowdeck/pipeline/__init__.py +5 -0
  36. flowdeck/pipeline/_utils.py +11 -0
  37. flowdeck/pipeline/context.py +13 -0
  38. flowdeck/pipeline/pipeline.py +40 -0
  39. flowdeck/pipeline/schedule.py +125 -0
  40. flowdeck/pipeline/task.py +104 -0
  41. flowdeck/pipeline/trigger.py +22 -0
  42. flowdeck/schemas.py +11 -0
  43. flowdeck/static/assets/BackfillModal-BViyo-00.js +1 -0
  44. flowdeck/static/assets/BackfillModal-D6je7CRx.css +1 -0
  45. flowdeck/static/assets/Btn-B77BQZvQ.js +1 -0
  46. flowdeck/static/assets/Btn-D6G_tsbF.css +1 -0
  47. flowdeck/static/assets/DashboardView-BM-S5j64.js +1 -0
  48. flowdeck/static/assets/DashboardView-CBu0kYw6.css +1 -0
  49. flowdeck/static/assets/DatePickerField-IOKwxOwp.js +830 -0
  50. flowdeck/static/assets/Empty-B5kRTX_h.css +1 -0
  51. flowdeck/static/assets/Empty-ScitfHnD.js +1 -0
  52. flowdeck/static/assets/Modal-7xA4aZKG.js +1 -0
  53. flowdeck/static/assets/Modal-BNFhtIvK.css +1 -0
  54. flowdeck/static/assets/NotificationsView-BTkWFeLt.css +1 -0
  55. flowdeck/static/assets/NotificationsView-BkofWdjj.js +1 -0
  56. flowdeck/static/assets/NotifySettings-BFdtzy6K.js +1 -0
  57. flowdeck/static/assets/NotifySettings-D9Nn2RLl.css +1 -0
  58. flowdeck/static/assets/NumInput--MSEekvd.js +582 -0
  59. flowdeck/static/assets/NumInput-DfqPA-uG.css +1 -0
  60. flowdeck/static/assets/PageHeader-3D30Zbvm.js +1 -0
  61. flowdeck/static/assets/PageHeader-BULVGwbD.css +1 -0
  62. flowdeck/static/assets/PipelineDetailView-89815vAO.js +1 -0
  63. flowdeck/static/assets/PipelineDetailView-B_iVBCYT.css +1 -0
  64. flowdeck/static/assets/PipelinesView-CtDub3qu.js +1 -0
  65. flowdeck/static/assets/PipelinesView-DC9QO4Wr.css +1 -0
  66. flowdeck/static/assets/PrettyJson-DjAv38hk.css +1 -0
  67. flowdeck/static/assets/PrettyJson-_gjY71Cb.js +1 -0
  68. flowdeck/static/assets/RecentFailuresView-CruW_Dj8.js +1 -0
  69. flowdeck/static/assets/RecentFailuresView-DjQsiRv9.css +1 -0
  70. flowdeck/static/assets/RunDetailView--NojY8JX.css +1 -0
  71. flowdeck/static/assets/RunDetailView-2ZVPmVgW.js +5 -0
  72. flowdeck/static/assets/ScheduleExceptionsView-DdccyMcD.js +2 -0
  73. flowdeck/static/assets/ScheduleExceptionsView-pWTB9mSE.css +1 -0
  74. flowdeck/static/assets/SettingsView-BwlizulV.js +4 -0
  75. flowdeck/static/assets/SettingsView-D4ybFG31.css +1 -0
  76. flowdeck/static/assets/StatCard-CdPYF8jZ.js +1 -0
  77. flowdeck/static/assets/StatCard-D06FdLL9.css +1 -0
  78. flowdeck/static/assets/StatsView-88bkL-AN.css +1 -0
  79. flowdeck/static/assets/StatsView-DONGQHCc.js +18 -0
  80. flowdeck/static/assets/StatusBadge-BDBPRgRa.css +1 -0
  81. flowdeck/static/assets/StatusBadge-DzUDQ0X_.js +1 -0
  82. flowdeck/static/assets/ToggleSwitch-KMgLwPsM.js +1 -0
  83. flowdeck/static/assets/ToggleSwitch-UNHeNS9K.css +1 -0
  84. flowdeck/static/assets/UiPipelinesView-BgzBgUYR.css +1 -0
  85. flowdeck/static/assets/UiPipelinesView-WTYqKxB5.js +2 -0
  86. flowdeck/static/assets/UiTaskEditorView-BgYyqqgT.js +10 -0
  87. flowdeck/static/assets/UiTaskEditorView-Dl6zmLDP.css +1 -0
  88. flowdeck/static/assets/_plugin-vue_export-helper-OBKhRxFI.js +12 -0
  89. flowdeck/static/assets/chakra-petch-latin-400-normal-D7EtbySE.woff +0 -0
  90. flowdeck/static/assets/chakra-petch-latin-400-normal-SafcrIr2.woff2 +0 -0
  91. flowdeck/static/assets/chakra-petch-latin-500-normal-BR1ody1F.woff2 +0 -0
  92. flowdeck/static/assets/chakra-petch-latin-500-normal-CnUQnZ4D.woff +0 -0
  93. flowdeck/static/assets/chakra-petch-latin-600-normal-DQKfcdKo.woff +0 -0
  94. flowdeck/static/assets/chakra-petch-latin-600-normal-DVQm9bgb.woff2 +0 -0
  95. flowdeck/static/assets/chakra-petch-latin-700-normal-CnDBPjkL.woff2 +0 -0
  96. flowdeck/static/assets/chakra-petch-latin-700-normal-D1s_c2du.woff +0 -0
  97. flowdeck/static/assets/chakra-petch-latin-ext-400-normal-C8u6EFkq.woff2 +0 -0
  98. flowdeck/static/assets/chakra-petch-latin-ext-400-normal-MNNNbyh_.woff +0 -0
  99. flowdeck/static/assets/chakra-petch-latin-ext-500-normal-BCHeNDEx.woff +0 -0
  100. flowdeck/static/assets/chakra-petch-latin-ext-500-normal-gA6791b0.woff2 +0 -0
  101. flowdeck/static/assets/chakra-petch-latin-ext-600-normal-CdGvbdDU.woff2 +0 -0
  102. flowdeck/static/assets/chakra-petch-latin-ext-600-normal-nL80L4xU.woff +0 -0
  103. flowdeck/static/assets/chakra-petch-latin-ext-700-normal-BeviJPUl.woff +0 -0
  104. flowdeck/static/assets/chakra-petch-latin-ext-700-normal-DAkvJhej.woff2 +0 -0
  105. flowdeck/static/assets/chakra-petch-thai-400-normal-Bw1Q-fVY.woff2 +0 -0
  106. flowdeck/static/assets/chakra-petch-thai-400-normal-KdzBjiWs.woff +0 -0
  107. flowdeck/static/assets/chakra-petch-thai-500-normal-CJG_V2_m.woff +0 -0
  108. flowdeck/static/assets/chakra-petch-thai-500-normal-DeexCGiz.woff2 +0 -0
  109. flowdeck/static/assets/chakra-petch-thai-600-normal-BiM5MXH8.woff +0 -0
  110. flowdeck/static/assets/chakra-petch-thai-600-normal-C620THcd.woff2 +0 -0
  111. flowdeck/static/assets/chakra-petch-thai-700-normal-B7WL5pBr.woff2 +0 -0
  112. flowdeck/static/assets/chakra-petch-thai-700-normal-vZLZ_5L8.woff +0 -0
  113. flowdeck/static/assets/chakra-petch-vietnamese-400-normal-Cn7ya5On.woff +0 -0
  114. flowdeck/static/assets/chakra-petch-vietnamese-500-normal-BVzUBLGs.woff +0 -0
  115. flowdeck/static/assets/chakra-petch-vietnamese-600-normal-Pvj4qcw_.woff +0 -0
  116. flowdeck/static/assets/chakra-petch-vietnamese-700-normal-gQuUA8Wu.woff +0 -0
  117. flowdeck/static/assets/index-DpymzEZv.css +1 -0
  118. flowdeck/static/assets/index-DuXbXiXo.js +2 -0
  119. flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  120. flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  121. flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  122. flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  123. flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  124. flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  125. flowdeck/static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  126. flowdeck/static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  127. flowdeck/static/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  128. flowdeck/static/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  129. flowdeck/static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  130. flowdeck/static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  131. flowdeck/static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  132. flowdeck/static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  133. flowdeck/static/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  134. flowdeck/static/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  135. flowdeck/static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  136. flowdeck/static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  137. flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  138. flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  139. flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  140. flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  141. flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  142. flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  143. flowdeck/static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  144. flowdeck/static/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  145. flowdeck/static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  146. flowdeck/static/assets/light-B0F-b5Z6.js +20 -0
  147. flowdeck/static/assets/runtime-dom.esm-bundler-DESsN8Jj.js +2 -0
  148. flowdeck/static/favicon.svg +13 -0
  149. flowdeck/static/index.html +18 -0
  150. flowdeck/storage.py +145 -0
  151. flowdeck/tasks/__init__.py +1 -0
  152. flowdeck/tasks/http_executor.py +985 -0
  153. flowdeck/tasks/paramdefs.py +170 -0
  154. flowdeck/tasks/paramextract.py +185 -0
  155. flowdeck/tasks/python_executor.py +234 -0
  156. flowdeck/tasks/sql_executor.py +683 -0
  157. flowdeck/tasks/timevars.py +125 -0
  158. flowdeck/tasks/ui_registry.py +394 -0
  159. flowdeck-0.2.1.dist-info/METADATA +228 -0
  160. flowdeck-0.2.1.dist-info/RECORD +163 -0
  161. flowdeck-0.2.1.dist-info/WHEEL +4 -0
  162. flowdeck-0.2.1.dist-info/entry_points.txt +2 -0
  163. flowdeck-0.2.1.dist-info/licenses/LICENSE +293 -0
@@ -0,0 +1,661 @@
1
+ """Pipeline 执行器:``run()`` 是真正执行 pipeline 的唯一入口。
2
+
3
+ 与 plombery 的核心差异:
4
+ - run 状态机为 PENDING → RUNNING → SUCCEEDED/FAILED/SKIPPED;
5
+ - UI 暂停通过 executor 级拦截实现(job 照常触发,但 run 标记为
6
+ SKIPPED 并写日志),每次被拦截的触发都有迹可查;
7
+ - 整个任务循环支持 ``pipeline.timeout_seconds`` 超时,超时视为
8
+ failed 并发出独立的 ``timeout`` 通知事件。
9
+ """
10
+
11
+ import asyncio
12
+ import inspect
13
+ import json
14
+ import logging
15
+ import traceback
16
+ from dataclasses import dataclass
17
+ from datetime import datetime
18
+ from typing import Any, Callable, Dict, Optional, Set
19
+
20
+ from pydantic import BaseModel
21
+
22
+ from flowdeck.database import repository
23
+ from flowdeck.logger import close_run_loggers, get_logger
24
+ from flowdeck.notifications.engine import notification_manager
25
+ from flowdeck.pipeline.context import pipeline_context, run_context, task_context
26
+ from flowdeck.schemas import PipelineRunStatus
27
+ from flowdeck.storage import has_task_data, read_task_data, write_task_data
28
+
29
+ MANUAL_TRIGGER_ID = "_manual"
30
+
31
+ _logger = logging.getLogger(__name__)
32
+
33
+ # 正在执行的 run:run_id -> asyncio.Task(kill API 用,进程内有效)
34
+ _active_runs: Dict[int, asyncio.Task] = {}
35
+ # 被 kill API 主动取消的 run id(区分「用户 kill」与「超时取消」两种 CancelledError)
36
+ _killed_run_ids: Set[int] = set()
37
+
38
+
39
+ class _TaskFailure(Exception):
40
+ """任务循环内部用:携带失败 traceback 跳出循环。"""
41
+
42
+ def __init__(self, error: str):
43
+ super().__init__(error)
44
+ self.error = error
45
+
46
+
47
+ @dataclass
48
+ class TaskFunctionSignature:
49
+ has_positional_args: bool = False
50
+ has_params_arg: bool = False
51
+
52
+
53
+ def check_task_signature(func: Callable) -> TaskFunctionSignature:
54
+ """判断任务函数是否声明了位置参数(接收上游数据)与 ``params`` 参数。
55
+
56
+ 签名形如 ``def task_fn(previous_task_output, params: Model)``。
57
+ 严格按 ``parameter.kind`` 显式分支判定(plombery 原实现把类属性
58
+ ``inspect.Parameter.VAR_POSITIONAL`` 当实例真值用,属恒真 bug,
59
+ 这里修正语义:位置参数收上游数据、名为 ``params`` 的参数收配置、
60
+ ``**kwargs`` 收配置)。
61
+ """
62
+ result = TaskFunctionSignature()
63
+
64
+ for name, parameter in inspect.signature(func).parameters.items():
65
+ kind = parameter.kind
66
+ if kind in (
67
+ inspect.Parameter.POSITIONAL_ONLY,
68
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
69
+ inspect.Parameter.VAR_POSITIONAL,
70
+ ):
71
+ if name == "params":
72
+ result.has_params_arg = True
73
+ else:
74
+ result.has_positional_args = True
75
+ elif kind == inspect.Parameter.KEYWORD_ONLY and name == "params":
76
+ result.has_params_arg = True
77
+ elif kind == inspect.Parameter.VAR_KEYWORD:
78
+ result.has_params_arg = True
79
+
80
+ return result
81
+
82
+
83
+ async def _execute_task(task, flowing_data, params: Optional[BaseModel] = None):
84
+ """调用单个 task.run:async 直接 await,sync 直接调。"""
85
+ signature = check_task_signature(task.run)
86
+
87
+ args = [flowing_data] if signature.has_positional_args else []
88
+ kwargs = {"params": params} if params is not None and signature.has_params_arg else {}
89
+
90
+ token = task_context.set(task)
91
+ try:
92
+ # async 直接 await;sync 直接调(iscoroutinefunction 会解包 functools.partial)
93
+ if asyncio.iscoroutinefunction(task.run):
94
+ return await task.run(*args, **kwargs)
95
+ return task.run(*args, **kwargs)
96
+ finally:
97
+ task_context.reset(token)
98
+
99
+
100
+ def _store_task_output(run_id: int, task_id: str, result: Any, logger) -> None:
101
+ """任务输出 JSON 落盘;不可序列化时 str() 兜底并注明。"""
102
+ try:
103
+ try:
104
+ json.dumps(result, ensure_ascii=False)
105
+ data = result
106
+ except (TypeError, ValueError):
107
+ data = {
108
+ "_note": "task output is not JSON serializable, stored via str()",
109
+ "value": str(result),
110
+ }
111
+ write_task_data(run_id, task_id, data)
112
+ except Exception:
113
+ logger.warning("Can't store the output of task %s", task_id, exc_info=True)
114
+
115
+
116
+ def _notify_task_result(pipeline_run, task, result, task_start: datetime) -> None:
117
+ """任务成功后按任务配置把结果直发企微(未配置 / YAML 任务为空操作)。
118
+
119
+ 补数 run 会逐日执行,避免一次回填刷屏,补数期间不发结果通知。
120
+ """
121
+ if getattr(pipeline_run, "reason", None) == "backfill":
122
+ return
123
+ try:
124
+ # 延迟 import:保持 executor 与本模块无环,与 notifications.engine 约定一致
125
+ from flowdeck.notifications.task_result import notify_task_result
126
+
127
+ notify_task_result(
128
+ pipeline_run.pipeline_id,
129
+ task.id,
130
+ result,
131
+ task_start,
132
+ pipeline_run.id,
133
+ )
134
+ except Exception:
135
+ _logger.warning("Failed to notify task result for %s", task.id, exc_info=True)
136
+
137
+
138
+ def _finish_task_run(task_run_id, task_start: datetime, status, error=None):
139
+ duration = (datetime.now() - task_start).total_seconds()
140
+ try:
141
+ repository.update_task_run(
142
+ task_run_id,
143
+ status,
144
+ end_time=datetime.now(),
145
+ duration=duration,
146
+ error=error,
147
+ )
148
+ except Exception:
149
+ _logger.error("Failed to update task run %s", task_run_id, exc_info=True)
150
+
151
+
152
+ def _finish_run(pipeline_run, status, event: str, pipeline, trigger, error=None):
153
+ """写终态(end_time/duration/error)并发出通知事件,返回最新 run。"""
154
+ end_time = datetime.now()
155
+ duration = (end_time - pipeline_run.start_time).total_seconds()
156
+ try:
157
+ run = repository.update_run_status(
158
+ pipeline_run.id, status, end_time=end_time, duration=duration, error=error
159
+ )
160
+ except Exception:
161
+ _logger.error("Failed to update run %s", pipeline_run.id, exc_info=True)
162
+ run = None
163
+
164
+ try:
165
+ # fire-and-forget:emit 内部自行 spawn asyncio task,失败只记日志
166
+ notification_manager.emit_run_event(event, run or pipeline_run, pipeline, trigger)
167
+ except Exception:
168
+ _logger.warning("Failed to emit %s event", event, exc_info=True)
169
+
170
+ return run or pipeline_run
171
+
172
+
173
+ async def _run_all_tasks(
174
+ pipeline,
175
+ pipeline_run,
176
+ pipeline_params,
177
+ logger,
178
+ resume_from: Optional[str] = None,
179
+ source_run_id: Optional[int] = None,
180
+ ):
181
+ """顺序执行全部 tasks:上游输出流向下游,失败即中断。
182
+
183
+ 任务失败自动重试:``Task.retries`` 为额外重试次数(默认 0 不重试,
184
+ 按需配置),每次间隔 retry_delay 秒(固定间隔);重试只对普通异常生效,
185
+ 超时取消(CancelledError)不重试直接中断。重试期间占用 pipeline
186
+ 整体 timeout_seconds 预算。
187
+
188
+ 断点续跑(``resume_from`` 指定起始 task id):其前的任务不执行、记为
189
+ SKIPPED,输入数据从 ``source_run_id`` 原始 run 的输出文件复用;上游
190
+ 产物文件已被清理时整个 run 失败(宁可失败也不带错数据继续跑)。
191
+
192
+ 任务级超时(``Task.timeout_seconds``,None 不限制):单个任务超过时限
193
+ 按失败处理,错误消息注明超时;与普通失败一样参与重试。
194
+ """
195
+ flowing_data = None
196
+
197
+ if resume_from is not None and not any(t.id == resume_from for t in pipeline.tasks):
198
+ raise _TaskFailure(
199
+ f"cannot resume: task `{resume_from}` not found in pipeline `{pipeline.id}`"
200
+ )
201
+
202
+ resuming = resume_from is not None
203
+ for task in pipeline.tasks:
204
+ if resuming and task.id != resume_from:
205
+ # 断点之前的任务:不执行,记 SKIPPED,并复用原 run 的输出供下游使用
206
+ logger.info("Task %s skipped (resumed from %s)", task.id, resume_from)
207
+ task_start = datetime.now()
208
+ task_run = repository.create_task_run(
209
+ pipeline_run.id, task.id, PipelineRunStatus.SKIPPED, task_start
210
+ )
211
+ _finish_task_run(task_run.id, task_start, PipelineRunStatus.SKIPPED)
212
+ if source_run_id is not None:
213
+ if not has_task_data(source_run_id, task.id):
214
+ raise _TaskFailure(
215
+ f"cannot resume: output of upstream task `{task.id}` in "
216
+ f"run #{source_run_id} is missing (cleaned up?)"
217
+ )
218
+ flowing_data = read_task_data(source_run_id, task.id)
219
+ continue
220
+
221
+ resuming = False
222
+
223
+ logger.info("Executing task %s", task.id)
224
+
225
+ task_start = datetime.now()
226
+ task_run = repository.create_task_run(
227
+ pipeline_run.id, task.id, PipelineRunStatus.RUNNING, task_start
228
+ )
229
+
230
+ total_attempts = task.retries + 1
231
+ for attempt in range(1, total_attempts + 1):
232
+ try:
233
+ if task.timeout_seconds and task.timeout_seconds > 0:
234
+ # 任务级超时:wait_for 超时后取消内部协程并抛 TimeoutError
235
+ result = await asyncio.wait_for(
236
+ _execute_task(task, flowing_data, pipeline_params),
237
+ timeout=task.timeout_seconds,
238
+ )
239
+ else:
240
+ result = await _execute_task(task, flowing_data, pipeline_params)
241
+ break
242
+ except asyncio.CancelledError:
243
+ # 取消(用户 kill 或超时):当前 task 标记为失败后继续向上抛出(不重试)
244
+ _finish_task_run(
245
+ task_run.id,
246
+ task_start,
247
+ PipelineRunStatus.FAILED,
248
+ error=(
249
+ "task cancelled by user (kill)"
250
+ if pipeline_run.id in _killed_run_ids
251
+ else "task cancelled: pipeline timed out"
252
+ ),
253
+ )
254
+ raise
255
+ except asyncio.TimeoutError:
256
+ # 任务级超时(wait_for 抛出)按「超时失败」处理(可重试);
257
+ # 任务未配置 timeout_seconds 时,这里是任务内部抛出的原生
258
+ # TimeoutError(3.11+ 中 socket.timeout 即其别名),须按普通
259
+ # 异常处理,避免误标超时并保留真实 traceback。
260
+ timed_out = bool(task.timeout_seconds and task.timeout_seconds > 0)
261
+ if timed_out:
262
+ error = (
263
+ f"task `{task.id}` timed out after {task.timeout_seconds}s"
264
+ )
265
+ logger.error("Task %s timed out after %ss", task.id, task.timeout_seconds)
266
+ else:
267
+ error = traceback.format_exc()
268
+ logger.error(
269
+ "Task %s failed after %d attempt(s)",
270
+ task.id,
271
+ attempt,
272
+ exc_info=True,
273
+ )
274
+ if attempt >= total_attempts:
275
+ _finish_task_run(task_run.id, task_start, PipelineRunStatus.FAILED, error=error)
276
+ if timed_out:
277
+ raise _TaskFailure(error) from None
278
+ raise _TaskFailure(error)
279
+ logger.warning(
280
+ "Task %s %s (attempt %d/%d), retrying in %ss",
281
+ task.id,
282
+ "timed out" if timed_out else "failed",
283
+ attempt,
284
+ total_attempts,
285
+ task.retry_delay,
286
+ )
287
+ if task.retry_delay > 0:
288
+ await asyncio.sleep(task.retry_delay)
289
+ except Exception:
290
+ if attempt >= total_attempts:
291
+ error = traceback.format_exc()
292
+ logger.error(
293
+ "Task %s failed after %d attempt(s)",
294
+ task.id,
295
+ attempt,
296
+ exc_info=True,
297
+ )
298
+ _finish_task_run(task_run.id, task_start, PipelineRunStatus.FAILED, error=error)
299
+ raise _TaskFailure(error)
300
+ logger.warning(
301
+ "Task %s failed (attempt %d/%d), retrying in %ss",
302
+ task.id,
303
+ attempt,
304
+ total_attempts,
305
+ task.retry_delay,
306
+ )
307
+ if task.retry_delay > 0:
308
+ await asyncio.sleep(task.retry_delay)
309
+
310
+ _store_task_output(pipeline_run.id, task.id, result, logger)
311
+ _finish_task_run(task_run.id, task_start, PipelineRunStatus.SUCCEEDED)
312
+ # 图片渲染是纯 CPU 的重活,放线程池里跑,避免阻塞事件循环上的调度与接口响应
313
+ await asyncio.to_thread(
314
+ _notify_task_result, pipeline_run, task, result, task_start
315
+ )
316
+ flowing_data = result
317
+
318
+
319
+ async def run(
320
+ pipeline,
321
+ trigger=None,
322
+ params: Optional[dict] = None,
323
+ pipeline_run=None,
324
+ reason: str = "scheduled",
325
+ resume_from: Optional[str] = None,
326
+ ):
327
+ """执行 pipeline 的全部 tasks(调度触发与手动触发共用入口)。
328
+
329
+ - ``pipeline_run is None``:定时触发,先创建 PENDING run(reason="scheduled");
330
+ - ``reason == "scheduled"`` 时执行 UI 暂停/触发器禁用拦截,命中则 run 标记
331
+ SKIPPED 并写日志后返回;手动触发(reason="api")不检查暂停状态;
332
+ - 任务顺序执行,上游输出流向下游;任务配置 retries 时失败自动重试
333
+ (默认 0 不重试),全部尝试耗尽 → 整个 run FAILED 并中断后续;
334
+ - ``pipeline.timeout_seconds`` 有值时整个任务循环受 ``asyncio.wait_for`` 约束,
335
+ 超时 → run FAILED(error 注明 timeout)+ "timeout" 事件;
336
+ - ``resume_from``:断点续跑起始 task id(其前任务 SKIPPED 并复用
337
+ ``pipeline_run.source_run_id`` 原始 run 的任务输出);
338
+ - 并发策略 ``pipeline.concurrency``(默认 skip):同 pipeline 已有
339
+ 运行中 run 时,skip 放弃本次(SKIPPED 留痕),cancel_previous
340
+ 先 kill 旧 run 再执行,parallel 完全并行。
341
+ """
342
+
343
+ if pipeline_run is None:
344
+ pipeline_run = repository.create_pipeline_run(
345
+ pipeline_id=pipeline.id,
346
+ trigger_id=trigger.id if trigger else MANUAL_TRIGGER_ID,
347
+ status=PipelineRunStatus.PENDING,
348
+ start_time=datetime.now(),
349
+ reason=reason,
350
+ input_params=None,
351
+ )
352
+
353
+ pipeline_token = None
354
+ run_token = None
355
+ logger = None
356
+
357
+ try:
358
+ if reason == "scheduled":
359
+ # UI 暂停/触发器禁用拦截:job 照常触发,但 run 标记为 SKIPPED
360
+ skip_reason = None
361
+ if trigger and repository.is_trigger_disabled(pipeline.id, trigger.id):
362
+ skip_reason = "trigger disabled by UI"
363
+ elif repository.is_pipeline_paused(pipeline.id):
364
+ override = repository.get_pipeline_override(pipeline.id)
365
+ if override and override.resume_at and datetime.now() >= override.resume_at:
366
+ # 定时暂停到期:删除 override 自动恢复,本次照常执行
367
+ repository.clear_override(pipeline.id, "")
368
+ _logger.info(
369
+ "Pipeline %s pause expired at %s, auto-resumed",
370
+ pipeline.id,
371
+ override.resume_at,
372
+ )
373
+ elif override and override.resume_at:
374
+ skip_reason = (
375
+ "pipeline paused by UI until "
376
+ f"{override.resume_at.strftime('%Y-%m-%d %H:%M')}"
377
+ )
378
+ else:
379
+ skip_reason = "pipeline paused by UI"
380
+
381
+ # 停机日历拦截:命中区间(全部或指定任务)→ 定时触发跳过并记录
382
+ if not skip_reason:
383
+ downtime = repository.find_downtime_exception(
384
+ pipeline.id, datetime.now().date()
385
+ )
386
+ if downtime:
387
+ skip_reason = f"downtime calendar: {downtime.reason or 'no reason'}"
388
+
389
+ if skip_reason:
390
+ pipeline_token = pipeline_context.set(pipeline)
391
+ run_token = run_context.set(pipeline_run)
392
+ logger = get_logger()
393
+
394
+ pipeline_run = repository.update_run_status(
395
+ pipeline_run.id,
396
+ PipelineRunStatus.SKIPPED,
397
+ end_time=datetime.now(),
398
+ duration=(datetime.now() - pipeline_run.start_time).total_seconds(),
399
+ error=skip_reason,
400
+ )
401
+ logger.warning("run skipped: %s", skip_reason)
402
+ # 跳过也发通知事件(error 字段携带跳过原因),匹配规则自行决定是否接收
403
+ try:
404
+ notification_manager.emit_run_event(
405
+ "skipped", pipeline_run, pipeline, trigger
406
+ )
407
+ except Exception:
408
+ _logger.warning("Failed to emit skipped event", exc_info=True)
409
+ return pipeline_run
410
+
411
+ # 并发互斥:同 pipeline 已有运行中 run 时的策略(对所有触发方式生效)。
412
+ # 默认 skip:重叠触发直接放弃本次并留痕,防止重复写库/重复调用;
413
+ # cancel_previous:kill 在跑的旧 run(取消在最近 await 点生效)再执行。
414
+ concurrency = (getattr(pipeline, "concurrency", None) or "skip").lower()
415
+ if concurrency != "parallel":
416
+ running_ids = repository.list_running_run_ids(
417
+ pipeline.id, exclude_run_id=pipeline_run.id
418
+ )
419
+ if running_ids:
420
+ if concurrency == "cancel_previous":
421
+ for running_id in running_ids:
422
+ _logger.info(
423
+ "concurrency=cancel_previous: killing run %d of pipeline %s",
424
+ running_id,
425
+ pipeline.id,
426
+ )
427
+ cancel_run(running_id)
428
+ else:
429
+ pipeline_token = pipeline_context.set(pipeline)
430
+ run_token = run_context.set(pipeline_run)
431
+ logger = get_logger()
432
+
433
+ skip_reason = (
434
+ f"concurrency=skip: run #{running_ids[-1]} of this "
435
+ "pipeline is still running"
436
+ )
437
+ pipeline_run = repository.update_run_status(
438
+ pipeline_run.id,
439
+ PipelineRunStatus.SKIPPED,
440
+ end_time=datetime.now(),
441
+ duration=(datetime.now() - pipeline_run.start_time).total_seconds(),
442
+ error=skip_reason,
443
+ )
444
+ logger.warning("run skipped: %s", skip_reason)
445
+ # 并发放弃同样发 skipped 事件(error 携带在跑的 run 编号)
446
+ try:
447
+ notification_manager.emit_run_event(
448
+ "skipped", pipeline_run, pipeline, trigger
449
+ )
450
+ except Exception:
451
+ _logger.warning("Failed to emit skipped event", exc_info=True)
452
+ return pipeline_run
453
+
454
+ # 进入 RUNNING
455
+ pipeline_run = repository.update_run_status(
456
+ pipeline_run.id, PipelineRunStatus.RUNNING
457
+ )
458
+ pipeline_token = pipeline_context.set(pipeline)
459
+ run_token = run_context.set(pipeline_run)
460
+ logger = get_logger()
461
+
462
+ # 注册进活动表(kill API 按 run_id 定位 asyncio.Task 取消)
463
+ current_task = asyncio.current_task()
464
+ if current_task is not None:
465
+ _active_runs[pipeline_run.id] = current_task
466
+
467
+ logger.info(
468
+ "Executing pipeline `%s` #%d via trigger `%s`",
469
+ pipeline.id,
470
+ pipeline_run.id,
471
+ trigger.id if trigger else MANUAL_TRIGGER_ID,
472
+ )
473
+
474
+ # 解析 pipeline 参数:手动运行用传入 params,定时运行用默认值
475
+ pipeline_params = None
476
+ if pipeline.params:
477
+ try:
478
+ pipeline_params = pipeline.params(**(params or {}))
479
+ except Exception:
480
+ error = traceback.format_exc()
481
+ logger.error("Invalid input params", exc_info=True)
482
+ return _finish_run(
483
+ pipeline_run,
484
+ PipelineRunStatus.FAILED,
485
+ "failed",
486
+ pipeline,
487
+ trigger,
488
+ error=error,
489
+ )
490
+ elif params:
491
+ logger.warning("This pipeline doesn't support input params")
492
+
493
+ try:
494
+ if pipeline.timeout_seconds and pipeline.timeout_seconds > 0:
495
+ await asyncio.wait_for(
496
+ _run_all_tasks(
497
+ pipeline,
498
+ pipeline_run,
499
+ pipeline_params,
500
+ logger,
501
+ resume_from=resume_from,
502
+ source_run_id=pipeline_run.source_run_id,
503
+ ),
504
+ timeout=pipeline.timeout_seconds,
505
+ )
506
+ else:
507
+ await _run_all_tasks(
508
+ pipeline,
509
+ pipeline_run,
510
+ pipeline_params,
511
+ logger,
512
+ resume_from=resume_from,
513
+ source_run_id=pipeline_run.source_run_id,
514
+ )
515
+ except asyncio.TimeoutError:
516
+ logger.error("Pipeline timed out after %ss", pipeline.timeout_seconds)
517
+ return _finish_run(
518
+ pipeline_run,
519
+ PipelineRunStatus.FAILED,
520
+ "timeout",
521
+ pipeline,
522
+ trigger,
523
+ error=f"pipeline timed out after {pipeline.timeout_seconds}s",
524
+ )
525
+ except _TaskFailure as exc:
526
+ return _finish_run(
527
+ pipeline_run,
528
+ PipelineRunStatus.FAILED,
529
+ "failed",
530
+ pipeline,
531
+ trigger,
532
+ error=exc.error,
533
+ )
534
+ except asyncio.CancelledError:
535
+ # 用户 kill:落终态(error 注明),后续可用断点续跑恢复;
536
+ # 非 kill 的取消(如进程退出)不落终态,交给启动时崩溃恢复
537
+ if pipeline_run.id in _killed_run_ids:
538
+ logger.warning(
539
+ "Pipeline run %d cancelled by user (kill)", pipeline_run.id
540
+ )
541
+ return _finish_run(
542
+ pipeline_run,
543
+ PipelineRunStatus.FAILED,
544
+ "failed",
545
+ pipeline,
546
+ trigger,
547
+ error="run cancelled by user (kill)",
548
+ )
549
+ logger.warning(
550
+ "Pipeline run %d cancelled without kill request"
551
+ " (treated as process interruption)",
552
+ pipeline_run.id,
553
+ )
554
+ raise
555
+
556
+ return _finish_run(
557
+ pipeline_run, PipelineRunStatus.SUCCEEDED, "succeeded", pipeline, trigger
558
+ )
559
+ except Exception:
560
+ # 最终兜底(xxl-job 语义:执行异常必须落终态):拦截检查/状态更新等
561
+ # 环节的意外异常若直接外抛,run 会永远停留在 PENDING/RUNNING
562
+ _logger.error("Pipeline run crashed unexpectedly", exc_info=True)
563
+ try:
564
+ return repository.update_run_status(
565
+ pipeline_run.id,
566
+ PipelineRunStatus.FAILED,
567
+ end_time=datetime.now(),
568
+ duration=(datetime.now() - pipeline_run.start_time).total_seconds(),
569
+ error=traceback.format_exc(),
570
+ )
571
+ except Exception:
572
+ return pipeline_run
573
+ finally:
574
+ if pipeline_run is not None:
575
+ # 关闭本次 run 的全部 logger(pipeline 级 + 各 task 级)的文件句柄
576
+ close_run_loggers(pipeline_run.id)
577
+ _active_runs.pop(pipeline_run.id, None)
578
+ # 无论以何种方式结束(含任务代码吞掉 CancelledError 的边缘场景)
579
+ # 都清理 kill 标记,避免残留条目影响诊断
580
+ _killed_run_ids.discard(pipeline_run.id)
581
+ if run_token is not None:
582
+ run_context.reset(run_token)
583
+ if pipeline_token is not None:
584
+ pipeline_context.reset(pipeline_token)
585
+
586
+
587
+ # ---------------------------------------------------------------------------
588
+ # 运行管控:kill / 崩溃恢复
589
+ # ---------------------------------------------------------------------------
590
+
591
+
592
+ def is_run_active(run_id: int) -> bool:
593
+ """run 是否正在本进程内执行(有注册的 asyncio.Task)。"""
594
+ return run_id in _active_runs
595
+
596
+
597
+ def cancel_run(run_id: int) -> bool:
598
+ """请求取消正在执行的 run(kill):向其 asyncio.Task 投递 CancelledError。
599
+
600
+ 取消在最近的 await 点生效;同步阻塞型任务(不 await 的普通函数)
601
+ 无法被打断,会在其结束后才终止。返回 False 表示该 run 不在当前
602
+ 进程的执行队列中(未运行/僵尸状态)。
603
+ """
604
+ task = _active_runs.get(run_id)
605
+ if task is None or task.done():
606
+ return False
607
+
608
+ _killed_run_ids.add(run_id)
609
+ task.cancel()
610
+ _logger.warning("Kill requested for run %d", run_id)
611
+ return True
612
+
613
+
614
+ def recover_interrupted_runs() -> Dict[str, int]:
615
+ """崩溃恢复:启动时清理上次进程中断遗留的 PENDING/RUNNING run。
616
+
617
+ 进程中断(断电/kill 进程/崩溃)时 run 停留在 RUNNING(或尚未开始
618
+ 执行的 PENDING),没有任何执行路径再处理它们。这里统一标记为
619
+ FAILED(error 注明进程中断),RUNNING 的 task_runs 一并落失败;
620
+ 之后用户可走常规的重跑/断点续跑入口恢复。返回统计:
621
+ {"runs": 清理的 run 数, "task_runs": 连带失败的 task_run 数}。
622
+ """
623
+ now = datetime.now()
624
+ stats = {"runs": 0, "task_runs": 0}
625
+
626
+ interrupted = repository.list_runs_by_statuses(
627
+ [PipelineRunStatus.RUNNING, PipelineRunStatus.PENDING]
628
+ )
629
+ for run_row in interrupted:
630
+ if run_row.status == PipelineRunStatus.RUNNING.value:
631
+ error = (
632
+ "进程中断:服务重启时该运行仍在执行中"
633
+ "(崩溃恢复自动标记为失败,可用重跑/断点续跑恢复)"
634
+ )
635
+ else:
636
+ error = (
637
+ "进程中断:服务重启时该运行尚未开始执行"
638
+ "(崩溃恢复自动标记为失败,可重跑)"
639
+ )
640
+ try:
641
+ stats["task_runs"] += repository.fail_running_task_runs(run_row.id, error)
642
+ repository.update_run_status(
643
+ run_row.id,
644
+ PipelineRunStatus.FAILED,
645
+ end_time=now,
646
+ duration=(now - run_row.start_time).total_seconds(),
647
+ error=error,
648
+ )
649
+ close_run_loggers(run_row.id)
650
+ stats["runs"] += 1
651
+ _logger.warning(
652
+ "Recovered interrupted run %d (was %s, pipeline=%s)",
653
+ run_row.id,
654
+ run_row.status,
655
+ run_row.pipeline_id,
656
+ )
657
+ except Exception:
658
+ _logger.error(
659
+ "Failed to recover interrupted run %d", run_row.id, exc_info=True
660
+ )
661
+ return stats
@@ -0,0 +1,5 @@
1
+ from .pipeline import Pipeline
2
+ from .task import Task, task
3
+ from .trigger import Trigger
4
+
5
+ __all__ = ["task", "Task", "Pipeline", "Trigger"]
@@ -0,0 +1,11 @@
1
+ import re
2
+
3
+
4
+ def prettify_name(name: str) -> str:
5
+ """把下划线替换为空格,美化名称(参考 plombery)。"""
6
+ return re.sub(r"_+", " ", name).strip()
7
+
8
+
9
+ def get_job_id(pipeline_id: str, trigger_id: str) -> str:
10
+ """生成 APScheduler 的 Job ID,用于反查关联的 pipeline 与 trigger。"""
11
+ return f"{pipeline_id}__{trigger_id}"
@@ -0,0 +1,13 @@
1
+ from contextvars import ContextVar
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ # 仅为类型提示服务,避免 pipeline -> database 的运行时循环导入
6
+ from flowdeck.database.models import PipelineRun
7
+ from flowdeck.pipeline.pipeline import Pipeline
8
+ from flowdeck.pipeline.task import Task
9
+
10
+ pipeline_context: ContextVar["Pipeline"] = ContextVar("pipeline")
11
+ task_context: ContextVar["Task"] = ContextVar("task")
12
+ # 运行时存 ORM PipelineRun 对象;手动运行等场景可能未设置(使用处需 get(None))
13
+ run_context: ContextVar["PipelineRun"] = ContextVar("run")