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,478 @@
1
+ """任务结果直发通知(企业微信机器人)。
2
+
3
+ 任务执行成功后,按任务自身的通知配置把执行结果渲染成企微消息直接投递,
4
+ 免去「只想把查询结果发出来」还要另建通知规则、单独写发消息逻辑的麻烦。
5
+
6
+ - 消息格式:auto = SQL / 存储过程走 markdown,Python 结构化结果(list /
7
+ dict / set / tuple)走 markdown,其余走 text;也可强制 markdown / text;
8
+ - 空结果策略:ignore = 不发送;warn = 发送「执行结果为空」告警;
9
+ - 正文可在界面编辑(``${占位符}``),模板未包含 ``${result}`` 时自动追加结果块;
10
+ - 投递 fire-and-forget,任何失败只记 warning,绝不影响任务本身。
11
+ """
12
+
13
+ import logging
14
+ import re
15
+ from datetime import datetime
16
+ from types import SimpleNamespace
17
+ from typing import Any, Dict, List, Optional, Tuple
18
+
19
+ _logger = logging.getLogger(__name__)
20
+
21
+ # 企微机器人正文上限:markdown 4096 字节、text 2048 字节,留一点余量
22
+ MAX_MARKDOWN_BYTES = 4000
23
+ MAX_TEXT_BYTES = 1900
24
+ # 单个单元格 / 标量的展示长度,避免一行把消息撑爆
25
+ MAX_CELL_CHARS = 80
26
+
27
+ STRUCTURED_TYPES = (list, tuple, dict, set, frozenset)
28
+
29
+ _TASK_TYPE_LABELS = {
30
+ "sql": "SQL 脚本",
31
+ "procedure": "存储过程",
32
+ "python": "Python 脚本",
33
+ "http": "HTTP 请求",
34
+ }
35
+
36
+ # 内置标准版式:用户留空 notify_template 时使用
37
+ DEFAULT_TEMPLATES = {
38
+ "markdown": (
39
+ "**任务执行结果**\n"
40
+ "> 任务:${task_name}(${task_id})\n"
41
+ "> 类型:${task_type}\n"
42
+ "> 状态:${status}\n"
43
+ "> 时间:${time}\n"
44
+ "> 耗时:${duration}\n\n"
45
+ "${result}"
46
+ ),
47
+ "text": (
48
+ "【任务执行结果】${task_name}(${task_id})\n"
49
+ "类型:${task_type}\n"
50
+ "状态:${status}\n"
51
+ "时间:${time}\n"
52
+ "耗时:${duration}\n\n"
53
+ "${result}"
54
+ ),
55
+ }
56
+
57
+ _PLACEHOLDER_RE = re.compile(r"\$\{(\w+)\}")
58
+
59
+ # 测试消息用的样例结果
60
+ _SAMPLE_RESULTS: Dict[str, Any] = {
61
+ "sql": {
62
+ "rowcount": 2,
63
+ "result_sets": [
64
+ {
65
+ "columns": ["id", "name", "amount"],
66
+ "rows": [[1, "张三", 128.5], [2, "李四", 96.0]],
67
+ }
68
+ ],
69
+ },
70
+ "procedure": {
71
+ "rowcount": 0,
72
+ "result": 0,
73
+ "procedure_output": [
74
+ {
75
+ "columns": ["项目", "值"],
76
+ "rows": [["执行状态", "成功"], ["写入行数", "128"]],
77
+ }
78
+ ],
79
+ },
80
+ "python": {
81
+ "result": [{"id": 1, "name": "张三"}, {"id": 2, "name": "李四"}],
82
+ "logs": [],
83
+ },
84
+ }
85
+
86
+
87
+ def _flatten(value: Any, limit: int = MAX_CELL_CHARS) -> str:
88
+ """把任意值压成单行短文本(None 显示 NULL,超长截断)。"""
89
+ text = "NULL" if value is None else str(value)
90
+ text = " ".join(text.split())
91
+ if len(text) > limit:
92
+ text = text[: limit - 1] + "…"
93
+ return text
94
+
95
+
96
+ def _truncate_bytes(text: str, limit: int) -> str:
97
+ if len(text.encode("utf-8")) <= limit:
98
+ return text
99
+ suffix = "\n…(内容过长已截断)"
100
+ budget = max(limit - len(suffix.encode("utf-8")), 0)
101
+ return text.encode("utf-8")[:budget].decode("utf-8", "ignore") + suffix
102
+
103
+
104
+ def _python_payload(result: Any) -> Tuple[Any, List[Any]]:
105
+ """Python 任务结果是 ``{"result": ..., "logs": [...]}``,取出真正的脚本结果。"""
106
+ if isinstance(result, dict) and "result" in result and "logs" in result:
107
+ return result.get("result"), result.get("logs") or []
108
+ return result, []
109
+
110
+
111
+ def _sql_result_sets(result: Dict[str, Any]) -> List[Dict[str, Any]]:
112
+ """存储过程输出结果集优先,其次普通 SQL 的结果集。"""
113
+ return list(result.get("procedure_output") or result.get("result_sets") or [])
114
+
115
+
116
+ def is_empty_result(task_type: str, result: Any) -> bool:
117
+ """判断本次执行结果是否为空。
118
+
119
+ - SQL:有结果集时,所有结果集都没有行才算空;无结果集(DML)时
120
+ rowcount 为 0 算空;
121
+ - 存储过程:有输出结果集按结果集判断,否则返回值为 None/0 算空;
122
+ - Python:未返回(None)或返回空容器 / 空字符串算空。
123
+ """
124
+ task_type = (task_type or "").lower()
125
+ if task_type in ("sql", "procedure"):
126
+ if not isinstance(result, dict):
127
+ return result is None
128
+ sets = _sql_result_sets(result)
129
+ if sets:
130
+ return all(not (item.get("rows") or []) for item in sets)
131
+ if task_type == "procedure":
132
+ return result.get("result") in (None, 0, "")
133
+ return not result.get("rowcount")
134
+ payload, _ = _python_payload(result)
135
+ if payload is None:
136
+ return True
137
+ if isinstance(payload, (str, bytes, list, tuple, dict, set, frozenset)):
138
+ return len(payload) == 0
139
+ return False
140
+
141
+
142
+ def resolve_format(task_type: str, result: Any, preferred: str = "auto") -> str:
143
+ """决定消息格式:显式 markdown/text 优先,auto 按任务类型与结果结构推断。"""
144
+ preferred = (preferred or "auto").lower()
145
+ if preferred in ("markdown", "text"):
146
+ return preferred
147
+ if (task_type or "").lower() in ("sql", "procedure"):
148
+ return "markdown"
149
+ payload, _ = _python_payload(result)
150
+ return "markdown" if isinstance(payload, STRUCTURED_TYPES) else "text"
151
+
152
+
153
+ def _block(markdown: bool, title: str, lines: List[str]) -> str:
154
+ if markdown:
155
+ body = "\n".join(f"> {line}" for line in lines)
156
+ return f"**{title}**\n{body}"
157
+ return "\n".join([title, *lines])
158
+
159
+
160
+ def _format_row(columns: List[str], row: Any) -> str:
161
+ if isinstance(row, (list, tuple)):
162
+ if columns:
163
+ pairs = []
164
+ for index, value in enumerate(row):
165
+ name = columns[index] if index < len(columns) else f"col{index + 1}"
166
+ pairs.append(f"{name}={_flatten(value)}")
167
+ return ",".join(pairs)
168
+ return ",".join(_flatten(value) for value in row)
169
+ return _flatten(row)
170
+
171
+
172
+ def _render_sql(markdown: bool, result: Dict[str, Any]) -> str:
173
+ sets = _sql_result_sets(result)
174
+ if not sets:
175
+ lines = [f"影响行数:{result.get('rowcount') or 0}"]
176
+ if result.get("result") is not None:
177
+ lines.append(f"返回值:{_flatten(result.get('result'))}")
178
+ return _block(markdown, "执行完成", lines)
179
+
180
+ blocks = []
181
+ for index, item in enumerate(sets, 1):
182
+ rows = item.get("rows") or []
183
+ columns = item.get("columns") or []
184
+ title = "查询结果" if len(sets) == 1 else f"结果集 {index}"
185
+ lines = [
186
+ f"{no}. {_format_row(columns, row)}" for no, row in enumerate(rows, 1)
187
+ ] or ["(无数据)"]
188
+ blocks.append(_block(markdown, f"{title}({len(rows)} 行)", lines))
189
+ return "\n".join(blocks)
190
+
191
+
192
+ def _render_python(markdown: bool, value: Any) -> str:
193
+ if isinstance(value, dict):
194
+ lines = [
195
+ f"{_flatten(key)}:{_flatten(item, 200)}" for key, item in value.items()
196
+ ]
197
+ return _block(markdown, f"脚本结果({len(value)} 个字段)", lines or ["(无数据)"])
198
+ if isinstance(value, (list, tuple)):
199
+ lines = []
200
+ for index, item in enumerate(value, 1):
201
+ if isinstance(item, dict):
202
+ pairs = ",".join(
203
+ f"{_flatten(key)}={_flatten(val)}" for key, val in item.items()
204
+ )
205
+ lines.append(f"{index}. {pairs}")
206
+ else:
207
+ lines.append(f"{index}. {_flatten(item, 200)}")
208
+ return _block(markdown, f"脚本结果({len(value)} 项)", lines or ["(无数据)"])
209
+ if isinstance(value, (set, frozenset)):
210
+ items = sorted(value, key=str)
211
+ lines = [f"{no}. {_flatten(item, 200)}" for no, item in enumerate(items, 1)]
212
+ return _block(markdown, f"脚本结果({len(value)} 项)", lines or ["(无数据)"])
213
+ return _block(markdown, "脚本结果", [_flatten(value, 500)])
214
+
215
+
216
+ def _render_result(task_type: str, result: Any, markdown: bool) -> str:
217
+ if (task_type or "").lower() in ("sql", "procedure"):
218
+ data = result if isinstance(result, dict) else {"result": result}
219
+ return _render_sql(markdown, data)
220
+ payload, _ = _python_payload(result)
221
+ return _render_python(markdown, payload)
222
+
223
+
224
+ def _empty_block(markdown: bool) -> str:
225
+ if markdown:
226
+ return "**⚠️ 执行结果为空**\n> 本次执行没有返回任何数据"
227
+ return "⚠️ 执行结果为空:本次执行没有返回任何数据"
228
+
229
+
230
+ def _image_note(markdown: bool, total_rows: int) -> str:
231
+ text = f"明细见上方图片(共 {total_rows} 行)"
232
+ return f"> {text}" if markdown else text
233
+
234
+
235
+ def _image_enabled(row: Any) -> bool:
236
+ """图片开关默认开启:历史行该列为 NULL 时按开启处理。"""
237
+ value = getattr(row, "notify_image_enabled", True)
238
+ return True if value is None else bool(value)
239
+
240
+
241
+ def _table_sets(task_type: str, result: Any) -> List[Dict[str, Any]]:
242
+ """取有数据的表格结果集(图片只画内容,不带标题)。"""
243
+ if task_type not in ("sql", "procedure") or not isinstance(result, dict):
244
+ return []
245
+ return [
246
+ {"columns": item.get("columns") or [], "rows": item["rows"]}
247
+ for item in _sql_result_sets(result)
248
+ if item.get("rows")
249
+ ]
250
+
251
+
252
+ def _template_values(
253
+ row: Any, result: Any, started_at: Optional[datetime], run_id: Optional[str]
254
+ ) -> Dict[str, Any]:
255
+ now = datetime.now()
256
+ start = started_at or now
257
+ duration = max((now - start).total_seconds(), 0.0)
258
+ payload, logs = _python_payload(result)
259
+
260
+ rowcount: Any = ""
261
+ if (getattr(row, "task_type", "") or "").lower() in ("sql", "procedure"):
262
+ if isinstance(result, dict):
263
+ sets = _sql_result_sets(result)
264
+ # 有结果集时行数取实际返回行数(SELECT 的 rowcount 恒为 0)
265
+ rowcount = (
266
+ sum(len(item.get("rows") or []) for item in sets)
267
+ if sets
268
+ else result.get("rowcount") or 0
269
+ )
270
+ elif isinstance(payload, (list, tuple, dict, set, frozenset)):
271
+ rowcount = len(payload)
272
+ elif payload is not None:
273
+ rowcount = 1
274
+
275
+ return {
276
+ "task_id": getattr(row, "id", ""),
277
+ "task_name": getattr(row, "name", ""),
278
+ "task_type": _TASK_TYPE_LABELS.get(
279
+ (getattr(row, "task_type", "") or "").lower(), getattr(row, "task_type", "")
280
+ ),
281
+ "status": "成功",
282
+ "time": start.strftime("%Y-%m-%d %H:%M:%S"),
283
+ "duration": f"{duration:.1f}s",
284
+ "rowcount": rowcount,
285
+ "run_id": run_id or "",
286
+ "logs": "\n".join(str(line) for line in logs[-20:]),
287
+ }
288
+
289
+
290
+ def render_message(template: str, values: Dict[str, Any], result_block: str) -> str:
291
+ """替换 ``${xxx}`` 占位符;模板没有 ``${result}`` 时把结果块追加到末尾。"""
292
+ has_result_slot = "${result}" in template
293
+ content = _PLACEHOLDER_RE.sub(
294
+ lambda match: (
295
+ result_block
296
+ if match.group(1) == "result"
297
+ else str(values.get(match.group(1), match.group(0)))
298
+ ),
299
+ template,
300
+ ).strip()
301
+ if not has_result_slot:
302
+ content = f"{content}\n\n{result_block}" if content else result_block
303
+ return content
304
+
305
+
306
+ def build_payload(
307
+ row: Any,
308
+ result: Any,
309
+ started_at: Optional[datetime] = None,
310
+ run_id: Optional[str] = None,
311
+ include_detail: bool = True,
312
+ ) -> Optional[Dict[str, Any]]:
313
+ """按任务配置生成文字消息体;空结果且策略为 ignore 时返回 None。
314
+
315
+ ``include_detail=False``:明细由图片承载,正文只留标题与「明细见图片」。
316
+ """
317
+ task_type = (getattr(row, "task_type", "") or "sql").lower()
318
+ empty = is_empty_result(task_type, result)
319
+ policy = (getattr(row, "notify_empty_policy", None) or "ignore").lower()
320
+ if empty and policy != "warn":
321
+ return None
322
+
323
+ fmt = resolve_format(task_type, result, getattr(row, "notify_format", None) or "auto")
324
+ markdown = fmt == "markdown"
325
+ if empty:
326
+ block = _empty_block(markdown)
327
+ elif include_detail:
328
+ block = _render_result(task_type, result, markdown)
329
+ else:
330
+ total_rows = sum(len(item.get("rows") or []) for item in _table_sets(task_type, result))
331
+ block = _image_note(markdown, total_rows)
332
+
333
+ template = (getattr(row, "notify_template", None) or "").strip()
334
+ if not template:
335
+ template = DEFAULT_TEMPLATES[fmt]
336
+ content = render_message(
337
+ template, _template_values(row, result, started_at, run_id), block
338
+ )
339
+ content = _truncate_bytes(
340
+ content, MAX_MARKDOWN_BYTES if markdown else MAX_TEXT_BYTES
341
+ )
342
+
343
+ if markdown:
344
+ return {"msgtype": "markdown", "markdown": {"content": content}}
345
+ return {"msgtype": "text", "text": {"content": content}}
346
+
347
+
348
+ def build_payloads(
349
+ row: Any,
350
+ result: Any,
351
+ started_at: Optional[datetime] = None,
352
+ run_id: Optional[str] = None,
353
+ ) -> List[Dict[str, Any]]:
354
+ """本次结果要发的所有消息:表格类结果先生成图片,正文说明明细见图片。
355
+
356
+ 图片渲染失败(无 Pillow / 无中文字体 / 超过 2MB)时自动退回纯文字,
357
+ 保证通知本身不会因为图片能力缺失而丢失。
358
+ """
359
+ task_type = (getattr(row, "task_type", "") or "sql").lower()
360
+ empty = is_empty_result(task_type, result)
361
+ if empty:
362
+ payload = build_payload(row, result, started_at, run_id)
363
+ return [payload] if payload else []
364
+
365
+ text_payload = build_payload(row, result, started_at, run_id, include_detail=False)
366
+ sets = _table_sets(task_type, result)
367
+ if _image_enabled(row) and sets:
368
+ try:
369
+ from flowdeck.notifications.table_image import (
370
+ build_image_payload,
371
+ render_table_image,
372
+ )
373
+
374
+ image_bytes = render_table_image(sets)
375
+ if image_bytes:
376
+ return [build_image_payload(image_bytes), text_payload]
377
+ except Exception:
378
+ _logger.warning("结果表格转图片失败,改发文字明细", exc_info=True)
379
+
380
+ # 图片不可用:正文补回完整明细
381
+ payload = build_payload(row, result, started_at, run_id)
382
+ return [payload] if payload else []
383
+
384
+
385
+ def notify_task_result(
386
+ pipeline_id: str,
387
+ task_id: str,
388
+ result: Any,
389
+ started_at: Optional[datetime] = None,
390
+ run_id: Optional[str] = None,
391
+ ) -> None:
392
+ """任务成功后按任务配置直发企微;任何异常只记 warning,不影响任务。"""
393
+ try:
394
+ from flowdeck.database import repository
395
+
396
+ row = repository.get_ui_pipeline(pipeline_id)
397
+ if row is None or not bool(getattr(row, "notify_enabled", False)):
398
+ return
399
+
400
+ webhook = (getattr(row, "notify_webhook", "") or "").strip()
401
+ if not webhook:
402
+ _logger.warning(
403
+ "任务 %s 已启用结果通知但未配置 webhook,已跳过发送", task_id
404
+ )
405
+ return
406
+
407
+ payloads = build_payloads(row, result, started_at, run_id)
408
+ if not payloads:
409
+ return
410
+
411
+ from flowdeck.notifications.engine import send_webhooks
412
+
413
+ send_webhooks(webhook, payloads)
414
+ except Exception:
415
+ _logger.warning("任务结果通知失败(task=%s)", task_id, exc_info=True)
416
+
417
+
418
+ def build_test_payloads(
419
+ *,
420
+ task_type: str,
421
+ task_name: str = "",
422
+ task_id: str = "",
423
+ notify_format: str = "auto",
424
+ template: Optional[str] = None,
425
+ empty_policy: str = "ignore",
426
+ image_enabled: bool = True,
427
+ ) -> List[Dict[str, Any]]:
428
+ """用样例结果渲染测试消息(不落库),与正式执行共用同一套渲染逻辑。"""
429
+ task_type = (task_type or "sql").lower()
430
+ row = SimpleNamespace(
431
+ id=task_id or "demo_task",
432
+ name=task_name or "测试任务",
433
+ task_type=task_type,
434
+ notify_format=notify_format or "auto",
435
+ notify_template=template,
436
+ notify_empty_policy=empty_policy or "ignore",
437
+ notify_image_enabled=image_enabled,
438
+ )
439
+ payloads = build_payloads(
440
+ row, _SAMPLE_RESULTS.get(task_type, _SAMPLE_RESULTS["sql"]), datetime.now()
441
+ )
442
+ if not payloads:
443
+ payloads = [
444
+ {
445
+ "msgtype": "text",
446
+ "text": {
447
+ "content": "测试消息:样例结果为空且策略为忽略,正式执行时不会发送。"
448
+ },
449
+ }
450
+ ]
451
+ return payloads
452
+
453
+
454
+ async def send_test(webhook: str, payload: Dict[str, Any]) -> Dict[str, Any]:
455
+ """同步等待一次投递,供界面「发送测试消息」使用;返回 ok/error。"""
456
+ import httpx
457
+
458
+ try:
459
+ async with httpx.AsyncClient() as client:
460
+ response = await client.post(webhook, json=payload, timeout=10)
461
+ except Exception as exc: # noqa: BLE001 - 需要把错误原样回给界面
462
+ return {"ok": False, "error": str(exc)}
463
+
464
+ if response.status_code >= 300:
465
+ return {
466
+ "ok": False,
467
+ "error": f"HTTP {response.status_code}: {response.text[:200]}",
468
+ }
469
+
470
+ try:
471
+ data = response.json()
472
+ except ValueError:
473
+ return {"ok": True, "error": None}
474
+
475
+ errcode = data.get("errcode")
476
+ if errcode not in (None, 0):
477
+ return {"ok": False, "error": f"errcode={errcode} {data.get('errmsg', '')}"}
478
+ return {"ok": True, "error": None}