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,122 @@
1
+ """运行日志:get_logger 从 contextvars 取 pipeline/task/run,写 JSONL 文件并广播。"""
2
+
3
+ import logging
4
+
5
+ from flowdeck.logger.formatter import JsonFormatter
6
+ from flowdeck.logger.web_socket_handler import broadcast_handler
7
+ from flowdeck.pipeline.context import pipeline_context, run_context, task_context
8
+ from flowdeck.storage import get_logs_filename
9
+
10
+
11
+ def get_logger() -> logging.LoggerAdapter:
12
+ """获取当前 task / pipeline 的 logger。
13
+
14
+ 必须在任务函数内或运行 pipeline 的内部函数中调用(依赖 contextvars)。
15
+ 当 run / pipeline 上下文未设置(手动场景)时,退化为普通控制台
16
+ LoggerAdapter,不会崩溃。
17
+ """
18
+ pipeline = pipeline_context.get(None)
19
+ task = task_context.get(None)
20
+ pipeline_run = run_context.get(None)
21
+
22
+ if pipeline_run is None or pipeline is None:
23
+ return _get_fallback_logger(pipeline, task)
24
+
25
+ json_formatter = JsonFormatter(pipeline=pipeline.id, task=task.id if task else None)
26
+
27
+ # 每个 pipeline run(+task)一个唯一命名的 logger,
28
+ # 避免后续 run 复用同一 logger 导致日志文件句柄不更新
29
+ # (plombery issue #131 的同类处理)
30
+ logger_name = f"flowdeck.{pipeline_run.id}"
31
+
32
+ # pipeline 与 task 各自独立命名,不能是父子关系,否则会产生双份日志
33
+ if task:
34
+ logger_name += f"-{task.id}"
35
+
36
+ logger = logging.getLogger(logger_name)
37
+ logger.setLevel(logging.DEBUG)
38
+
39
+ # getLogger 会返回之前创建的同名 logger,避免重复挂载相同 handler
40
+ if not logger.handlers:
41
+ # encoding 必须显式 utf-8:Windows 默认 locale 编码(GBK)会把中文
42
+ # 日志写成 GBK 字节,API 端按 utf-8 读取即抛 UnicodeDecodeError(500)
43
+ json_handler = logging.FileHandler(
44
+ get_logs_filename(pipeline_run.id), encoding="utf-8"
45
+ )
46
+ json_handler.setFormatter(json_formatter)
47
+ logger.addHandler(json_handler)
48
+ logger.addHandler(broadcast_handler)
49
+
50
+ # 共享的广播 handler 使用无上下文的 formatter:
51
+ # pipeline/task/run_id 一律从 LogRecord(LoggerAdapter 的 extra)读取,
52
+ # 避免并发 run 之间互相覆盖 formatter
53
+ if broadcast_handler.formatter is None:
54
+ broadcast_handler.setFormatter(JsonFormatter())
55
+
56
+ extra_log_info = {
57
+ "pipeline": pipeline.id,
58
+ "run_id": pipeline_run.id,
59
+ "task": task.id if task else None,
60
+ }
61
+
62
+ return logging.LoggerAdapter(logger, extra_log_info)
63
+
64
+
65
+ def _get_fallback_logger(pipeline, task) -> logging.LoggerAdapter:
66
+ """无 run 上下文时的退化实现:普通控制台输出。"""
67
+ name = "flowdeck.manual"
68
+ if pipeline:
69
+ name += f".{pipeline.id}"
70
+ if task:
71
+ name += f".{task.id}"
72
+
73
+ logger = logging.getLogger(name)
74
+ logger.setLevel(logging.INFO)
75
+ logger.propagate = False
76
+
77
+ if not logger.handlers:
78
+ logger.addHandler(logging.StreamHandler())
79
+
80
+ return logging.LoggerAdapter(
81
+ logger,
82
+ {
83
+ "pipeline": pipeline.id if pipeline else None,
84
+ "run_id": None,
85
+ "task": task.id if task else None,
86
+ },
87
+ )
88
+
89
+
90
+ def close_logger(logger: logging.LoggerAdapter) -> None:
91
+ """关闭 logger 持有的资源与文件句柄(plombery issue #491 的同类处理)。
92
+
93
+ 共享的 broadcast_handler 只从当前 logger 移除、不关闭,
94
+ 以便后续 run 继续使用。
95
+ """
96
+ for handler in list(logger.logger.handlers):
97
+ logger.logger.removeHandler(handler)
98
+ if handler is not broadcast_handler:
99
+ handler.close()
100
+
101
+
102
+ def close_run_loggers(run_id: int) -> None:
103
+ """关闭本次 run 产生的全部 logger 的 handler(pipeline 级 + 各 task 级)。
104
+
105
+ 任务函数内调用 ``get_logger()`` 会按 ``flowdeck.{run_id}-{task_id}``
106
+ 再建独立 logger(各自持有 FileHandler),这些 handler 无人引用,
107
+ 必须按命名约定统一回收——否则每次 run 每个任务泄漏一个文件句柄,
108
+ Windows 下还会导致日志文件无法删除。
109
+ """
110
+ rid = str(run_id)
111
+ for name, item in list(logging.Logger.manager.loggerDict.items()):
112
+ if not isinstance(item, logging.Logger):
113
+ continue
114
+ if not name.startswith("flowdeck."):
115
+ continue
116
+ rest = name[len("flowdeck."):]
117
+ if rest != rid and not rest.startswith(rid + "-"):
118
+ continue
119
+ for handler in list(item.handlers):
120
+ item.removeHandler(handler)
121
+ if handler is not broadcast_handler:
122
+ handler.close()
@@ -0,0 +1,112 @@
1
+ """JSON 日志格式化器。
2
+
3
+ 与 plombery 的核心差异(根修其 UTC 缺陷):时间戳使用本地时间 +
4
+ 本地时区偏移(如 ``2026-10-15T12:00:00.123+08:00``),
5
+ 而非 plombery 的 UTC ``Z`` 后缀。
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ from datetime import datetime
11
+ from time import localtime
12
+ from typing import Any, Dict, Optional
13
+
14
+
15
+ DEFAULT_LOG_ATTRIBUTES = {
16
+ "level": "levelname",
17
+ "message": "message",
18
+ "loggerName": "name",
19
+ "timestamp": "asctime",
20
+ }
21
+
22
+
23
+ def _local_timezone_offset() -> str:
24
+ """本地时区偏移,格式 ±HH:MM(如 +08:00)。"""
25
+ offset = datetime.now().astimezone().strftime("%z") # 如 +0800
26
+ if len(offset) >= 5:
27
+ return f"{offset[:3]}:{offset[3:]}"
28
+ return "+00:00"
29
+
30
+
31
+ class JsonFormatter(logging.Formatter):
32
+ """输出 JSON 行日志。
33
+
34
+ @param pipeline: pipeline id(None 时从 LogRecord 的 extra 读取)
35
+ @param task: task id(None 时从 LogRecord 的 extra 读取)
36
+ @param fmt_dict: Key: logging 格式属性 pairs
37
+ @param time_format: time.strftime() 格式串,默认 "%Y-%m-%dT%H:%M:%S"
38
+ @param msec_format: 毫秒后缀格式串,默认为 ".%03d{本地时区偏移}"
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ pipeline: Optional[str] = None,
44
+ task: Optional[str] = None,
45
+ fmt_dict: Optional[Dict[str, str]] = None,
46
+ time_format: str = "%Y-%m-%dT%H:%M:%S",
47
+ msec_format: Optional[str] = None,
48
+ ):
49
+ self.pipeline = pipeline
50
+ self.task = task
51
+ self.fmt_dict = fmt_dict if fmt_dict is not None else DEFAULT_LOG_ATTRIBUTES
52
+ self.default_time_format = time_format
53
+ # 毫秒后缀使用本地时区偏移(如 .123+08:00),而非 UTC 的 Z
54
+ self.default_msec_format = (
55
+ msec_format
56
+ if msec_format is not None
57
+ else f"%s.%03d{_local_timezone_offset()}"
58
+ )
59
+ self.datefmt = None
60
+ # 使用本地时间(plombery 用 gmtime 存 UTC)
61
+ self.converter = localtime
62
+
63
+ def usesTime(self) -> bool:
64
+ """Overwritten to look for the attribute in the format dict values
65
+ instead of the fmt string.
66
+ """
67
+ return "asctime" in self.fmt_dict.values()
68
+
69
+ def formatMessage(self, record) -> Dict[str, Any]:
70
+ """Overwritten to return a dictionary of the relevant LogRecord attributes
71
+ instead of a string.
72
+ """
73
+ msg = {
74
+ fmt_key: record.__dict__[fmt_val]
75
+ for fmt_key, fmt_val in self.fmt_dict.items()
76
+ }
77
+ msg["pipeline"] = (
78
+ self.pipeline
79
+ if self.pipeline is not None
80
+ else getattr(record, "pipeline", None)
81
+ )
82
+ msg["task"] = (
83
+ self.task if self.task is not None else getattr(record, "task", None)
84
+ )
85
+ msg["run_id"] = getattr(record, "run_id", None)
86
+
87
+ return msg
88
+
89
+ def format(self, record) -> str:
90
+ """Mostly the same as the parent's class method, the difference being
91
+ that a dict is manipulated and dumped as JSON instead of a string.
92
+ """
93
+ record.message = record.getMessage()
94
+
95
+ if self.usesTime():
96
+ record.asctime = self.formatTime(record, self.datefmt)
97
+
98
+ message_dict = self.formatMessage(record)
99
+
100
+ if record.exc_info:
101
+ # Cache the traceback text to avoid converting it multiple times
102
+ # (it's constant anyway)
103
+ if not record.exc_text:
104
+ record.exc_text = self.formatException(record.exc_info)
105
+
106
+ if record.exc_text:
107
+ message_dict["exc_info"] = record.exc_text
108
+
109
+ if record.stack_info:
110
+ message_dict["stack_info"] = self.formatStack(record.stack_info)
111
+
112
+ return json.dumps(message_dict, default=str, ensure_ascii=False)
@@ -0,0 +1,85 @@
1
+ """WebSocket 日志广播(不依赖 fastapi,纯 asyncio / 线程安全)。
2
+
3
+ logging 侧通过模块级单例 ``broadcast_handler`` 输出日志行;
4
+ API 层(异步 websocket 端点内)调用 ``broadcaster.register(ws)`` /
5
+ ``broadcaster.unregister(ws)`` 接入真实连接。
6
+
7
+ 相当于 plombery 的队列广播模式:emit 通过 ``run_coroutine_threadsafe``
8
+ 把发送任务调度到目标连接所在的事件循环,本身不阻塞 logging 调用方。
9
+ """
10
+
11
+ import asyncio
12
+ import logging
13
+ import threading
14
+ from typing import Any, List, Optional, Tuple
15
+
16
+
17
+ class Broadcaster:
18
+ """线程安全的 WebSocket 连接注册器 + 日志行广播器。
19
+
20
+ ws 类型为 Any(运行时为 fastapi/starlette WebSocket,
21
+ 只要求实现 ``send_text(str)`` 协程)。
22
+ """
23
+
24
+ def __init__(self) -> None:
25
+ self._clients: List[Tuple[Any, asyncio.AbstractEventLoop]] = []
26
+ self._lock = threading.Lock()
27
+
28
+ def register(self, ws: Any) -> None:
29
+ """注册一个 WebSocket 连接(应在其事件循环内调用)。"""
30
+ try:
31
+ loop: Optional[asyncio.AbstractEventLoop] = asyncio.get_running_loop()
32
+ except RuntimeError:
33
+ loop = None
34
+
35
+ with self._lock:
36
+ if all(client is not ws for client, _ in self._clients):
37
+ self._clients.append((ws, loop))
38
+
39
+ def unregister(self, ws: Any) -> None:
40
+ with self._lock:
41
+ self._clients = [
42
+ (client, loop)
43
+ for client, loop in self._clients
44
+ if client is not ws
45
+ ]
46
+
47
+ def broadcast(self, line: str) -> None:
48
+ """把一行日志广播给所有已注册连接(线程安全、非阻塞)。"""
49
+ with self._lock:
50
+ clients = list(self._clients)
51
+
52
+ for ws, loop in clients:
53
+ self._send(ws, loop, line)
54
+
55
+ def _send(
56
+ self,
57
+ ws: Any,
58
+ loop: Optional[asyncio.AbstractEventLoop],
59
+ line: str,
60
+ ) -> None:
61
+ if loop is None or not loop.is_running():
62
+ return
63
+
64
+ try:
65
+ future = asyncio.run_coroutine_threadsafe(ws.send_text(line), loop)
66
+ # 消费可能的异常,避免未处理的 Future 告警
67
+ future.add_done_callback(lambda f: f.cancelled() or f.exception())
68
+ except Exception:
69
+ self.unregister(ws)
70
+
71
+
72
+ broadcaster = Broadcaster()
73
+
74
+
75
+ class WebSocketBroadcastHandler(logging.Handler):
76
+ """把格式化后的日志行广播到所有已注册的 WebSocket。"""
77
+
78
+ def emit(self, record: logging.LogRecord) -> None:
79
+ try:
80
+ broadcaster.broadcast(self.format(record))
81
+ except Exception:
82
+ self.handleError(record)
83
+
84
+
85
+ broadcast_handler = WebSocketBroadcastHandler()
@@ -0,0 +1,13 @@
1
+ from .engine import RuleManager, notification_manager, run_missed_patrol
2
+ from .rules import NotificationRuleSchema
3
+
4
+ # plombery 兼容别名
5
+ NotificationRule = NotificationRuleSchema
6
+
7
+ __all__ = [
8
+ "NotificationRule",
9
+ "NotificationRuleSchema",
10
+ "RuleManager",
11
+ "notification_manager",
12
+ "run_missed_patrol",
13
+ ]
@@ -0,0 +1,79 @@
1
+ """SMTP 邮件发送器(简版邮件通知渠道)。
2
+
3
+ 配置门控:以 ``repository.get_smtp_config()`` 为总开关——设置页未配置或未
4
+ 启用 SMTP 时,本模块对 engine 而言不可达(email 规则被跳过仅记 warning),
5
+ 对运行中的 pipeline 没有任何影响。
6
+
7
+ 实现约束:
8
+ - 只用标准库 ``smtplib``,不引入新依赖;
9
+ - 同步发送放到线程池(``asyncio.to_thread``),不阻塞事件循环;
10
+ - 沿用通知引擎的 fire-and-forget 约定:任何失败只记 warning。
11
+
12
+ 安全说明:连接方式由 ``security`` 决定——``ssl``(465 常用,SMTP_SSL)、
13
+ ``starttls``(587 常用,明文连接后升级 TLS)、``none``(不加密,仅内网
14
+ 调试用)。
15
+ """
16
+
17
+ import asyncio
18
+ import logging
19
+ import smtplib
20
+ from email.header import Header
21
+ from email.mime.text import MIMEText
22
+ from email.utils import formataddr
23
+
24
+ _logger = logging.getLogger(__name__)
25
+
26
+
27
+ def _send_sync(cfg: dict, recipients: list, subject: str, body: str) -> None:
28
+ """同步 SMTP 发送;任何异常向上抛出,由调用方决定处理方式。
29
+
30
+ 正文按 HTML 发送:通知内容里的运行详情链接需要可点击(未配置站点
31
+ 基地址时模板给出相对路径并显式提示,不会渲染成错误链接)。
32
+ """
33
+ msg = MIMEText(body, "html", "utf-8")
34
+ msg["Subject"] = Header(subject, "utf-8")
35
+ from_addr = cfg["from_addr"]
36
+ msg["From"] = formataddr((str(Header("FlowDeck", "utf-8")), from_addr))
37
+ msg["To"] = ", ".join(recipients)
38
+
39
+ security = (cfg.get("security") or "ssl").lower()
40
+ port = int(cfg.get("port") or (465 if security == "ssl" else 25))
41
+
42
+ if security == "ssl":
43
+ server = smtplib.SMTP_SSL(cfg["host"], port, timeout=15)
44
+ else:
45
+ server = smtplib.SMTP(cfg["host"], port, timeout=15)
46
+ try:
47
+ if security == "starttls":
48
+ server.starttls()
49
+ username = cfg.get("username") or from_addr
50
+ password = cfg.get("password") or ""
51
+ if password and server.has_extn("auth"):
52
+ server.login(username, password)
53
+ # 服务器未宣告 AUTH 扩展时跳过登录(内网中转/免认证服务器)
54
+ server.sendmail(from_addr, recipients, msg.as_string())
55
+ finally:
56
+ try:
57
+ server.quit()
58
+ except Exception:
59
+ pass
60
+
61
+
62
+ async def send_email(
63
+ cfg: dict, recipients: list, subject: str, body: str
64
+ ) -> None:
65
+ """异步发送邮件(线程池执行同步 SMTP);失败只记 warning 不外抛。"""
66
+ try:
67
+ await asyncio.to_thread(_send_sync, cfg, recipients, subject, body)
68
+ except Exception:
69
+ _logger.warning(
70
+ "Failed to send notification email to %s", recipients, exc_info=True
71
+ )
72
+
73
+
74
+ def send_email_sync(cfg: dict, recipients: list, subject: str, body: str) -> None:
75
+ """同步发送(设置页「发送测试邮件」等线程池上下文直接调用)。
76
+
77
+ 异常向上抛出,由调用方转成用户可见的错误提示。
78
+ """
79
+ _send_sync(cfg, recipients, subject, body)