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,274 @@
1
+ """pipelines 路由:列表/详情/手动运行/暂停恢复(可定时自动恢复)/批量操作/触发器开关/未来触发时间/统计。"""
2
+
3
+ from datetime import datetime
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from fastapi import APIRouter, HTTPException, Query
7
+ from pydantic import BaseModel
8
+
9
+ from flowdeck.database import repository
10
+ from flowdeck.orchestrator import orchestrator
11
+ from flowdeck.pipeline.pipeline import Pipeline
12
+ from flowdeck.pipeline.trigger import Trigger
13
+
14
+ router = APIRouter(prefix="/pipelines", tags=["Pipelines"])
15
+
16
+
17
+ def _get_pipeline_or_404(pipeline_id: str) -> Pipeline:
18
+ pipeline = orchestrator.get_pipeline(pipeline_id)
19
+ if pipeline is None:
20
+ raise HTTPException(
21
+ status_code=404, detail=f"Pipeline {pipeline_id} 不存在"
22
+ )
23
+ return pipeline
24
+
25
+
26
+ def _get_trigger_or_404(pipeline: Pipeline, trigger_id: str) -> Trigger:
27
+ for trigger in pipeline.triggers:
28
+ if trigger.id == trigger_id:
29
+ return trigger
30
+ raise HTTPException(status_code=404, detail=f"触发器 {trigger_id} 不存在")
31
+
32
+
33
+ def _parse_resume_at(value: Optional[str]) -> Optional[datetime]:
34
+ """解析「暂停至」时间:支持 YYYY-MM-DD HH:MM(推荐)与 ISO 格式。
35
+
36
+ naive 值按服务器本地时间理解;带时区的值转换为本地时间后去 tzinfo。
37
+ 必须是未来时间(过去的恢复时间会在下次触发时立即自动恢复,视为误操作)。
38
+ """
39
+ if value is None or not value.strip():
40
+ return None
41
+
42
+ value = value.strip()
43
+ for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"):
44
+ try:
45
+ parsed = datetime.strptime(value, fmt)
46
+ break
47
+ except ValueError:
48
+ continue
49
+ else:
50
+ try:
51
+ parsed = datetime.fromisoformat(value)
52
+ except ValueError as exc:
53
+ raise HTTPException(
54
+ status_code=422,
55
+ detail=f"resume_at 格式无效 `{value}`:"
56
+ f"应为 YYYY-MM-DD HH:MM 或 ISO 时间",
57
+ ) from exc
58
+ if parsed.tzinfo is not None:
59
+ parsed = parsed.astimezone().replace(tzinfo=None)
60
+
61
+ if parsed <= datetime.now():
62
+ raise HTTPException(
63
+ status_code=422, detail="resume_at 必须晚于当前时间"
64
+ )
65
+ return parsed
66
+
67
+
68
+ def _last_run_summary(pipeline_id: str) -> Optional[Dict[str, Any]]:
69
+ runs, _total = repository.list_runs(pipeline_id=pipeline_id, page=1, page_size=1)
70
+ if not runs:
71
+ return None
72
+ run = runs[0]
73
+ return {
74
+ "id": run.id,
75
+ "status": run.status,
76
+ "start_time": run.start_time,
77
+ "duration": run.duration,
78
+ "reason": run.reason,
79
+ }
80
+
81
+
82
+ def _serialize_trigger(
83
+ pipeline: Pipeline, trigger: Trigger, pipeline_paused: bool
84
+ ) -> Dict[str, Any]:
85
+ disabled = repository.is_trigger_disabled(pipeline.id, trigger.id)
86
+ # 代码级暂停 / UI 禁用 / pipeline 级暂停时不会真正执行,next_run_time 置 null
87
+ next_run_time = None
88
+ if not trigger.paused and not disabled and not pipeline_paused:
89
+ job = orchestrator.get_job(pipeline.id, trigger.id)
90
+ next_run_time = job.next_run_time if job else None
91
+
92
+ return {
93
+ "id": trigger.id,
94
+ "name": trigger.name,
95
+ "paused": trigger.paused,
96
+ "disabled": disabled,
97
+ "schedule_desc": str(trigger.schedule),
98
+ "next_run_time": next_run_time,
99
+ }
100
+
101
+
102
+ def _serialize_pipeline(pipeline: Pipeline) -> Dict[str, Any]:
103
+ override = repository.get_pipeline_override(pipeline.id)
104
+ pipeline_paused = override is not None
105
+ triggers = [
106
+ _serialize_trigger(pipeline, trigger, pipeline_paused)
107
+ for trigger in pipeline.triggers
108
+ ]
109
+ active_times = [
110
+ trigger["next_run_time"]
111
+ for trigger in triggers
112
+ if trigger["next_run_time"] is not None
113
+ ]
114
+
115
+ return {
116
+ "id": pipeline.id,
117
+ "name": pipeline.name,
118
+ "description": pipeline.description,
119
+ "task_count": len(pipeline.tasks),
120
+ "has_params": pipeline.params is not None,
121
+ "timeout_seconds": pipeline.timeout_seconds,
122
+ "paused": pipeline_paused,
123
+ "resume_at": override.resume_at if override else None,
124
+ "triggers": triggers,
125
+ "last_run": _last_run_summary(pipeline.id),
126
+ "next_run_time": min(active_times) if active_times else None,
127
+ }
128
+
129
+
130
+ @router.get("")
131
+ def list_pipelines():
132
+ return {
133
+ "pipelines": [
134
+ _serialize_pipeline(pipeline)
135
+ for pipeline in orchestrator.pipelines.values()
136
+ ]
137
+ }
138
+
139
+
140
+ @router.get("/{pipeline_id}")
141
+ def get_pipeline(pipeline_id: str):
142
+ pipeline = _get_pipeline_or_404(pipeline_id)
143
+ data = _serialize_pipeline(pipeline)
144
+ data["tasks"] = [
145
+ {"id": task.id, "name": task.name, "description": task.description}
146
+ for task in pipeline.tasks
147
+ ]
148
+ data["params_schema"] = (
149
+ pipeline.params.model_json_schema() if pipeline.params else None
150
+ )
151
+ return data
152
+
153
+
154
+ class RunInput(BaseModel):
155
+ params: Optional[dict] = None
156
+
157
+
158
+ @router.post("/{pipeline_id}/run")
159
+ def run_pipeline(pipeline_id: str, body: RunInput):
160
+ pipeline = _get_pipeline_or_404(pipeline_id)
161
+
162
+ if pipeline.params is not None and body.params:
163
+ try:
164
+ pipeline.params(**body.params)
165
+ except Exception as exc:
166
+ raise HTTPException(
167
+ status_code=422,
168
+ detail=f"Pipeline {pipeline_id} 参数校验失败: {exc}",
169
+ )
170
+
171
+ try:
172
+ run = orchestrator.run_pipeline_now(pipeline, params=body.params)
173
+ except ValueError as exc:
174
+ raise HTTPException(status_code=422, detail=str(exc))
175
+
176
+ return {"run_id": run.id}
177
+
178
+
179
+ @router.get("/{pipeline_id}/next-runs")
180
+ def get_next_runs(pipeline_id: str, count: int = Query(default=5, ge=1, le=100)):
181
+ pipeline = _get_pipeline_or_404(pipeline_id)
182
+
183
+ triggers = [
184
+ {
185
+ "trigger_id": trigger.id,
186
+ "name": trigger.name,
187
+ "paused": trigger.paused,
188
+ "disabled": repository.is_trigger_disabled(pipeline.id, trigger.id),
189
+ "next_runs": orchestrator.get_next_run_times(
190
+ pipeline.id, trigger.id, count
191
+ ),
192
+ }
193
+ for trigger in pipeline.triggers
194
+ ]
195
+ return {"triggers": triggers}
196
+
197
+
198
+ class PauseInput(BaseModel):
199
+ resume_at: Optional[str] = None
200
+ """暂停至指定时间(YYYY-MM-DD HH:MM / ISO);空 = 一直暂停。"""
201
+
202
+
203
+ @router.post("/{pipeline_id}/pause")
204
+ def pause_pipeline(pipeline_id: str, body: Optional[PauseInput] = None):
205
+ _get_pipeline_or_404(pipeline_id)
206
+ resume_at = _parse_resume_at(body.resume_at if body else None)
207
+ orchestrator.pause_pipeline(pipeline_id, resume_at=resume_at)
208
+ override = repository.get_pipeline_override(pipeline_id)
209
+ return {"paused": override is not None, "resume_at": override.resume_at if override else None}
210
+
211
+
212
+ @router.post("/{pipeline_id}/resume")
213
+ def resume_pipeline(pipeline_id: str):
214
+ _get_pipeline_or_404(pipeline_id)
215
+ orchestrator.resume_pipeline(pipeline_id)
216
+ return {"paused": repository.is_pipeline_paused(pipeline_id), "resume_at": None}
217
+
218
+
219
+ class BatchPauseInput(BaseModel):
220
+ ids: List[str]
221
+ resume_at: Optional[str] = None
222
+
223
+
224
+ class BatchResumeInput(BaseModel):
225
+ ids: List[str]
226
+
227
+
228
+ def _validate_batch_ids(ids: List[str]) -> None:
229
+ missing = [pid for pid in ids if orchestrator.get_pipeline(pid) is None]
230
+ if missing:
231
+ raise HTTPException(
232
+ status_code=404, detail=f"Pipeline 不存在: {', '.join(missing)}"
233
+ )
234
+
235
+
236
+ @router.post("/batch-pause")
237
+ def batch_pause_pipelines(body: BatchPauseInput):
238
+ """批量暂停:ids 里的全部 pipeline,可选统一恢复时间。"""
239
+ _validate_batch_ids(body.ids)
240
+ resume_at = _parse_resume_at(body.resume_at)
241
+ for pipeline_id in body.ids:
242
+ orchestrator.pause_pipeline(pipeline_id, resume_at=resume_at)
243
+ return {"updated": len(body.ids), "resume_at": resume_at}
244
+
245
+
246
+ @router.post("/batch-resume")
247
+ def batch_resume_pipelines(body: BatchResumeInput):
248
+ """批量恢复调度。"""
249
+ _validate_batch_ids(body.ids)
250
+ for pipeline_id in body.ids:
251
+ orchestrator.resume_pipeline(pipeline_id)
252
+ return {"updated": len(body.ids)}
253
+
254
+
255
+ @router.post("/{pipeline_id}/triggers/{trigger_id}/disable")
256
+ def disable_trigger(pipeline_id: str, trigger_id: str):
257
+ pipeline = _get_pipeline_or_404(pipeline_id)
258
+ _get_trigger_or_404(pipeline, trigger_id)
259
+ orchestrator.disable_trigger(pipeline_id, trigger_id)
260
+ return {"disabled": repository.is_trigger_disabled(pipeline_id, trigger_id)}
261
+
262
+
263
+ @router.post("/{pipeline_id}/triggers/{trigger_id}/enable")
264
+ def enable_trigger(pipeline_id: str, trigger_id: str):
265
+ pipeline = _get_pipeline_or_404(pipeline_id)
266
+ _get_trigger_or_404(pipeline, trigger_id)
267
+ orchestrator.enable_trigger(pipeline_id, trigger_id)
268
+ return {"disabled": repository.is_trigger_disabled(pipeline_id, trigger_id)}
269
+
270
+
271
+ @router.get("/{pipeline_id}/stats")
272
+ def get_pipeline_stats(pipeline_id: str, days: int = Query(default=90, ge=1, le=3650)):
273
+ _get_pipeline_or_404(pipeline_id)
274
+ return repository.pipeline_stats(pipeline_id, days=days)
@@ -0,0 +1,227 @@
1
+ """runs 路由:运行列表/详情/日志 JSONL/任务输出数据/重跑与断点续跑。"""
2
+
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ from typing import Any, Dict, Optional
6
+
7
+ from fastapi import APIRouter, HTTPException, Query
8
+ from pydantic import BaseModel
9
+ from starlette.responses import PlainTextResponse
10
+
11
+ from flowdeck.database import repository
12
+ from flowdeck.orchestrator import orchestrator
13
+ from flowdeck.schemas import PipelineRunStatus
14
+ from flowdeck.storage import get_logs_filename, read_task_data
15
+
16
+ router = APIRouter(prefix="/runs", tags=["Runs"])
17
+
18
+
19
+ def _error_summary(error: Any, limit: int = 200) -> Optional[str]:
20
+ """错误摘要:traceback 取最后一行(异常类型与消息),否则截断。"""
21
+ if not isinstance(error, str) or not error:
22
+ return None
23
+ lines = [line for line in error.strip().splitlines() if line.strip()]
24
+ if len(lines) >= 2 and len(lines[-1]) <= limit:
25
+ return lines[-1]
26
+ return error if len(error) <= limit else error[:limit] + "…"
27
+
28
+
29
+ def _serialize_run(
30
+ run, failure: Optional[Dict[str, Any]] = None
31
+ ) -> Dict[str, Any]:
32
+ data = {
33
+ "id": run.id,
34
+ "pipeline_id": run.pipeline_id,
35
+ "trigger_id": run.trigger_id,
36
+ "status": run.status,
37
+ "start_time": run.start_time,
38
+ "end_time": run.end_time,
39
+ "duration": run.duration,
40
+ "reason": run.reason,
41
+ "source_run_id": run.source_run_id,
42
+ "error": run.error,
43
+ }
44
+ if failure is not None:
45
+ data["failed_task_id"] = failure.get("failed_task_id")
46
+ data["failed_task_error"] = _error_summary(failure.get("failed_task_error"))
47
+ data["rerun_count"] = failure.get("rerun_count", 0)
48
+ return data
49
+
50
+
51
+ def _serialize_task_run(task_run) -> Dict[str, Any]:
52
+ return {
53
+ "id": task_run.id,
54
+ "task_id": task_run.task_id,
55
+ "status": task_run.status,
56
+ "start_time": task_run.start_time,
57
+ "end_time": task_run.end_time,
58
+ "duration": task_run.duration,
59
+ "error": task_run.error,
60
+ }
61
+
62
+
63
+ @router.get("")
64
+ def list_runs(
65
+ pipeline_id: Optional[str] = None,
66
+ status: Optional[PipelineRunStatus] = None,
67
+ since_hours: Optional[int] = Query(default=None, ge=1, le=24 * 365),
68
+ page: int = Query(default=1, ge=1),
69
+ page_size: int = Query(default=20, ge=1, le=200),
70
+ ):
71
+ """运行列表。since_hours 为相对当前时间的窗口(如 24 / 168),
72
+ 用于「最近报错」页按时间窗口过滤;失败 run 额外返回首个失败任务
73
+ 与已重跑次数(failed_task_id / failed_task_error / rerun_count)。"""
74
+ since = (
75
+ datetime.now() - timedelta(hours=since_hours) if since_hours else None
76
+ )
77
+ runs, total = repository.list_runs(
78
+ pipeline_id=pipeline_id or None,
79
+ status=status,
80
+ page=page,
81
+ page_size=page_size,
82
+ since=since,
83
+ )
84
+
85
+ failures = repository.get_run_failure_details(
86
+ [run.id for run in runs if run.status == PipelineRunStatus.FAILED.value]
87
+ )
88
+ return {
89
+ "items": [
90
+ _serialize_run(run, failures.get(run.id))
91
+ for run in runs
92
+ ],
93
+ "total": total,
94
+ }
95
+
96
+
97
+ @router.get("/{run_id}")
98
+ def get_run_detail(run_id: int):
99
+ run = repository.get_run(run_id)
100
+ if run is None:
101
+ raise HTTPException(status_code=404, detail=f"运行记录 {run_id} 不存在")
102
+
103
+ data = _serialize_run(run)
104
+ data["input_params"] = json.loads(run.input_params) if run.input_params else None
105
+ data["task_runs"] = [
106
+ _serialize_task_run(task_run)
107
+ for task_run in repository.get_task_runs(run_id)
108
+ ]
109
+ return data
110
+
111
+
112
+ @router.get("/{run_id}/logs")
113
+ def get_run_logs(run_id: int):
114
+ logs_file = get_logs_filename(run_id)
115
+ # errors=replace:历史遗留的非 utf-8 日志文件(如编码修复前 GBK 落盘的)
116
+ # 返回时坏字节替换为 U+FFFD,不因单个坏字节 500
117
+ content = (
118
+ logs_file.read_text(encoding="utf-8", errors="replace")
119
+ if logs_file.is_file()
120
+ else ""
121
+ )
122
+ return PlainTextResponse(content, media_type="text/plain")
123
+
124
+
125
+ @router.get("/{run_id}/data/{task_id}")
126
+ def get_task_data(run_id: int, task_id: str):
127
+ try:
128
+ data = read_task_data(run_id, task_id)
129
+ except ValueError:
130
+ raise HTTPException(
131
+ status_code=404, detail=f"运行 {run_id} 中不存在任务 {task_id}"
132
+ )
133
+
134
+ if data is None:
135
+ raise HTTPException(
136
+ status_code=404,
137
+ detail=f"运行 {run_id} 中任务 {task_id} 无输出数据",
138
+ )
139
+ return data
140
+
141
+
142
+ class RerunInput(BaseModel):
143
+ resume: bool = False
144
+ """true = 断点续跑(从原 run 首个失败任务起,复用上游输出);
145
+ false = 整条重跑。"""
146
+
147
+
148
+
149
+ @router.post("/{run_id}/rerun")
150
+ def rerun_run(run_id: int, body: RerunInput):
151
+ """重跑历史 run:复用原 run 的输入参数快照,reason=rerun 并记录来源。
152
+
153
+ 风险提示(前端确认弹窗同步展示):任务可能写库,重跑会按原参数
154
+ 再次执行写操作;断点续跑只适合任务间有上下游数据流的 pipeline。
155
+ """
156
+ source_run = repository.get_run(run_id)
157
+ if source_run is None:
158
+ raise HTTPException(status_code=404, detail=f"运行记录 {run_id} 不存在")
159
+
160
+ pipeline = orchestrator.get_pipeline(source_run.pipeline_id)
161
+ if pipeline is None:
162
+ raise HTTPException(
163
+ status_code=422,
164
+ detail=f"Pipeline {source_run.pipeline_id} 未注册(已被移除或服务重启后未加载),无法重跑",
165
+ )
166
+
167
+ # 输入参数快照复用(补数 run 也带 data_date 覆盖,一并还原)
168
+ params = json.loads(source_run.input_params) if source_run.input_params else None
169
+
170
+ resume_from: Optional[str] = None
171
+ if body.resume:
172
+ # 找原 run 首个非成功任务作为续跑起点(按 task_run 记录顺序)
173
+ task_runs = repository.get_task_runs(run_id)
174
+ first_failed = next(
175
+ (tr for tr in task_runs if tr.status != PipelineRunStatus.SUCCEEDED.value),
176
+ None,
177
+ )
178
+ if first_failed is None:
179
+ raise HTTPException(
180
+ status_code=422, detail="原运行没有失败任务,无需断点续跑"
181
+ )
182
+ if not any(task.id == first_failed.task_id for task in pipeline.tasks):
183
+ raise HTTPException(
184
+ status_code=422,
185
+ detail=f"任务 {first_failed.task_id} 已不在当前 pipeline 定义中,无法断点续跑",
186
+ )
187
+ resume_from = first_failed.task_id
188
+
189
+ try:
190
+ new_run = orchestrator.run_pipeline_now(
191
+ pipeline,
192
+ params=params,
193
+ reason="rerun",
194
+ source_run_id=source_run.id,
195
+ resume_from=resume_from,
196
+ )
197
+ except ValueError as exc:
198
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
199
+
200
+ return {"run_id": new_run.id, "resume_from": resume_from}
201
+
202
+
203
+ @router.post("/{run_id}/kill")
204
+ async def kill_run(run_id: int):
205
+ """停止正在执行的 run:向其协程投递 CancelledError。
206
+
207
+ - run 落 FAILED 终态(error 注明用户 kill),后续可走重跑/断点续跑;
208
+ - 取消在任务最近的 await 点生效,纯同步阻塞型任务会在执行完后才终止;
209
+ - run 必须处于 RUNNING 且在本进程执行队列中,否则 422。
210
+ """
211
+ run = repository.get_run(run_id)
212
+ if run is None:
213
+ raise HTTPException(status_code=404, detail=f"运行记录 {run_id} 不存在")
214
+
215
+ if run.status != PipelineRunStatus.RUNNING.value:
216
+ raise HTTPException(
217
+ status_code=422, detail="只有运行中(running)的运行才能停止"
218
+ )
219
+
220
+ if not orchestrator.cancel_run(run_id):
221
+ raise HTTPException(
222
+ status_code=422,
223
+ detail="该运行不在当前进程的执行队列中,无法停止"
224
+ "(可能为历史遗留状态,重启后会被崩溃恢复自动清理)",
225
+ )
226
+
227
+ return {"run_id": run_id, "killed": True}
@@ -0,0 +1,141 @@
1
+ """schedule_exceptions 路由:停机日历(节假日/临时停机)的增删改查。
2
+
3
+ 停机日只拦截定时触发(executor 拦截点记 SKIPPED + 原因),手动运行不受影响;
4
+ 生效范围可选:全部任务(scope=all)或指定任务(scope=selected + pipeline_ids)。
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ from datetime import date
10
+ from typing import List, Optional
11
+
12
+ from fastapi import APIRouter, HTTPException
13
+ from pydantic import BaseModel, Field
14
+
15
+ from flowdeck.database import repository
16
+
17
+ router = APIRouter(prefix="/schedule-exceptions", tags=["Schedule Exceptions"])
18
+
19
+ _logger = logging.getLogger(__name__)
20
+
21
+ MAX_REASON_LENGTH = 100
22
+
23
+
24
+ def _parse_date(value: str, field: str) -> date:
25
+ try:
26
+ return date.fromisoformat(str(value).strip())
27
+ except ValueError as exc:
28
+ raise HTTPException(
29
+ status_code=422, detail=f"{field} 格式无效 `{value}`,应为 YYYY-MM-DD"
30
+ ) from exc
31
+
32
+
33
+ def _validate(data: "ScheduleExceptionInput") -> None:
34
+ if data.scope not in ("all", "selected"):
35
+ raise HTTPException(status_code=422, detail="生效范围必须是 all 或 selected")
36
+ if data.scope == "selected" and not data.pipeline_ids:
37
+ raise HTTPException(
38
+ status_code=422, detail="生效范围为指定任务时,至少选择一个任务"
39
+ )
40
+ if len(data.reason) > MAX_REASON_LENGTH:
41
+ raise HTTPException(
42
+ status_code=422, detail=f"停机原因过长(最多 {MAX_REASON_LENGTH} 字)"
43
+ )
44
+
45
+
46
+ def _row_to_dict(row) -> dict:
47
+ return {
48
+ "id": row.id,
49
+ "start_date": row.start_date.strftime("%Y-%m-%d"),
50
+ "end_date": row.end_date.strftime("%Y-%m-%d"),
51
+ "reason": row.reason,
52
+ "scope": row.scope,
53
+ "pipeline_ids": json.loads(row.pipeline_ids) if row.pipeline_ids else [],
54
+ "created_at": row.created_at,
55
+ }
56
+
57
+
58
+ class ScheduleExceptionInput(BaseModel):
59
+ start_date: str
60
+ """生效起始日期(YYYY-MM-DD,含)"""
61
+ end_date: str
62
+ """生效结束日期(YYYY-MM-DD,含)"""
63
+ reason: str = Field(default="", max_length=MAX_REASON_LENGTH)
64
+ """停机原因(记入被跳过 run 的信息中)"""
65
+ scope: str = "all"
66
+ """all = 全部任务;selected = 仅 pipeline_ids 内的任务"""
67
+ pipeline_ids: Optional[List[str]] = None
68
+ """scope=selected 时生效的任务 id 列表"""
69
+
70
+
71
+ @router.get("")
72
+ def list_exceptions():
73
+ rows = repository.list_schedule_exceptions()
74
+ return {"items": [_row_to_dict(row) for row in rows]}
75
+
76
+
77
+ @router.post("")
78
+ def create_exception(data: ScheduleExceptionInput):
79
+ start = _parse_date(data.start_date, "start_date")
80
+ end = _parse_date(data.end_date, "end_date")
81
+ if end < start:
82
+ raise HTTPException(status_code=422, detail="end_date 不能早于 start_date")
83
+ _validate(data)
84
+
85
+ row = repository.create_schedule_exception(
86
+ {
87
+ "start_date": start,
88
+ "end_date": end,
89
+ "reason": data.reason.strip(),
90
+ "scope": data.scope,
91
+ "pipeline_ids": (
92
+ json.dumps(data.pipeline_ids, ensure_ascii=False)
93
+ if data.scope == "selected" and data.pipeline_ids
94
+ else None
95
+ ),
96
+ }
97
+ )
98
+ _logger.info(
99
+ "Schedule exception created: %s ~ %s scope=%s (%s)",
100
+ row.start_date,
101
+ row.end_date,
102
+ row.scope,
103
+ row.reason,
104
+ )
105
+ return _row_to_dict(row)
106
+
107
+
108
+ @router.put("/{exception_id}")
109
+ def update_exception(exception_id: int, data: ScheduleExceptionInput):
110
+ row = repository.get_schedule_exception(exception_id)
111
+ if row is None:
112
+ raise HTTPException(status_code=404, detail=f"停机日 {exception_id} 不存在")
113
+
114
+ start = _parse_date(data.start_date, "start_date")
115
+ end = _parse_date(data.end_date, "end_date")
116
+ if end < start:
117
+ raise HTTPException(status_code=422, detail="end_date 不能早于 start_date")
118
+ _validate(data)
119
+
120
+ row = repository.update_schedule_exception(
121
+ exception_id,
122
+ {
123
+ "start_date": start,
124
+ "end_date": end,
125
+ "reason": data.reason.strip(),
126
+ "scope": data.scope,
127
+ "pipeline_ids": (
128
+ json.dumps(data.pipeline_ids, ensure_ascii=False)
129
+ if data.scope == "selected" and data.pipeline_ids
130
+ else None
131
+ ),
132
+ },
133
+ )
134
+ return _row_to_dict(row)
135
+
136
+
137
+ @router.delete("/{exception_id}")
138
+ def delete_exception(exception_id: int):
139
+ if not repository.delete_schedule_exception(exception_id):
140
+ raise HTTPException(status_code=404, detail=f"停机日 {exception_id} 不存在")
141
+ return {"deleted": exception_id}