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.
- flowdeck/__init__.py +65 -0
- flowdeck/_version.py +1 -0
- flowdeck/api/__init__.py +216 -0
- flowdeck/api/routers/__init__.py +1 -0
- flowdeck/api/routers/dashboard.py +73 -0
- flowdeck/api/routers/health.py +26 -0
- flowdeck/api/routers/notifications.py +92 -0
- flowdeck/api/routers/pipelines.py +274 -0
- flowdeck/api/routers/runs.py +227 -0
- flowdeck/api/routers/schedule_exceptions.py +141 -0
- flowdeck/api/routers/system.py +386 -0
- flowdeck/api/routers/ui_pipelines.py +507 -0
- flowdeck/api/routers/ui_task_tools.py +275 -0
- flowdeck/api/routers/webhooks.py +115 -0
- flowdeck/auth/__init__.py +0 -0
- flowdeck/auth/basic.py +65 -0
- flowdeck/cli.py +40 -0
- flowdeck/config.py +240 -0
- flowdeck/database/__init__.py +0 -0
- flowdeck/database/base.py +91 -0
- flowdeck/database/models.py +218 -0
- flowdeck/database/repository.py +1231 -0
- flowdeck/logger/__init__.py +122 -0
- flowdeck/logger/formatter.py +112 -0
- flowdeck/logger/web_socket_handler.py +85 -0
- flowdeck/notifications/__init__.py +13 -0
- flowdeck/notifications/email_sender.py +79 -0
- flowdeck/notifications/engine.py +412 -0
- flowdeck/notifications/rules.py +22 -0
- flowdeck/notifications/table_image.py +273 -0
- flowdeck/notifications/task_result.py +478 -0
- flowdeck/notifications/templates.py +224 -0
- flowdeck/orchestrator/__init__.py +380 -0
- flowdeck/orchestrator/executor.py +661 -0
- flowdeck/pipeline/__init__.py +5 -0
- flowdeck/pipeline/_utils.py +11 -0
- flowdeck/pipeline/context.py +13 -0
- flowdeck/pipeline/pipeline.py +40 -0
- flowdeck/pipeline/schedule.py +125 -0
- flowdeck/pipeline/task.py +104 -0
- flowdeck/pipeline/trigger.py +22 -0
- flowdeck/schemas.py +11 -0
- flowdeck/static/assets/BackfillModal-BViyo-00.js +1 -0
- flowdeck/static/assets/BackfillModal-D6je7CRx.css +1 -0
- flowdeck/static/assets/Btn-B77BQZvQ.js +1 -0
- flowdeck/static/assets/Btn-D6G_tsbF.css +1 -0
- flowdeck/static/assets/DashboardView-BM-S5j64.js +1 -0
- flowdeck/static/assets/DashboardView-CBu0kYw6.css +1 -0
- flowdeck/static/assets/DatePickerField-IOKwxOwp.js +830 -0
- flowdeck/static/assets/Empty-B5kRTX_h.css +1 -0
- flowdeck/static/assets/Empty-ScitfHnD.js +1 -0
- flowdeck/static/assets/Modal-7xA4aZKG.js +1 -0
- flowdeck/static/assets/Modal-BNFhtIvK.css +1 -0
- flowdeck/static/assets/NotificationsView-BTkWFeLt.css +1 -0
- flowdeck/static/assets/NotificationsView-BkofWdjj.js +1 -0
- flowdeck/static/assets/NotifySettings-BFdtzy6K.js +1 -0
- flowdeck/static/assets/NotifySettings-D9Nn2RLl.css +1 -0
- flowdeck/static/assets/NumInput--MSEekvd.js +582 -0
- flowdeck/static/assets/NumInput-DfqPA-uG.css +1 -0
- flowdeck/static/assets/PageHeader-3D30Zbvm.js +1 -0
- flowdeck/static/assets/PageHeader-BULVGwbD.css +1 -0
- flowdeck/static/assets/PipelineDetailView-89815vAO.js +1 -0
- flowdeck/static/assets/PipelineDetailView-B_iVBCYT.css +1 -0
- flowdeck/static/assets/PipelinesView-CtDub3qu.js +1 -0
- flowdeck/static/assets/PipelinesView-DC9QO4Wr.css +1 -0
- flowdeck/static/assets/PrettyJson-DjAv38hk.css +1 -0
- flowdeck/static/assets/PrettyJson-_gjY71Cb.js +1 -0
- flowdeck/static/assets/RecentFailuresView-CruW_Dj8.js +1 -0
- flowdeck/static/assets/RecentFailuresView-DjQsiRv9.css +1 -0
- flowdeck/static/assets/RunDetailView--NojY8JX.css +1 -0
- flowdeck/static/assets/RunDetailView-2ZVPmVgW.js +5 -0
- flowdeck/static/assets/ScheduleExceptionsView-DdccyMcD.js +2 -0
- flowdeck/static/assets/ScheduleExceptionsView-pWTB9mSE.css +1 -0
- flowdeck/static/assets/SettingsView-BwlizulV.js +4 -0
- flowdeck/static/assets/SettingsView-D4ybFG31.css +1 -0
- flowdeck/static/assets/StatCard-CdPYF8jZ.js +1 -0
- flowdeck/static/assets/StatCard-D06FdLL9.css +1 -0
- flowdeck/static/assets/StatsView-88bkL-AN.css +1 -0
- flowdeck/static/assets/StatsView-DONGQHCc.js +18 -0
- flowdeck/static/assets/StatusBadge-BDBPRgRa.css +1 -0
- flowdeck/static/assets/StatusBadge-DzUDQ0X_.js +1 -0
- flowdeck/static/assets/ToggleSwitch-KMgLwPsM.js +1 -0
- flowdeck/static/assets/ToggleSwitch-UNHeNS9K.css +1 -0
- flowdeck/static/assets/UiPipelinesView-BgzBgUYR.css +1 -0
- flowdeck/static/assets/UiPipelinesView-WTYqKxB5.js +2 -0
- flowdeck/static/assets/UiTaskEditorView-BgYyqqgT.js +10 -0
- flowdeck/static/assets/UiTaskEditorView-Dl6zmLDP.css +1 -0
- flowdeck/static/assets/_plugin-vue_export-helper-OBKhRxFI.js +12 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-D7EtbySE.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-SafcrIr2.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-BR1ody1F.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-CnUQnZ4D.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DQKfcdKo.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DVQm9bgb.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-CnDBPjkL.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-D1s_c2du.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-C8u6EFkq.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-MNNNbyh_.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-BCHeNDEx.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-gA6791b0.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-CdGvbdDU.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-nL80L4xU.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-BeviJPUl.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-DAkvJhej.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-Bw1Q-fVY.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-KdzBjiWs.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-CJG_V2_m.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-DeexCGiz.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-BiM5MXH8.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-C620THcd.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-B7WL5pBr.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-vZLZ_5L8.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-400-normal-Cn7ya5On.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-500-normal-BVzUBLGs.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-600-normal-Pvj4qcw_.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-700-normal-gQuUA8Wu.woff +0 -0
- flowdeck/static/assets/index-DpymzEZv.css +1 -0
- flowdeck/static/assets/index-DuXbXiXo.js +2 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- flowdeck/static/assets/light-B0F-b5Z6.js +20 -0
- flowdeck/static/assets/runtime-dom.esm-bundler-DESsN8Jj.js +2 -0
- flowdeck/static/favicon.svg +13 -0
- flowdeck/static/index.html +18 -0
- flowdeck/storage.py +145 -0
- flowdeck/tasks/__init__.py +1 -0
- flowdeck/tasks/http_executor.py +985 -0
- flowdeck/tasks/paramdefs.py +170 -0
- flowdeck/tasks/paramextract.py +185 -0
- flowdeck/tasks/python_executor.py +234 -0
- flowdeck/tasks/sql_executor.py +683 -0
- flowdeck/tasks/timevars.py +125 -0
- flowdeck/tasks/ui_registry.py +394 -0
- flowdeck-0.2.1.dist-info/METADATA +228 -0
- flowdeck-0.2.1.dist-info/RECORD +163 -0
- flowdeck-0.2.1.dist-info/WHEEL +4 -0
- flowdeck-0.2.1.dist-info/entry_points.txt +2 -0
- flowdeck-0.2.1.dist-info/licenses/LICENSE +293 -0
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
"""数据访问层(纯函数式仓储:每个函数内部自行开关 Session)。
|
|
2
|
+
|
|
3
|
+
时间统一使用 naive 本地时间(datetime.now()),见 models.py 的说明。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
from datetime import datetime, timedelta
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
10
|
+
from urllib.parse import urlsplit
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import case, func, inspect, text
|
|
13
|
+
|
|
14
|
+
from flowdeck.config import settings
|
|
15
|
+
from flowdeck.notifications.rules import NotificationRuleSchema
|
|
16
|
+
from flowdeck.schemas import PipelineRunStatus
|
|
17
|
+
|
|
18
|
+
from . import models
|
|
19
|
+
from .base import Base, SessionLocal, get_engine
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _status_value(status: Union[str, PipelineRunStatus]) -> str:
|
|
23
|
+
"""接受 str 或 PipelineRunStatus,统一转成 str 存库。"""
|
|
24
|
+
if isinstance(status, PipelineRunStatus):
|
|
25
|
+
return status.value
|
|
26
|
+
return status
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _local_midnight(now: Optional[datetime] = None) -> datetime:
|
|
30
|
+
"""本地时间当日零点。"""
|
|
31
|
+
now = now or datetime.now()
|
|
32
|
+
return now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _run_summary(run: models.PipelineRun) -> Dict[str, Any]:
|
|
36
|
+
return {
|
|
37
|
+
"id": run.id,
|
|
38
|
+
"pipeline_id": run.pipeline_id,
|
|
39
|
+
"trigger_id": run.trigger_id,
|
|
40
|
+
"status": run.status,
|
|
41
|
+
"start_time": run.start_time,
|
|
42
|
+
"end_time": run.end_time,
|
|
43
|
+
"duration": run.duration,
|
|
44
|
+
"reason": run.reason,
|
|
45
|
+
"error": run.error,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# 初始化
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def init_db() -> None:
|
|
55
|
+
"""创建全部表(幂等)+ 补齐新增列(SQLite create_all 不改已有表结构)。"""
|
|
56
|
+
engine = get_engine()
|
|
57
|
+
Base.metadata.create_all(bind=engine)
|
|
58
|
+
_migrate_schema(engine)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _migrate_schema(engine) -> None:
|
|
62
|
+
"""轻量迁移:按表逐列检查,缺列则 ALTER TABLE ADD COLUMN。"""
|
|
63
|
+
inspector = inspect(engine)
|
|
64
|
+
tables = set(inspector.get_table_names())
|
|
65
|
+
|
|
66
|
+
if "job_overrides" in tables:
|
|
67
|
+
columns = {col["name"] for col in inspector.get_columns("job_overrides")}
|
|
68
|
+
if "resume_at" not in columns:
|
|
69
|
+
with engine.begin() as conn:
|
|
70
|
+
conn.execute(text("ALTER TABLE job_overrides ADD COLUMN resume_at DATETIME"))
|
|
71
|
+
|
|
72
|
+
if "notification_rules" in tables:
|
|
73
|
+
columns = {col["name"] for col in inspector.get_columns("notification_rules")}
|
|
74
|
+
if "mentioned_list" not in columns:
|
|
75
|
+
with engine.begin() as conn:
|
|
76
|
+
conn.execute(
|
|
77
|
+
text("ALTER TABLE notification_rules ADD COLUMN mentioned_list TEXT")
|
|
78
|
+
)
|
|
79
|
+
for name, ddl in (("channel", "VARCHAR"), ("recipients", "TEXT")):
|
|
80
|
+
if name not in columns:
|
|
81
|
+
with engine.begin() as conn:
|
|
82
|
+
conn.execute(
|
|
83
|
+
text(f"ALTER TABLE notification_rules ADD COLUMN {name} {ddl}")
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
if "pipeline_runs" in tables:
|
|
87
|
+
columns = {col["name"] for col in inspector.get_columns("pipeline_runs")}
|
|
88
|
+
if "source_run_id" not in columns:
|
|
89
|
+
with engine.begin() as conn:
|
|
90
|
+
conn.execute(
|
|
91
|
+
text("ALTER TABLE pipeline_runs ADD COLUMN source_run_id INTEGER")
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
if "ui_pipelines" in tables:
|
|
95
|
+
columns = {col["name"] for col in inspector.get_columns("ui_pipelines")}
|
|
96
|
+
pending = [
|
|
97
|
+
("schedule_json", "TEXT"),
|
|
98
|
+
("credential", "VARCHAR"),
|
|
99
|
+
("request_json", "TEXT"),
|
|
100
|
+
("param_defs_json", "TEXT"),
|
|
101
|
+
("concurrency", "VARCHAR"),
|
|
102
|
+
("notify_enabled", "BOOLEAN"),
|
|
103
|
+
("notify_webhook", "TEXT"),
|
|
104
|
+
("notify_format", "VARCHAR"),
|
|
105
|
+
("notify_template", "TEXT"),
|
|
106
|
+
("notify_empty_policy", "VARCHAR"),
|
|
107
|
+
("notify_image_enabled", "BOOLEAN"),
|
|
108
|
+
]
|
|
109
|
+
missing = [(name, ddl) for name, ddl in pending if name not in columns]
|
|
110
|
+
if missing:
|
|
111
|
+
with engine.begin() as conn:
|
|
112
|
+
for name, ddl in missing:
|
|
113
|
+
conn.execute(
|
|
114
|
+
text(f"ALTER TABLE ui_pipelines ADD COLUMN {name} {ddl}")
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------------------
|
|
119
|
+
# Runs
|
|
120
|
+
# ---------------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def create_pipeline_run(
|
|
124
|
+
pipeline_id: str,
|
|
125
|
+
trigger_id: str,
|
|
126
|
+
status: Union[str, PipelineRunStatus],
|
|
127
|
+
start_time: datetime,
|
|
128
|
+
reason: str = "manual",
|
|
129
|
+
input_params: Optional[dict] = None,
|
|
130
|
+
source_run_id: Optional[int] = None,
|
|
131
|
+
) -> models.PipelineRun:
|
|
132
|
+
with SessionLocal() as db:
|
|
133
|
+
run = models.PipelineRun(
|
|
134
|
+
pipeline_id=pipeline_id,
|
|
135
|
+
trigger_id=trigger_id,
|
|
136
|
+
status=_status_value(status),
|
|
137
|
+
start_time=start_time,
|
|
138
|
+
reason=reason,
|
|
139
|
+
input_params=(
|
|
140
|
+
json.dumps(input_params, default=str, ensure_ascii=False)
|
|
141
|
+
if input_params
|
|
142
|
+
else None
|
|
143
|
+
),
|
|
144
|
+
source_run_id=source_run_id,
|
|
145
|
+
)
|
|
146
|
+
db.add(run)
|
|
147
|
+
db.commit()
|
|
148
|
+
db.refresh(run)
|
|
149
|
+
return run
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def update_run_status(
|
|
153
|
+
run_id: int,
|
|
154
|
+
status: Union[str, PipelineRunStatus],
|
|
155
|
+
end_time: Optional[datetime] = None,
|
|
156
|
+
duration: Optional[float] = None,
|
|
157
|
+
error: Optional[str] = None,
|
|
158
|
+
) -> Optional[models.PipelineRun]:
|
|
159
|
+
with SessionLocal() as db:
|
|
160
|
+
run = db.get(models.PipelineRun, run_id)
|
|
161
|
+
if run is None:
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
run.status = _status_value(status)
|
|
165
|
+
if end_time is not None:
|
|
166
|
+
run.end_time = end_time
|
|
167
|
+
if duration is not None:
|
|
168
|
+
run.duration = duration
|
|
169
|
+
if error is not None:
|
|
170
|
+
run.error = error
|
|
171
|
+
|
|
172
|
+
db.commit()
|
|
173
|
+
db.refresh(run)
|
|
174
|
+
return run
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def get_run(run_id: int) -> Optional[models.PipelineRun]:
|
|
178
|
+
with SessionLocal() as db:
|
|
179
|
+
return db.get(models.PipelineRun, run_id)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def list_runs(
|
|
183
|
+
pipeline_id: Optional[str] = None,
|
|
184
|
+
status: Optional[Union[str, PipelineRunStatus]] = None,
|
|
185
|
+
page: int = 1,
|
|
186
|
+
page_size: int = 20,
|
|
187
|
+
order_desc: bool = True,
|
|
188
|
+
since: Optional[datetime] = None,
|
|
189
|
+
) -> Tuple[List[models.PipelineRun], int]:
|
|
190
|
+
with SessionLocal() as db:
|
|
191
|
+
query = db.query(models.PipelineRun)
|
|
192
|
+
|
|
193
|
+
if pipeline_id:
|
|
194
|
+
query = query.filter(models.PipelineRun.pipeline_id == pipeline_id)
|
|
195
|
+
if status:
|
|
196
|
+
query = query.filter(models.PipelineRun.status == _status_value(status))
|
|
197
|
+
if since:
|
|
198
|
+
query = query.filter(models.PipelineRun.start_time >= since)
|
|
199
|
+
|
|
200
|
+
total = query.count()
|
|
201
|
+
|
|
202
|
+
order = (
|
|
203
|
+
models.PipelineRun.id.desc()
|
|
204
|
+
if order_desc
|
|
205
|
+
else models.PipelineRun.id.asc()
|
|
206
|
+
)
|
|
207
|
+
runs = (
|
|
208
|
+
query.order_by(order)
|
|
209
|
+
.offset((page - 1) * page_size)
|
|
210
|
+
.limit(page_size)
|
|
211
|
+
.all()
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
return runs, total
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def list_failed_recent(limit: int = 10) -> List[models.PipelineRun]:
|
|
218
|
+
with SessionLocal() as db:
|
|
219
|
+
return (
|
|
220
|
+
db.query(models.PipelineRun)
|
|
221
|
+
.filter(models.PipelineRun.status == PipelineRunStatus.FAILED.value)
|
|
222
|
+
.order_by(models.PipelineRun.id.desc())
|
|
223
|
+
.limit(limit)
|
|
224
|
+
.all()
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def get_run_failure_details(run_ids: List[int]) -> Dict[int, Dict[str, Any]]:
|
|
229
|
+
"""批量补充失败 run 信息(最近报错页用):
|
|
230
|
+
|
|
231
|
+
- ``failed_task_id`` / ``failed_task_error``:该 run 第一个失败任务;
|
|
232
|
+
- ``rerun_count``:以该 run 为来源的后续重跑次数(source_run_id 指向它)。
|
|
233
|
+
"""
|
|
234
|
+
if not run_ids:
|
|
235
|
+
return {}
|
|
236
|
+
|
|
237
|
+
with SessionLocal() as db:
|
|
238
|
+
failed_rows = (
|
|
239
|
+
db.query(models.TaskRun)
|
|
240
|
+
.filter(
|
|
241
|
+
models.TaskRun.run_id.in_(run_ids),
|
|
242
|
+
models.TaskRun.status == PipelineRunStatus.FAILED.value,
|
|
243
|
+
)
|
|
244
|
+
.order_by(models.TaskRun.id.asc())
|
|
245
|
+
.all()
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
rerun_rows = (
|
|
249
|
+
db.query(
|
|
250
|
+
models.PipelineRun.source_run_id,
|
|
251
|
+
func.count(models.PipelineRun.id),
|
|
252
|
+
)
|
|
253
|
+
.filter(models.PipelineRun.source_run_id.in_(run_ids))
|
|
254
|
+
.group_by(models.PipelineRun.source_run_id)
|
|
255
|
+
.all()
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
details: Dict[int, Dict[str, Any]] = {
|
|
259
|
+
run_id: {"failed_task_id": None, "failed_task_error": None, "rerun_count": 0}
|
|
260
|
+
for run_id in run_ids
|
|
261
|
+
}
|
|
262
|
+
for row in failed_rows:
|
|
263
|
+
# 只取首个失败任务(顺序执行,后续任务不会再跑)
|
|
264
|
+
if details[row.run_id]["failed_task_id"] is None:
|
|
265
|
+
details[row.run_id]["failed_task_id"] = row.task_id
|
|
266
|
+
details[row.run_id]["failed_task_error"] = row.error
|
|
267
|
+
for source_run_id, count in rerun_rows:
|
|
268
|
+
if source_run_id in details:
|
|
269
|
+
details[source_run_id]["rerun_count"] = count
|
|
270
|
+
return details
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def get_first_failed_task(run_id: int) -> Optional[models.TaskRun]:
|
|
274
|
+
"""该 run 第一个失败任务(通知里定位失败任务用);无则返回 None。"""
|
|
275
|
+
with SessionLocal() as db:
|
|
276
|
+
return (
|
|
277
|
+
db.query(models.TaskRun)
|
|
278
|
+
.filter(
|
|
279
|
+
models.TaskRun.run_id == run_id,
|
|
280
|
+
models.TaskRun.status == PipelineRunStatus.FAILED.value,
|
|
281
|
+
)
|
|
282
|
+
.order_by(models.TaskRun.id.asc())
|
|
283
|
+
.first()
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def list_runs_by_statuses(
|
|
288
|
+
statuses: List[Union[str, PipelineRunStatus]],
|
|
289
|
+
) -> List[models.PipelineRun]:
|
|
290
|
+
"""按状态集合查 runs(崩溃恢复用:启动时找遗留的 RUNNING/PENDING)。"""
|
|
291
|
+
values = [_status_value(status) for status in statuses]
|
|
292
|
+
with SessionLocal() as db:
|
|
293
|
+
return (
|
|
294
|
+
db.query(models.PipelineRun)
|
|
295
|
+
.filter(models.PipelineRun.status.in_(values))
|
|
296
|
+
.order_by(models.PipelineRun.id.asc())
|
|
297
|
+
.all()
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def fail_running_task_runs(run_id: int, error: str) -> int:
|
|
302
|
+
"""把 run 下仍处于 RUNNING 的 task_runs 标记为 FAILED,返回条数(崩溃恢复用)。"""
|
|
303
|
+
with SessionLocal() as db:
|
|
304
|
+
rows = (
|
|
305
|
+
db.query(models.TaskRun)
|
|
306
|
+
.filter(
|
|
307
|
+
models.TaskRun.run_id == run_id,
|
|
308
|
+
models.TaskRun.status == PipelineRunStatus.RUNNING.value,
|
|
309
|
+
)
|
|
310
|
+
.all()
|
|
311
|
+
)
|
|
312
|
+
now = datetime.now()
|
|
313
|
+
for row in rows:
|
|
314
|
+
row.status = PipelineRunStatus.FAILED.value
|
|
315
|
+
row.end_time = now
|
|
316
|
+
row.duration = (now - row.start_time).total_seconds()
|
|
317
|
+
row.error = error
|
|
318
|
+
if rows:
|
|
319
|
+
db.commit()
|
|
320
|
+
return len(rows)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def delete_runs_before(cutoff: datetime) -> List[int]:
|
|
324
|
+
"""删除 start_time 早于 cutoff 的 runs(连同 task_runs),返回被删的 run id 列表。"""
|
|
325
|
+
with SessionLocal() as db:
|
|
326
|
+
ids = [
|
|
327
|
+
row[0]
|
|
328
|
+
for row in db.query(models.PipelineRun.id)
|
|
329
|
+
.filter(models.PipelineRun.start_time < cutoff)
|
|
330
|
+
.all()
|
|
331
|
+
]
|
|
332
|
+
|
|
333
|
+
if ids:
|
|
334
|
+
db.query(models.TaskRun).filter(
|
|
335
|
+
models.TaskRun.run_id.in_(ids)
|
|
336
|
+
).delete(synchronize_session=False)
|
|
337
|
+
db.query(models.PipelineRun).filter(
|
|
338
|
+
models.PipelineRun.id.in_(ids)
|
|
339
|
+
).delete(synchronize_session=False)
|
|
340
|
+
db.commit()
|
|
341
|
+
|
|
342
|
+
return ids
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def list_running_run_ids(
|
|
346
|
+
pipeline_id: str, exclude_run_id: Optional[int] = None
|
|
347
|
+
) -> List[int]:
|
|
348
|
+
"""同 pipeline 仍处于 RUNNING 的 run id 列表(并发互斥判断用)。"""
|
|
349
|
+
with SessionLocal() as db:
|
|
350
|
+
query = db.query(models.PipelineRun.id).filter(
|
|
351
|
+
models.PipelineRun.pipeline_id == pipeline_id,
|
|
352
|
+
models.PipelineRun.status == PipelineRunStatus.RUNNING.value,
|
|
353
|
+
)
|
|
354
|
+
if exclude_run_id is not None:
|
|
355
|
+
query = query.filter(models.PipelineRun.id != exclude_run_id)
|
|
356
|
+
return [row[0] for row in query.all()]
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def first_run_time(pipeline_id: str, trigger_id: str) -> Optional[datetime]:
|
|
360
|
+
"""该 trigger 最早一次 run 的开始时间(naive);从未运行过返回 None。"""
|
|
361
|
+
with SessionLocal() as db:
|
|
362
|
+
return (
|
|
363
|
+
db.query(func.min(models.PipelineRun.start_time))
|
|
364
|
+
.filter(
|
|
365
|
+
models.PipelineRun.pipeline_id == pipeline_id,
|
|
366
|
+
models.PipelineRun.trigger_id == trigger_id,
|
|
367
|
+
)
|
|
368
|
+
.scalar()
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def count_runs_in_window(
|
|
373
|
+
pipeline_id: str,
|
|
374
|
+
trigger_id: str,
|
|
375
|
+
start: datetime,
|
|
376
|
+
end: datetime,
|
|
377
|
+
) -> int:
|
|
378
|
+
"""统计时间窗 [start, end) 内的运行数(missed 巡检用)。"""
|
|
379
|
+
with SessionLocal() as db:
|
|
380
|
+
return (
|
|
381
|
+
db.query(func.count(models.PipelineRun.id))
|
|
382
|
+
.filter(
|
|
383
|
+
models.PipelineRun.pipeline_id == pipeline_id,
|
|
384
|
+
models.PipelineRun.trigger_id == trigger_id,
|
|
385
|
+
models.PipelineRun.start_time >= start,
|
|
386
|
+
models.PipelineRun.start_time < end,
|
|
387
|
+
)
|
|
388
|
+
.scalar()
|
|
389
|
+
or 0
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def count_all_runs() -> int:
|
|
394
|
+
with SessionLocal() as db:
|
|
395
|
+
return db.query(func.count(models.PipelineRun.id)).scalar() or 0
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def count_runs_before(cutoff: datetime) -> int:
|
|
399
|
+
"""start_time 早于 cutoff 的 run 数量(按当前保留策略的「待清理数」)。"""
|
|
400
|
+
with SessionLocal() as db:
|
|
401
|
+
return (
|
|
402
|
+
db.query(func.count(models.PipelineRun.id))
|
|
403
|
+
.filter(models.PipelineRun.start_time < cutoff)
|
|
404
|
+
.scalar()
|
|
405
|
+
or 0
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
# ---------------------------------------------------------------------------
|
|
410
|
+
# TaskRuns
|
|
411
|
+
# ---------------------------------------------------------------------------
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def create_task_run(
|
|
415
|
+
run_id: int,
|
|
416
|
+
task_id: str,
|
|
417
|
+
status: Union[str, PipelineRunStatus],
|
|
418
|
+
start_time: datetime,
|
|
419
|
+
) -> models.TaskRun:
|
|
420
|
+
with SessionLocal() as db:
|
|
421
|
+
task_run = models.TaskRun(
|
|
422
|
+
run_id=run_id,
|
|
423
|
+
task_id=task_id,
|
|
424
|
+
status=_status_value(status),
|
|
425
|
+
start_time=start_time,
|
|
426
|
+
)
|
|
427
|
+
db.add(task_run)
|
|
428
|
+
db.commit()
|
|
429
|
+
db.refresh(task_run)
|
|
430
|
+
return task_run
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def update_task_run(
|
|
434
|
+
task_run_id: int,
|
|
435
|
+
status: Union[str, PipelineRunStatus],
|
|
436
|
+
end_time: Optional[datetime] = None,
|
|
437
|
+
duration: Optional[float] = None,
|
|
438
|
+
error: Optional[str] = None,
|
|
439
|
+
) -> Optional[models.TaskRun]:
|
|
440
|
+
with SessionLocal() as db:
|
|
441
|
+
task_run = db.get(models.TaskRun, task_run_id)
|
|
442
|
+
if task_run is None:
|
|
443
|
+
return None
|
|
444
|
+
|
|
445
|
+
task_run.status = _status_value(status)
|
|
446
|
+
if end_time is not None:
|
|
447
|
+
task_run.end_time = end_time
|
|
448
|
+
if duration is not None:
|
|
449
|
+
task_run.duration = duration
|
|
450
|
+
if error is not None:
|
|
451
|
+
task_run.error = error
|
|
452
|
+
|
|
453
|
+
db.commit()
|
|
454
|
+
db.refresh(task_run)
|
|
455
|
+
return task_run
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def get_task_runs(run_id: int) -> List[models.TaskRun]:
|
|
459
|
+
with SessionLocal() as db:
|
|
460
|
+
return (
|
|
461
|
+
db.query(models.TaskRun)
|
|
462
|
+
.filter(models.TaskRun.run_id == run_id)
|
|
463
|
+
.order_by(models.TaskRun.id.asc())
|
|
464
|
+
.all()
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# ---------------------------------------------------------------------------
|
|
469
|
+
# 统计
|
|
470
|
+
# ---------------------------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _status_counts(db, since: datetime) -> Dict[str, int]:
|
|
474
|
+
rows = (
|
|
475
|
+
db.query(models.PipelineRun.status, func.count(models.PipelineRun.id))
|
|
476
|
+
.filter(models.PipelineRun.start_time >= since)
|
|
477
|
+
.group_by(models.PipelineRun.status)
|
|
478
|
+
.all()
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
counts = {status.value: 0 for status in PipelineRunStatus}
|
|
482
|
+
for status, count in rows:
|
|
483
|
+
counts[status] = count
|
|
484
|
+
return counts
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def dashboard_summary() -> Dict[str, Any]:
|
|
488
|
+
"""仪表盘汇总:今日/近 7 天各状态计数 + 最近失败列表(边界按本地零点)。"""
|
|
489
|
+
today_zero = _local_midnight()
|
|
490
|
+
week_start = today_zero - timedelta(days=6) # 含今日共 7 个自然日
|
|
491
|
+
|
|
492
|
+
with SessionLocal() as db:
|
|
493
|
+
today = _status_counts(db, today_zero)
|
|
494
|
+
week = _status_counts(db, week_start)
|
|
495
|
+
|
|
496
|
+
recent_failures = [
|
|
497
|
+
_run_summary(run)
|
|
498
|
+
for run in db.query(models.PipelineRun)
|
|
499
|
+
.filter(models.PipelineRun.status == PipelineRunStatus.FAILED.value)
|
|
500
|
+
.order_by(models.PipelineRun.id.desc())
|
|
501
|
+
.limit(10)
|
|
502
|
+
.all()
|
|
503
|
+
]
|
|
504
|
+
|
|
505
|
+
return {
|
|
506
|
+
"today": today,
|
|
507
|
+
"week": week,
|
|
508
|
+
"recent_failures": recent_failures,
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def pipeline_stats(pipeline_id: str, days: int = 90) -> Dict[str, Any]:
|
|
513
|
+
"""单 pipeline 统计:按日聚合 [{date,total,succeeded,failed,avg_duration}] + 最近 200 条 run 摘要。"""
|
|
514
|
+
since = _local_midnight() - timedelta(days=days - 1)
|
|
515
|
+
|
|
516
|
+
with SessionLocal() as db:
|
|
517
|
+
date_col = func.date(models.PipelineRun.start_time)
|
|
518
|
+
|
|
519
|
+
daily_rows = (
|
|
520
|
+
db.query(
|
|
521
|
+
date_col.label("date"),
|
|
522
|
+
func.count(models.PipelineRun.id).label("total"),
|
|
523
|
+
func.sum(
|
|
524
|
+
case(
|
|
525
|
+
(
|
|
526
|
+
models.PipelineRun.status
|
|
527
|
+
== PipelineRunStatus.SUCCEEDED.value,
|
|
528
|
+
1,
|
|
529
|
+
),
|
|
530
|
+
else_=0,
|
|
531
|
+
)
|
|
532
|
+
).label("succeeded"),
|
|
533
|
+
func.sum(
|
|
534
|
+
case(
|
|
535
|
+
(models.PipelineRun.status == PipelineRunStatus.FAILED.value, 1),
|
|
536
|
+
else_=0,
|
|
537
|
+
)
|
|
538
|
+
).label("failed"),
|
|
539
|
+
func.sum(
|
|
540
|
+
case(
|
|
541
|
+
(
|
|
542
|
+
models.PipelineRun.status == PipelineRunStatus.SKIPPED.value,
|
|
543
|
+
1,
|
|
544
|
+
),
|
|
545
|
+
else_=0,
|
|
546
|
+
)
|
|
547
|
+
).label("skipped"),
|
|
548
|
+
func.avg(models.PipelineRun.duration).label("avg_duration"),
|
|
549
|
+
)
|
|
550
|
+
.filter(
|
|
551
|
+
models.PipelineRun.pipeline_id == pipeline_id,
|
|
552
|
+
models.PipelineRun.start_time >= since,
|
|
553
|
+
)
|
|
554
|
+
.group_by(date_col)
|
|
555
|
+
.order_by(date_col.asc())
|
|
556
|
+
.all()
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
daily = [
|
|
560
|
+
{
|
|
561
|
+
"date": str(row.date),
|
|
562
|
+
"total": row.total,
|
|
563
|
+
"succeeded": row.succeeded or 0,
|
|
564
|
+
"failed": row.failed or 0,
|
|
565
|
+
"skipped": row.skipped or 0,
|
|
566
|
+
"avg_duration": (
|
|
567
|
+
round(row.avg_duration, 3) if row.avg_duration is not None else None
|
|
568
|
+
),
|
|
569
|
+
}
|
|
570
|
+
for row in daily_rows
|
|
571
|
+
]
|
|
572
|
+
|
|
573
|
+
recent_runs = [
|
|
574
|
+
_run_summary(run)
|
|
575
|
+
for run in db.query(models.PipelineRun)
|
|
576
|
+
.filter(models.PipelineRun.pipeline_id == pipeline_id)
|
|
577
|
+
.order_by(models.PipelineRun.id.desc())
|
|
578
|
+
.limit(200)
|
|
579
|
+
.all()
|
|
580
|
+
]
|
|
581
|
+
|
|
582
|
+
return {"daily": daily, "runs": recent_runs}
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
# ---------------------------------------------------------------------------
|
|
586
|
+
# JobOverrides(暂停 / 禁用)
|
|
587
|
+
# ---------------------------------------------------------------------------
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def set_override(
|
|
591
|
+
pipeline_id: str, trigger_id: str = "", resume_at: Optional[datetime] = None
|
|
592
|
+
) -> None:
|
|
593
|
+
"""写入暂停/禁用状态(行存在即暂停;幂等,重复暂停会刷新 resume_at)。"""
|
|
594
|
+
with SessionLocal() as db:
|
|
595
|
+
exists = (
|
|
596
|
+
db.query(models.JobOverride)
|
|
597
|
+
.filter(
|
|
598
|
+
models.JobOverride.pipeline_id == pipeline_id,
|
|
599
|
+
models.JobOverride.trigger_id == trigger_id,
|
|
600
|
+
)
|
|
601
|
+
.first()
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
if exists is None:
|
|
605
|
+
db.add(
|
|
606
|
+
models.JobOverride(
|
|
607
|
+
pipeline_id=pipeline_id,
|
|
608
|
+
trigger_id=trigger_id,
|
|
609
|
+
created_at=datetime.now(),
|
|
610
|
+
resume_at=resume_at,
|
|
611
|
+
)
|
|
612
|
+
)
|
|
613
|
+
else:
|
|
614
|
+
exists.resume_at = resume_at
|
|
615
|
+
db.commit()
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def clear_override(pipeline_id: str, trigger_id: str = "") -> None:
|
|
619
|
+
with SessionLocal() as db:
|
|
620
|
+
db.query(models.JobOverride).filter(
|
|
621
|
+
models.JobOverride.pipeline_id == pipeline_id,
|
|
622
|
+
models.JobOverride.trigger_id == trigger_id,
|
|
623
|
+
).delete(synchronize_session=False)
|
|
624
|
+
db.commit()
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def is_pipeline_paused(pipeline_id: str) -> bool:
|
|
628
|
+
return get_pipeline_override(pipeline_id) is not None
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def get_pipeline_override(pipeline_id: str) -> Optional[models.JobOverride]:
|
|
632
|
+
"""pipeline 级暂停行(含 resume_at),未暂停返回 None。"""
|
|
633
|
+
with SessionLocal() as db:
|
|
634
|
+
return (
|
|
635
|
+
db.query(models.JobOverride)
|
|
636
|
+
.filter(
|
|
637
|
+
models.JobOverride.pipeline_id == pipeline_id,
|
|
638
|
+
models.JobOverride.trigger_id == "",
|
|
639
|
+
)
|
|
640
|
+
.first()
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def is_trigger_disabled(pipeline_id: str, trigger_id: str) -> bool:
|
|
645
|
+
with SessionLocal() as db:
|
|
646
|
+
return (
|
|
647
|
+
db.query(models.JobOverride)
|
|
648
|
+
.filter(
|
|
649
|
+
models.JobOverride.pipeline_id == pipeline_id,
|
|
650
|
+
models.JobOverride.trigger_id == trigger_id,
|
|
651
|
+
)
|
|
652
|
+
.first()
|
|
653
|
+
is not None
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def list_overrides() -> List[models.JobOverride]:
|
|
658
|
+
with SessionLocal() as db:
|
|
659
|
+
return (
|
|
660
|
+
db.query(models.JobOverride).order_by(models.JobOverride.id.asc()).all()
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
# ---------------------------------------------------------------------------
|
|
665
|
+
# NotificationRules
|
|
666
|
+
# ---------------------------------------------------------------------------
|
|
667
|
+
|
|
668
|
+
_RULE_COLUMN_NAMES = (
|
|
669
|
+
"name",
|
|
670
|
+
"events",
|
|
671
|
+
"pipeline_pattern",
|
|
672
|
+
"webhook_url",
|
|
673
|
+
"template",
|
|
674
|
+
"mentioned_list",
|
|
675
|
+
"channel",
|
|
676
|
+
"recipients",
|
|
677
|
+
"enabled",
|
|
678
|
+
"source",
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def _rule_model_fields(
|
|
683
|
+
data: Union[Dict[str, Any], NotificationRuleSchema]
|
|
684
|
+
) -> Dict[str, Any]:
|
|
685
|
+
"""把 dict / NotificationRuleSchema 规范化为 NotificationRule 的字段 dict。"""
|
|
686
|
+
if isinstance(data, NotificationRuleSchema):
|
|
687
|
+
fields = data.model_dump()
|
|
688
|
+
else:
|
|
689
|
+
fields = dict(data)
|
|
690
|
+
|
|
691
|
+
fields = {key: value for key, value in fields.items() if key in _RULE_COLUMN_NAMES}
|
|
692
|
+
|
|
693
|
+
if "events" in fields:
|
|
694
|
+
fields["events"] = json.dumps(fields.get("events") or [], ensure_ascii=False)
|
|
695
|
+
|
|
696
|
+
if "mentioned_list" in fields:
|
|
697
|
+
fields["mentioned_list"] = json.dumps(
|
|
698
|
+
fields.get("mentioned_list") or [], ensure_ascii=False
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
if "recipients" in fields:
|
|
702
|
+
fields["recipients"] = json.dumps(
|
|
703
|
+
fields.get("recipients") or [], ensure_ascii=False
|
|
704
|
+
)
|
|
705
|
+
|
|
706
|
+
fields.setdefault("source", "ui")
|
|
707
|
+
return fields
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def list_rules_db() -> List[models.NotificationRule]:
|
|
711
|
+
with SessionLocal() as db:
|
|
712
|
+
return (
|
|
713
|
+
db.query(models.NotificationRule)
|
|
714
|
+
.order_by(models.NotificationRule.id.asc())
|
|
715
|
+
.all()
|
|
716
|
+
)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def create_rule(
|
|
720
|
+
data: Union[Dict[str, Any], NotificationRuleSchema]
|
|
721
|
+
) -> models.NotificationRule:
|
|
722
|
+
fields = _rule_model_fields(data)
|
|
723
|
+
|
|
724
|
+
with SessionLocal() as db:
|
|
725
|
+
rule = models.NotificationRule(**fields)
|
|
726
|
+
db.add(rule)
|
|
727
|
+
db.commit()
|
|
728
|
+
db.refresh(rule)
|
|
729
|
+
return rule
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def update_rule(
|
|
733
|
+
rule_id: int, data: Union[Dict[str, Any], NotificationRuleSchema]
|
|
734
|
+
) -> Optional[models.NotificationRule]:
|
|
735
|
+
fields = _rule_model_fields(data)
|
|
736
|
+
|
|
737
|
+
with SessionLocal() as db:
|
|
738
|
+
rule = db.get(models.NotificationRule, rule_id)
|
|
739
|
+
if rule is None:
|
|
740
|
+
return None
|
|
741
|
+
|
|
742
|
+
for key, value in fields.items():
|
|
743
|
+
setattr(rule, key, value)
|
|
744
|
+
|
|
745
|
+
db.commit()
|
|
746
|
+
db.refresh(rule)
|
|
747
|
+
return rule
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def delete_rule(rule_id: int) -> bool:
|
|
751
|
+
with SessionLocal() as db:
|
|
752
|
+
deleted = (
|
|
753
|
+
db.query(models.NotificationRule)
|
|
754
|
+
.filter(models.NotificationRule.id == rule_id)
|
|
755
|
+
.delete(synchronize_session=False)
|
|
756
|
+
)
|
|
757
|
+
db.commit()
|
|
758
|
+
return deleted > 0
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
# ---------------------------------------------------------------------------
|
|
762
|
+
# WebhookRobots(企业微信群机器人注册表)
|
|
763
|
+
# ---------------------------------------------------------------------------
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def list_robots() -> List[models.WebhookRobot]:
|
|
767
|
+
with SessionLocal() as db:
|
|
768
|
+
return db.query(models.WebhookRobot).order_by(models.WebhookRobot.name.asc()).all()
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def get_robot_by_name(name: str) -> Optional[models.WebhookRobot]:
|
|
772
|
+
with SessionLocal() as db:
|
|
773
|
+
return db.query(models.WebhookRobot).filter(models.WebhookRobot.name == name).first()
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def upsert_robot(
|
|
777
|
+
name: str, url: str, note: str = ""
|
|
778
|
+
) -> Tuple[models.WebhookRobot, bool]:
|
|
779
|
+
"""按名 upsert 机器人,返回 (robot, created)。导入 webhooks.yaml 等场景复用。"""
|
|
780
|
+
with SessionLocal() as db:
|
|
781
|
+
robot = db.query(models.WebhookRobot).filter(models.WebhookRobot.name == name).first()
|
|
782
|
+
created = robot is None
|
|
783
|
+
if robot is None:
|
|
784
|
+
robot = models.WebhookRobot(name=name, url=url, note=note)
|
|
785
|
+
db.add(robot)
|
|
786
|
+
else:
|
|
787
|
+
robot.url = url
|
|
788
|
+
if note:
|
|
789
|
+
robot.note = note
|
|
790
|
+
db.commit()
|
|
791
|
+
db.refresh(robot)
|
|
792
|
+
return robot, created
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def update_robot(
|
|
796
|
+
robot_id: int, name: str, url: str, note: str = ""
|
|
797
|
+
) -> Optional[models.WebhookRobot]:
|
|
798
|
+
"""按 id 更新机器人(字段全量覆盖,支持改名与清空备注)。"""
|
|
799
|
+
with SessionLocal() as db:
|
|
800
|
+
robot = db.get(models.WebhookRobot, robot_id)
|
|
801
|
+
if robot is None:
|
|
802
|
+
return None
|
|
803
|
+
robot.name = name
|
|
804
|
+
robot.url = url
|
|
805
|
+
robot.note = note
|
|
806
|
+
db.commit()
|
|
807
|
+
db.refresh(robot)
|
|
808
|
+
return robot
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def delete_robot(robot_id: int) -> bool:
|
|
812
|
+
with SessionLocal() as db:
|
|
813
|
+
deleted = (
|
|
814
|
+
db.query(models.WebhookRobot)
|
|
815
|
+
.filter(models.WebhookRobot.id == robot_id)
|
|
816
|
+
.delete(synchronize_session=False)
|
|
817
|
+
)
|
|
818
|
+
db.commit()
|
|
819
|
+
return deleted > 0
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
# ---------------------------------------------------------------------------
|
|
823
|
+
# AppSettings(运行时键值设置)
|
|
824
|
+
# ---------------------------------------------------------------------------
|
|
825
|
+
|
|
826
|
+
SETTING_RETENTION_DAYS = "retention_days"
|
|
827
|
+
SETTING_DISPLAY_TZ = "display_tz"
|
|
828
|
+
SETTING_EXPECTED_UTC_OFFSET = "expected_utc_offset"
|
|
829
|
+
SETTING_ALLOWED_ORIGINS = "allowed_origins"
|
|
830
|
+
SETTING_AUTH_CONFIG = "auth_config"
|
|
831
|
+
SETTING_SMTP_CONFIG = "smtp_config"
|
|
832
|
+
SETTING_BASE_URL = "base_url"
|
|
833
|
+
SETTING_LEARNED_ORIGIN = "learned_origin"
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def get_setting(key: str) -> Optional[str]:
|
|
837
|
+
with SessionLocal() as db:
|
|
838
|
+
row = db.get(models.AppSetting, key)
|
|
839
|
+
return row.value if row is not None else None
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def set_setting(key: str, value: str) -> None:
|
|
843
|
+
"""写入设置(upsert)。"""
|
|
844
|
+
with SessionLocal() as db:
|
|
845
|
+
row = db.get(models.AppSetting, key)
|
|
846
|
+
if row is None:
|
|
847
|
+
db.add(models.AppSetting(key=key, value=value, updated_at=datetime.now()))
|
|
848
|
+
else:
|
|
849
|
+
row.value = value
|
|
850
|
+
row.updated_at = datetime.now()
|
|
851
|
+
db.commit()
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
def get_retention_days() -> int:
|
|
855
|
+
"""动态保留天数:DB app_settings 优先,回落 yaml/env 默认。0 或负数 = 不清理。"""
|
|
856
|
+
raw = get_setting(SETTING_RETENTION_DAYS)
|
|
857
|
+
if raw is not None:
|
|
858
|
+
try:
|
|
859
|
+
return int(raw)
|
|
860
|
+
except (TypeError, ValueError):
|
|
861
|
+
pass # 脏数据回落默认
|
|
862
|
+
return settings.retention_days
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def get_expected_utc_offset() -> str:
|
|
866
|
+
"""动态时区校验偏移:DB 优先,回落 yaml/env 默认。空串 = 关闭检测。
|
|
867
|
+
|
|
868
|
+
DB 不可读时(如首次启动建库前)静默回落默认,保证启动链路不中断。
|
|
869
|
+
"""
|
|
870
|
+
try:
|
|
871
|
+
raw = get_setting(SETTING_EXPECTED_UTC_OFFSET)
|
|
872
|
+
except Exception:
|
|
873
|
+
raw = None
|
|
874
|
+
if raw is not None:
|
|
875
|
+
return raw
|
|
876
|
+
return settings.expected_utc_offset
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def get_allowed_origins() -> List[str]:
|
|
880
|
+
"""动态 CORS 允许来源:DB 优先(JSON 数组),回落 yaml/env 默认。"""
|
|
881
|
+
try:
|
|
882
|
+
raw = get_setting(SETTING_ALLOWED_ORIGINS)
|
|
883
|
+
except Exception:
|
|
884
|
+
raw = None
|
|
885
|
+
if raw is not None:
|
|
886
|
+
try:
|
|
887
|
+
data = json.loads(raw)
|
|
888
|
+
if isinstance(data, list):
|
|
889
|
+
return [str(item) for item in data]
|
|
890
|
+
except (TypeError, ValueError):
|
|
891
|
+
pass # 脏数据回落默认
|
|
892
|
+
return list(settings.allowed_origins)
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def _normalize_origin(raw: str) -> str:
|
|
896
|
+
"""规范化站点 origin:仅保留 http(s)://host[:port],非法/本机/污染值返回空串。
|
|
897
|
+
|
|
898
|
+
只接受 http/https 绝对地址;拒绝带路径、query、fragment 与用户信息;
|
|
899
|
+
本机回环地址(localhost / 127.0.0.0/8 / 0.0.0.0 / ::1)不记录,避免
|
|
900
|
+
用本机访问把通知链接写坏。
|
|
901
|
+
"""
|
|
902
|
+
value = (raw or "").strip()
|
|
903
|
+
if not value:
|
|
904
|
+
return ""
|
|
905
|
+
try:
|
|
906
|
+
parsed = urlsplit(value)
|
|
907
|
+
except ValueError:
|
|
908
|
+
return ""
|
|
909
|
+
if parsed.scheme.lower() not in ("http", "https"):
|
|
910
|
+
return ""
|
|
911
|
+
if not parsed.netloc or parsed.username or parsed.password:
|
|
912
|
+
return ""
|
|
913
|
+
if parsed.query or parsed.fragment or parsed.path not in ("", "/"):
|
|
914
|
+
return ""
|
|
915
|
+
host = (parsed.hostname or "").lower()
|
|
916
|
+
if not host:
|
|
917
|
+
return ""
|
|
918
|
+
if (
|
|
919
|
+
host == "localhost"
|
|
920
|
+
or host == "0.0.0.0"
|
|
921
|
+
or host == "::1"
|
|
922
|
+
or host.startswith("127.")
|
|
923
|
+
):
|
|
924
|
+
return ""
|
|
925
|
+
return f"{parsed.scheme.lower()}://{parsed.netloc}"
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
def get_base_url() -> str:
|
|
929
|
+
"""手工配置的通知站点基地址(DB app_settings,可选覆盖)。
|
|
930
|
+
|
|
931
|
+
允许带路径前缀(如 http://host/flowdeck),仅拒绝非 http(s)、无主机、
|
|
932
|
+
带 query/fragment 的值;未配置或非法时返回空串,回落到自动推断值。
|
|
933
|
+
"""
|
|
934
|
+
try:
|
|
935
|
+
raw = get_setting(SETTING_BASE_URL)
|
|
936
|
+
except Exception:
|
|
937
|
+
raw = None
|
|
938
|
+
|
|
939
|
+
value = (raw or "").strip().rstrip("/")
|
|
940
|
+
if not value:
|
|
941
|
+
return ""
|
|
942
|
+
try:
|
|
943
|
+
parsed = urlsplit(value)
|
|
944
|
+
except ValueError:
|
|
945
|
+
return ""
|
|
946
|
+
if (
|
|
947
|
+
parsed.scheme.lower() not in ("http", "https")
|
|
948
|
+
or not parsed.netloc
|
|
949
|
+
or parsed.query
|
|
950
|
+
or parsed.fragment
|
|
951
|
+
):
|
|
952
|
+
return ""
|
|
953
|
+
return value
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
# 自动学到的 origin 缓存:避免每个请求都读库,也避免相同值反复写库。
|
|
957
|
+
# 进程内单例;多进程部署时各进程仅在值变化时写一次,不会刷爆库。
|
|
958
|
+
_learned_lock = threading.Lock()
|
|
959
|
+
_learned_cache = ""
|
|
960
|
+
_learned_loaded = False
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _get_learned_cached() -> str:
|
|
964
|
+
"""读取缓存中的自动 origin;首次调用从 DB 加载并校验(调用方需持锁)。"""
|
|
965
|
+
global _learned_cache, _learned_loaded
|
|
966
|
+
|
|
967
|
+
if not _learned_loaded:
|
|
968
|
+
try:
|
|
969
|
+
raw = get_setting(SETTING_LEARNED_ORIGIN)
|
|
970
|
+
except Exception:
|
|
971
|
+
raw = None
|
|
972
|
+
_learned_cache = _normalize_origin(raw or "")
|
|
973
|
+
_learned_loaded = True
|
|
974
|
+
return _learned_cache
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def get_learned_origin() -> str:
|
|
978
|
+
"""自动学到的站点 origin;未学到时返回空串。"""
|
|
979
|
+
with _learned_lock:
|
|
980
|
+
return _get_learned_cached()
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def record_learned_origin(raw: str) -> str:
|
|
984
|
+
"""记录最近一次访问的站点 origin,返回最终生效的自动值。
|
|
985
|
+
|
|
986
|
+
- 非法/本机地址直接忽略(不写库);
|
|
987
|
+
- 与缓存相同则不写库;
|
|
988
|
+
- 加锁串行化「比较 + 写入」,避免并发请求重复写。
|
|
989
|
+
"""
|
|
990
|
+
global _learned_cache, _learned_loaded
|
|
991
|
+
|
|
992
|
+
origin = _normalize_origin(raw)
|
|
993
|
+
if not origin:
|
|
994
|
+
return ""
|
|
995
|
+
|
|
996
|
+
with _learned_lock:
|
|
997
|
+
current = _get_learned_cached()
|
|
998
|
+
if origin == current:
|
|
999
|
+
return current
|
|
1000
|
+
try:
|
|
1001
|
+
set_setting(SETTING_LEARNED_ORIGIN, origin)
|
|
1002
|
+
except Exception:
|
|
1003
|
+
# 学习失败不影响请求本身,保留旧值等下次再试
|
|
1004
|
+
return current
|
|
1005
|
+
_learned_cache = origin
|
|
1006
|
+
_learned_loaded = True
|
|
1007
|
+
return origin
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def get_effective_base_url() -> str:
|
|
1011
|
+
"""通知链接最终使用的基地址:手工配置 > 自动推断 > 空串(相对路径)。"""
|
|
1012
|
+
manual = get_base_url()
|
|
1013
|
+
if manual:
|
|
1014
|
+
return manual
|
|
1015
|
+
return get_learned_origin()
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def get_base_url_source() -> str:
|
|
1019
|
+
"""生效地址来源:manual(手工指定)/ auto(自动推断)/ none(未确定)。"""
|
|
1020
|
+
if get_base_url():
|
|
1021
|
+
return "manual"
|
|
1022
|
+
if get_learned_origin():
|
|
1023
|
+
return "auto"
|
|
1024
|
+
return "none"
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def get_auth_config() -> Optional[Dict[str, Any]]:
|
|
1028
|
+
"""DB 中的 Basic 认证配置({enabled, username, password});未设置返回 None。
|
|
1029
|
+
|
|
1030
|
+
与 yaml settings.auth 的优先级由调用方决定(DB 优先)。
|
|
1031
|
+
"""
|
|
1032
|
+
try:
|
|
1033
|
+
raw = get_setting(SETTING_AUTH_CONFIG)
|
|
1034
|
+
except Exception:
|
|
1035
|
+
return None
|
|
1036
|
+
if raw is None:
|
|
1037
|
+
return None
|
|
1038
|
+
try:
|
|
1039
|
+
data = json.loads(raw)
|
|
1040
|
+
except (TypeError, ValueError):
|
|
1041
|
+
return None
|
|
1042
|
+
return data if isinstance(data, dict) else None
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
def get_smtp_config() -> Optional[Dict[str, Any]]:
|
|
1046
|
+
"""DB 中的 SMTP 配置;「已启用且必填项齐全」才返回 dict,否则 None。
|
|
1047
|
+
|
|
1048
|
+
返回结构:{enabled, host, port, security, username, password, from_addr}。
|
|
1049
|
+
email 通知渠道以此为总开关(设置页未配置 = 功能不存在)。
|
|
1050
|
+
"""
|
|
1051
|
+
try:
|
|
1052
|
+
raw = get_setting(SETTING_SMTP_CONFIG)
|
|
1053
|
+
except Exception:
|
|
1054
|
+
return None
|
|
1055
|
+
if raw is None:
|
|
1056
|
+
return None
|
|
1057
|
+
try:
|
|
1058
|
+
data = json.loads(raw)
|
|
1059
|
+
except (TypeError, ValueError):
|
|
1060
|
+
return None
|
|
1061
|
+
if not isinstance(data, dict) or not data.get("enabled"):
|
|
1062
|
+
return None
|
|
1063
|
+
if not (data.get("host") and data.get("from_addr")):
|
|
1064
|
+
return None
|
|
1065
|
+
return data
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
# ---------------------------------------------------------------------------
|
|
1069
|
+
# UIPipelines(界面定义的 sql/procedure/http/python 任务)
|
|
1070
|
+
# ---------------------------------------------------------------------------
|
|
1071
|
+
|
|
1072
|
+
_UI_PIPELINE_FIELDS = (
|
|
1073
|
+
"name",
|
|
1074
|
+
"description",
|
|
1075
|
+
"task_type",
|
|
1076
|
+
"sql_text",
|
|
1077
|
+
"params_json",
|
|
1078
|
+
"datasource",
|
|
1079
|
+
"credential",
|
|
1080
|
+
"request_json",
|
|
1081
|
+
"param_defs_json",
|
|
1082
|
+
"cron",
|
|
1083
|
+
"schedule_json",
|
|
1084
|
+
"timeout_seconds",
|
|
1085
|
+
"retries",
|
|
1086
|
+
"retry_delay",
|
|
1087
|
+
"concurrency",
|
|
1088
|
+
"enabled",
|
|
1089
|
+
"notify_enabled",
|
|
1090
|
+
"notify_webhook",
|
|
1091
|
+
"notify_format",
|
|
1092
|
+
"notify_template",
|
|
1093
|
+
"notify_empty_policy",
|
|
1094
|
+
"notify_image_enabled",
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def list_ui_pipelines() -> List[models.UIPipeline]:
|
|
1099
|
+
with SessionLocal() as db:
|
|
1100
|
+
return (
|
|
1101
|
+
db.query(models.UIPipeline)
|
|
1102
|
+
.order_by(models.UIPipeline.id.asc())
|
|
1103
|
+
.all()
|
|
1104
|
+
)
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def get_ui_pipeline(pipeline_id: str) -> Optional[models.UIPipeline]:
|
|
1108
|
+
with SessionLocal() as db:
|
|
1109
|
+
return db.get(models.UIPipeline, pipeline_id)
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
def create_ui_pipeline(fields: Dict[str, Any]) -> models.UIPipeline:
|
|
1113
|
+
pipeline_id = fields["id"]
|
|
1114
|
+
fields = {k: v for k, v in fields.items() if k in _UI_PIPELINE_FIELDS}
|
|
1115
|
+
with SessionLocal() as db:
|
|
1116
|
+
row = models.UIPipeline(id=pipeline_id, **fields)
|
|
1117
|
+
db.add(row)
|
|
1118
|
+
db.commit()
|
|
1119
|
+
db.refresh(row)
|
|
1120
|
+
return row
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def update_ui_pipeline(
|
|
1124
|
+
pipeline_id: str, fields: Dict[str, Any]
|
|
1125
|
+
) -> Optional[models.UIPipeline]:
|
|
1126
|
+
fields = {k: v for k, v in fields.items() if k in _UI_PIPELINE_FIELDS}
|
|
1127
|
+
with SessionLocal() as db:
|
|
1128
|
+
row = db.get(models.UIPipeline, pipeline_id)
|
|
1129
|
+
if row is None:
|
|
1130
|
+
return None
|
|
1131
|
+
for key, value in fields.items():
|
|
1132
|
+
setattr(row, key, value)
|
|
1133
|
+
row.updated_at = datetime.now()
|
|
1134
|
+
db.commit()
|
|
1135
|
+
db.refresh(row)
|
|
1136
|
+
return row
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def delete_ui_pipeline(pipeline_id: str) -> bool:
|
|
1140
|
+
with SessionLocal() as db:
|
|
1141
|
+
deleted = (
|
|
1142
|
+
db.query(models.UIPipeline)
|
|
1143
|
+
.filter(models.UIPipeline.id == pipeline_id)
|
|
1144
|
+
.delete(synchronize_session=False)
|
|
1145
|
+
)
|
|
1146
|
+
db.commit()
|
|
1147
|
+
return deleted > 0
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
# ---------------------------------------------------------------------------
|
|
1151
|
+
# ScheduleExceptions(停机日历:指定日期区间跳过定时触发)
|
|
1152
|
+
# ---------------------------------------------------------------------------
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def list_schedule_exceptions() -> List[models.ScheduleException]:
|
|
1156
|
+
with SessionLocal() as db:
|
|
1157
|
+
return (
|
|
1158
|
+
db.query(models.ScheduleException)
|
|
1159
|
+
.order_by(models.ScheduleException.start_date.desc(), models.ScheduleException.id.desc())
|
|
1160
|
+
.all()
|
|
1161
|
+
)
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def get_schedule_exception(exception_id: int) -> Optional[models.ScheduleException]:
|
|
1165
|
+
with SessionLocal() as db:
|
|
1166
|
+
return db.get(models.ScheduleException, exception_id)
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
def create_schedule_exception(fields: Dict[str, Any]) -> models.ScheduleException:
|
|
1170
|
+
with SessionLocal() as db:
|
|
1171
|
+
row = models.ScheduleException(**fields)
|
|
1172
|
+
db.add(row)
|
|
1173
|
+
db.commit()
|
|
1174
|
+
db.refresh(row)
|
|
1175
|
+
return row
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def update_schedule_exception(
|
|
1179
|
+
exception_id: int, fields: Dict[str, Any]
|
|
1180
|
+
) -> Optional[models.ScheduleException]:
|
|
1181
|
+
with SessionLocal() as db:
|
|
1182
|
+
row = db.get(models.ScheduleException, exception_id)
|
|
1183
|
+
if row is None:
|
|
1184
|
+
return None
|
|
1185
|
+
for key, value in fields.items():
|
|
1186
|
+
setattr(row, key, value)
|
|
1187
|
+
db.commit()
|
|
1188
|
+
db.refresh(row)
|
|
1189
|
+
return row
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def delete_schedule_exception(exception_id: int) -> bool:
|
|
1193
|
+
with SessionLocal() as db:
|
|
1194
|
+
deleted = (
|
|
1195
|
+
db.query(models.ScheduleException)
|
|
1196
|
+
.filter(models.ScheduleException.id == exception_id)
|
|
1197
|
+
.delete(synchronize_session=False)
|
|
1198
|
+
)
|
|
1199
|
+
db.commit()
|
|
1200
|
+
return deleted > 0
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
def find_downtime_exception(
|
|
1204
|
+
pipeline_id: str, day
|
|
1205
|
+
) -> Optional[models.ScheduleException]:
|
|
1206
|
+
"""查某任务在某天是否落在停机日区间内,命中返回第一条(区间最早创建优先)。
|
|
1207
|
+
|
|
1208
|
+
scope=all 直接命中;scope=selected 时按 pipeline_ids JSON 列表判断。
|
|
1209
|
+
无命中返回 None(含当天无任何停机记录的情况)。
|
|
1210
|
+
"""
|
|
1211
|
+
with SessionLocal() as db:
|
|
1212
|
+
rows = (
|
|
1213
|
+
db.query(models.ScheduleException)
|
|
1214
|
+
.filter(
|
|
1215
|
+
models.ScheduleException.start_date <= day,
|
|
1216
|
+
models.ScheduleException.end_date >= day,
|
|
1217
|
+
)
|
|
1218
|
+
.order_by(models.ScheduleException.start_date)
|
|
1219
|
+
.all()
|
|
1220
|
+
)
|
|
1221
|
+
|
|
1222
|
+
for row in rows:
|
|
1223
|
+
if row.scope == "selected":
|
|
1224
|
+
try:
|
|
1225
|
+
ids = json.loads(row.pipeline_ids) if row.pipeline_ids else []
|
|
1226
|
+
except (TypeError, ValueError):
|
|
1227
|
+
ids = []
|
|
1228
|
+
if pipeline_id not in ids:
|
|
1229
|
+
continue
|
|
1230
|
+
return row
|
|
1231
|
+
return None
|