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,985 @@
1
+ """HTTP API 请求任务执行器(UI 任务使用)。
2
+
3
+ 一条链路贯穿「界面预览 / 测试请求 / 定时执行」:解析请求规格(``request_json``)
4
+ → 渲染 ``${变量}`` → 应用命名凭证 → 发送 → 成功判定 → 组装任务输出。
5
+ 测试端点与任务执行复用同一套构造/发送/校验函数(沿用 ADR-9「测试与执行
6
+ 同一条转译链」,测得过 = 跑起来就是同一个行为)。
7
+
8
+ 凭证不落库:任务只存凭证**名称**,真实密钥在配置文件 ``api_credentials`` 段,
9
+ 输出/日志/错误里统一脱敏(Authorization、``secret=true`` 的 header、
10
+ 放在 query 里的 api_key 一律替换为 ``***``)。
11
+
12
+ 依赖:核心依赖 httpx(零新增)。不支持的场景(文件上传、分页轮询、cookie
13
+ 会话、OAuth2 授权码/refresh、代理)明确不做,见文档「HTTP 任务能力边界」。
14
+ """
15
+
16
+ import json
17
+ import logging
18
+ import re
19
+ import threading
20
+ import time
21
+ from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple
22
+
23
+ import httpx
24
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
25
+
26
+ from flowdeck.config import (
27
+ ApiCredentialSpec,
28
+ ApiKeyCredential,
29
+ BasicCredential,
30
+ BearerCredential,
31
+ OAuth2ClientCredentials,
32
+ settings,
33
+ )
34
+ from flowdeck.tasks.timevars import render_vars
35
+
36
+ _logger = logging.getLogger(__name__)
37
+
38
+ REDACTED = "***"
39
+ """脱敏占位符(输出、日志、错误里一律用它替换密钥)"""
40
+
41
+ DEFAULT_TIMEOUT_SECONDS = 30.0
42
+ TOKEN_CACHE_SAFETY_SECONDS = 60
43
+ """OAuth2 token 提前 60 秒过期(避开边界时刻换到刚失效的 token)"""
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # 请求规格(request_json 的 schema)
48
+ # ---------------------------------------------------------------------------
49
+
50
+
51
+ class KVItem(BaseModel):
52
+ """键值对条目(query / headers / form / multipart 共用)。"""
53
+
54
+ key: str = ""
55
+ value: str = ""
56
+ enabled: bool = True
57
+ secret: bool = False
58
+ """标记为密钥:输出与日志里的值一律脱敏"""
59
+
60
+ model_config = ConfigDict(extra="forbid")
61
+
62
+
63
+ class AuthSpec(BaseModel):
64
+ """认证方式:none(无认证)/ credential(使用任务字段指定的命名凭证)。"""
65
+
66
+ type: Literal["none", "credential"] = "none"
67
+
68
+ model_config = ConfigDict(extra="forbid")
69
+
70
+
71
+ class BodySpec(BaseModel):
72
+ """请求体:按 mode 切换具体内容。"""
73
+
74
+ mode: Literal["none", "json", "form", "multipart", "text"] = "none"
75
+ json_text: str = Field(default="", alias="json")
76
+ """json 模式:JSON 文本(支持 ${变量},保存/预览时做语法校验)"""
77
+ form: List[KVItem] = Field(default_factory=list)
78
+ multipart: List[KVItem] = Field(default_factory=list)
79
+ text: str = ""
80
+ content_type: Optional[str] = None
81
+ """text 模式的 Content-Type(缺省 text/plain)"""
82
+
83
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
84
+ """JSON 键名沿用 ``json``(前端契约),Python 侧用 ``json_text``
85
+ 避免遮蔽 ``BaseModel.json()``;存库与下发时按别名序列化"""
86
+
87
+
88
+ class OptionsSpec(BaseModel):
89
+ """发送选项。"""
90
+
91
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
92
+ verify_tls: bool = True
93
+ follow_redirects: bool = True
94
+ max_redirects: int = 5
95
+
96
+ model_config = ConfigDict(extra="forbid")
97
+
98
+
99
+ class JsonCheck(BaseModel):
100
+ """一条 JSON 响应断言(路径为自写点路径,不引 jsonpath 依赖)。"""
101
+
102
+ path: str = "$"
103
+ op: Literal["exists", "equals", "not_equals", "contains", "regex", "gt", "lt"] = "equals"
104
+ value: Optional[str] = None
105
+ enabled: bool = True
106
+
107
+ model_config = ConfigDict(extra="forbid")
108
+
109
+
110
+ class VerifySpec(BaseModel):
111
+ """成功判定:状态码范围 + JSON 断言,任一不过即 run FAILED。"""
112
+
113
+ status_codes: str = "200-299"
114
+ json_checks: List[JsonCheck] = Field(default_factory=list)
115
+
116
+ model_config = ConfigDict(extra="forbid")
117
+
118
+
119
+ class ResponseSpec(BaseModel):
120
+ """响应留档策略。"""
121
+
122
+ truncate_kb: int = 16
123
+ capture_headers: List[str] = Field(default_factory=list)
124
+ store_body: Literal["json", "text", "none"] = "json"
125
+
126
+ model_config = ConfigDict(extra="forbid")
127
+
128
+
129
+ class HttpRequestSpec(BaseModel):
130
+ """整个请求规格(``request_json`` 列的 schema)。"""
131
+
132
+ version: int = 1
133
+ method: Literal["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"] = "GET"
134
+ url: str = ""
135
+ query: List[KVItem] = Field(default_factory=list)
136
+ headers: List[KVItem] = Field(default_factory=list)
137
+ auth: AuthSpec = Field(default_factory=AuthSpec)
138
+ body: BodySpec = Field(default_factory=BodySpec)
139
+ options: OptionsSpec = Field(default_factory=OptionsSpec)
140
+ verify: VerifySpec = Field(default_factory=VerifySpec)
141
+ response: ResponseSpec = Field(default_factory=ResponseSpec)
142
+
143
+ model_config = ConfigDict(extra="forbid")
144
+
145
+
146
+ def validation_error_summary(exc: ValidationError) -> str:
147
+ """把 pydantic 校验错误压成一行摘要(API 层 422 详情用)。
148
+
149
+ ui_pipelines / ui_task_tools 路由与 parse_request_spec 共用,
150
+ 保证四类任务的「配置无效」报错格式一致。
151
+ """
152
+ first = exc.errors()[0] if exc.errors() else {}
153
+ loc = ".".join(str(p) for p in first.get("loc", ()))
154
+ msg = first.get("msg", "格式错误")
155
+ return f"{loc}: {msg}" if loc else str(msg)
156
+
157
+
158
+ def parse_request_spec(raw: Optional[str]) -> Optional[HttpRequestSpec]:
159
+ """解析 ``request_json`` 列 → HttpRequestSpec;非法时抛 ValueError(中文)。
160
+
161
+ 空值返回 None(非 http 任务无需请求规格)。
162
+ """
163
+ if not raw or not raw.strip():
164
+ return None
165
+ try:
166
+ data = json.loads(raw)
167
+ except (TypeError, ValueError) as exc:
168
+ raise ValueError(f"请求配置 JSON 无效: {exc}") from exc
169
+ if not isinstance(data, dict):
170
+ raise ValueError("请求配置必须是 JSON 对象")
171
+ try:
172
+ return HttpRequestSpec.model_validate(data)
173
+ except ValidationError as exc:
174
+ raise ValueError(f"请求配置无效({validation_error_summary(exc)})") from exc
175
+
176
+
177
+ def parse_status_codes(raw: str) -> List[Tuple[int, int]]:
178
+ """``"200-299"`` / ``"200,201"`` → 区间列表;非法时抛 ValueError。"""
179
+ ranges: List[Tuple[int, int]] = []
180
+ for part in (raw or "").split(","):
181
+ part = part.strip()
182
+ if not part:
183
+ continue
184
+ try:
185
+ if "-" in part:
186
+ lo_text, _, hi_text = part.partition("-")
187
+ lo, hi = int(lo_text.strip()), int(hi_text.strip())
188
+ else:
189
+ lo = hi = int(part)
190
+ except ValueError as exc:
191
+ raise ValueError(
192
+ f"状态码范围 `{part}` 无效(示例:200-299 或 200,204)"
193
+ ) from exc
194
+ if not (100 <= lo <= hi <= 599):
195
+ raise ValueError(f"状态码范围 `{part}` 超出 100-599")
196
+ ranges.append((lo, hi))
197
+
198
+ if not ranges:
199
+ raise ValueError("状态码范围不能为空(示例:200-299)")
200
+ return ranges
201
+
202
+
203
+ def validate_request_spec(spec: HttpRequestSpec, credential_name: Optional[str]) -> None:
204
+ """保存与注册前的规格校验(不通过抛 ValueError,API 层转 422)。"""
205
+ if not (spec.url or "").strip():
206
+ raise ValueError("请求 URL 不能为空")
207
+ url = spec.url.strip()
208
+ if "://" not in url:
209
+ raise ValueError("请求 URL 必须以 http:// 或 https:// 开头")
210
+ scheme = url.split("://", 1)[0].lower()
211
+ if scheme not in ("http", "https"):
212
+ raise ValueError(f"请求 URL 的协议 `{scheme}` 不受支持(仅 http/https)")
213
+
214
+ parse_status_codes(spec.verify.status_codes)
215
+
216
+ if spec.body.mode == "json" and (spec.body.json_text or "").strip():
217
+ try:
218
+ json.loads(spec.body.json_text)
219
+ except (TypeError, ValueError) as exc:
220
+ raise ValueError(f"请求体 JSON 无效: {exc}") from exc
221
+ # 变量渲染后仍是合法 JSON 才能发送;把占位符换成 0 先试一次
222
+ probe = re.sub(r"\$\{[A-Za-z_][A-Za-z0-9_]*\}", "0", spec.body.json_text)
223
+ try:
224
+ json.loads(probe)
225
+ except (TypeError, ValueError):
226
+ raise ValueError(
227
+ "请求体 JSON 里的 ${变量} 必须整体处于字符串值中"
228
+ "(如 \"{\\\"date\\\": \\\"${data_date}\\\"}\")"
229
+ ) from None
230
+
231
+ for index, check in enumerate(spec.verify.json_checks, 1):
232
+ if not (check.path or "").strip():
233
+ raise ValueError(f"第 {index} 条响应断言缺少路径")
234
+ if not (check.path or "").strip().startswith("$"):
235
+ raise ValueError(
236
+ f"第 {index} 条响应断言的路径应以 $ 开头(如 $.code)"
237
+ )
238
+ if check.enabled and check.op in ("equals", "not_equals", "contains", "regex", "gt", "lt"):
239
+ if check.value is None:
240
+ raise ValueError(f"第 {index} 条响应断言缺少比较值")
241
+
242
+ if spec.auth.type == "credential" and not (credential_name or "").strip():
243
+ raise ValueError("认证方式为「使用凭证」时必须选择凭证")
244
+ if spec.options.timeout_seconds <= 0:
245
+ raise ValueError("超时时间必须大于 0")
246
+ if spec.response.truncate_kb < 0:
247
+ raise ValueError("响应体保留上限不能为负数")
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # 凭证解析与摘要(摘要绝不包含密文)
252
+ # ---------------------------------------------------------------------------
253
+
254
+
255
+ def get_credential(name: Optional[str]) -> Optional[ApiCredentialSpec]:
256
+ """按名称取凭证定义;未定义时抛 ValueError(中文,指向配置文件)。"""
257
+ if not (name or "").strip():
258
+ return None
259
+ cred = settings.api_credentials.get(name)
260
+ if cred is None:
261
+ raise ValueError(
262
+ f"凭证 `{name}` 未在配置文件 api_credentials 段定义"
263
+ )
264
+ return cred
265
+
266
+
267
+ def describe_credential(name: str, cred: ApiCredentialSpec) -> Dict[str, Any]:
268
+ """凭证摘要(名称 + 类型 + 非密文信息),用于前端下拉展示。"""
269
+ info: Dict[str, Any] = {"name": name, "type": cred.type}
270
+ if isinstance(cred, BasicCredential):
271
+ info["summary"] = f"用户名 {cred.username}"
272
+ elif isinstance(cred, BearerCredential):
273
+ info["summary"] = "静态 Token"
274
+ elif isinstance(cred, ApiKeyCredential):
275
+ location = "请求头" if cred.in_ == "header" else "查询参数"
276
+ info["summary"] = f"{location} {cred.key}"
277
+ elif isinstance(cred, OAuth2ClientCredentials):
278
+ info["summary"] = f"token_url {cred.token_url}"
279
+ info["token_url"] = cred.token_url
280
+ return info
281
+
282
+
283
+ def credential_summaries() -> List[Dict[str, Any]]:
284
+ """全部凭证摘要(按名称排序),接口直接下发前端。"""
285
+ return [
286
+ describe_credential(name, cred)
287
+ for name, cred in sorted(settings.api_credentials.items())
288
+ ]
289
+
290
+
291
+ # ---------------------------------------------------------------------------
292
+ # OAuth2 token 缓存(进程级共享,带锁;同一凭证并发只换一次 token)
293
+ # ---------------------------------------------------------------------------
294
+
295
+ _token_cache: Dict[str, Tuple[str, float]] = {}
296
+ _token_lock = threading.Lock()
297
+
298
+
299
+ def _token_cache_key(cred: OAuth2ClientCredentials) -> str:
300
+ return f"{cred.token_url}|{cred.client_id}|{cred.scope or ''}"
301
+
302
+
303
+ def _fetch_oauth_token(cred: OAuth2ClientCredentials) -> str:
304
+ """换 token(命中缓存直接返回);失败抛 ValueError(中文)。"""
305
+ key = _token_cache_key(cred)
306
+ with _token_lock:
307
+ cached = _token_cache.get(key)
308
+ if cached and cached[1] > time.time():
309
+ return cached[0]
310
+
311
+ try:
312
+ response = httpx.post(
313
+ cred.token_url,
314
+ data={
315
+ "grant_type": "client_credentials",
316
+ **({"scope": cred.scope} if cred.scope else {}),
317
+ },
318
+ auth=httpx.BasicAuth(cred.client_id, cred.client_secret),
319
+ timeout=DEFAULT_TIMEOUT_SECONDS,
320
+ )
321
+ except httpx.HTTPError as exc:
322
+ raise ValueError(
323
+ f"OAuth2 换 token 失败:{_translate_http_error(exc, DEFAULT_TIMEOUT_SECONDS)}"
324
+ ) from exc
325
+
326
+ if response.status_code >= 400:
327
+ raise ValueError(
328
+ f"OAuth2 换 token 失败:HTTP {response.status_code} "
329
+ f"{_truncate_text(response.text, 500)}"
330
+ )
331
+ try:
332
+ payload = response.json()
333
+ except ValueError as exc:
334
+ raise ValueError(
335
+ "OAuth2 换 token 失败:token 接口返回的不是 JSON"
336
+ ) from exc
337
+
338
+ token = payload.get("access_token")
339
+ if not token:
340
+ raise ValueError("OAuth2 换 token 失败:响应里没有 access_token 字段")
341
+
342
+ try:
343
+ expires_in = float(payload.get("expires_in") or 300)
344
+ except (TypeError, ValueError):
345
+ expires_in = 300.0
346
+ ttl = max(expires_in - TOKEN_CACHE_SAFETY_SECONDS, 30.0)
347
+ _token_cache[key] = (str(token), time.time() + ttl)
348
+ _logger.info("OAuth2 token acquired from %s (ttl %.0fs)", cred.token_url, ttl)
349
+ return str(token)
350
+
351
+
352
+ def clear_token_cache() -> None:
353
+ """清空 token 缓存(测试用)。"""
354
+ with _token_lock:
355
+ _token_cache.clear()
356
+
357
+
358
+ # ---------------------------------------------------------------------------
359
+ # JSON 点路径解析与断言
360
+ # ---------------------------------------------------------------------------
361
+
362
+
363
+ def resolve_json_path(data: Any, path: str) -> Tuple[bool, Any]:
364
+ """自写点路径取值:``$.a.b[0].c``;不存在返回 (False, None)。"""
365
+ if not path.startswith("$"):
366
+ raise ValueError(f"断言路径 `{path}` 应以 $ 开头(如 $.code)")
367
+
368
+ current = data
369
+ i = 1
370
+ while i < len(path):
371
+ char = path[i]
372
+ if char == ".":
373
+ i += 1
374
+ j = i
375
+ while j < len(path) and path[j] not in ".[":
376
+ j += 1
377
+ key = path[i:j]
378
+ if key == "" or not isinstance(current, dict) or key not in current:
379
+ return False, None
380
+ current = current[key]
381
+ i = j
382
+ elif char == "[":
383
+ j = path.find("]", i)
384
+ if j == -1:
385
+ raise ValueError(f"断言路径 `{path}` 缺少 ]")
386
+ index_text = path[i + 1 : j].strip()
387
+ if not index_text.isdigit():
388
+ raise ValueError(f"断言路径 `{path}` 的数组下标必须是数字")
389
+ index = int(index_text)
390
+ if not isinstance(current, list) or index >= len(current):
391
+ return False, None
392
+ current = current[index]
393
+ i = j + 1
394
+ else:
395
+ raise ValueError(f"断言路径 `{path}` 在第 {i + 1} 个字符处无法解析")
396
+ return True, current
397
+
398
+
399
+ def _check_text(actual: Any) -> str:
400
+ if isinstance(actual, bool):
401
+ return "true" if actual else "false"
402
+ if actual is None:
403
+ return "null"
404
+ if isinstance(actual, (dict, list)):
405
+ return json.dumps(actual, ensure_ascii=False)
406
+ return str(actual)
407
+
408
+
409
+ def _run_json_check(payload: Any, check: JsonCheck) -> Dict[str, Any]:
410
+ """执行单条断言,返回 {path, op, expected, actual, passed, error}。"""
411
+ result: Dict[str, Any] = {
412
+ "path": check.path,
413
+ "op": check.op,
414
+ "expected": check.value,
415
+ "actual": None,
416
+ "passed": False,
417
+ "error": None,
418
+ }
419
+ try:
420
+ found, actual = resolve_json_path(payload, check.path)
421
+ except ValueError as exc:
422
+ result["error"] = str(exc)
423
+ return result
424
+
425
+ result["actual"] = _check_text(actual) if found else None
426
+
427
+ if check.op == "exists":
428
+ result["passed"] = found
429
+ if not found:
430
+ result["error"] = f"{check.path} 不存在"
431
+ return result
432
+
433
+ if not found:
434
+ result["error"] = f"{check.path} 不存在"
435
+ return result
436
+
437
+ expected = check.value if check.value is not None else ""
438
+ if check.op == "equals":
439
+ result["passed"] = _check_text(actual) == expected
440
+ elif check.op == "not_equals":
441
+ result["passed"] = _check_text(actual) != expected
442
+ elif check.op == "contains":
443
+ result["passed"] = expected in _check_text(actual)
444
+ elif check.op == "regex":
445
+ try:
446
+ result["passed"] = re.search(expected, _check_text(actual)) is not None
447
+ except re.error as exc:
448
+ result["error"] = f"正则表达式无效: {exc}"
449
+ return result
450
+ elif check.op in ("gt", "lt"):
451
+ try:
452
+ left, right = float(actual), float(expected)
453
+ except (TypeError, ValueError):
454
+ result["error"] = f"比较大小需要数字(实际 `{_check_text(actual)}`)"
455
+ return result
456
+ result["passed"] = left > right if check.op == "gt" else left < right
457
+
458
+ if not result["passed"] and result["error"] is None:
459
+ result["error"] = f"{check.path} 期望 {expected},实际 {_check_text(actual)}"
460
+ return result
461
+
462
+
463
+ # ---------------------------------------------------------------------------
464
+ # 错误转译与脱敏
465
+ # ---------------------------------------------------------------------------
466
+
467
+
468
+ def _truncate_text(text: Optional[str], limit: int = 500) -> str:
469
+ text = text or ""
470
+ return text if len(text) <= limit else text[:limit] + "…"
471
+
472
+
473
+ def _translate_http_error(exc: Exception, timeout_seconds: float) -> str:
474
+ """把 httpx 异常转成可操作的中文提示(与执行同处一文件,文案统一)。"""
475
+ if isinstance(exc, httpx.TimeoutException):
476
+ return f"请求超时(超过 {timeout_seconds:g} 秒未完成)"
477
+ if isinstance(exc, httpx.TooManyRedirects):
478
+ return "重定向次数超过上限(可在请求选项里调大或关闭跟随重定向)"
479
+ if isinstance(exc, httpx.UnsupportedProtocol):
480
+ return f"URL 协议不受支持(仅支持 http/https):{exc}"
481
+ if isinstance(exc, httpx.ConnectError):
482
+ detail = str(exc)
483
+ lowered = detail.lower()
484
+ if "getaddrinfo" in lowered or "name or service not known" in lowered or "nodename nor servname" in lowered:
485
+ return f"无法解析主机名(请检查域名/网络/DNS):{_truncate_text(detail, 300)}"
486
+ if "refused" in lowered or "10061" in lowered:
487
+ return f"连接被拒绝(目标主机端口无服务监听或防火墙拦截):{_truncate_text(detail, 300)}"
488
+ if "certificate" in lowered or "ssl" in lowered or "tls" in lowered:
489
+ return (
490
+ "TLS 证书校验失败(自签或内网证书可在请求选项里关闭 verify_tls):"
491
+ f"{_truncate_text(detail, 300)}"
492
+ )
493
+ return f"无法建立连接:{_truncate_text(detail, 300)}"
494
+ # 其余 httpx.HTTPError 与非 httpx 异常共用同一兜底文案
495
+ return f"请求失败({type(exc).__name__}):{_truncate_text(str(exc), 300)}"
496
+
497
+
498
+ def _redact_headers(headers: Dict[str, str], secret_keys: Sequence[str]) -> Dict[str, str]:
499
+ """脱敏响应/请求头:Authorization 恒脱敏,另有任务标记的 secret 头。"""
500
+ secret_lower = {k.lower() for k in secret_keys}
501
+ redacted: Dict[str, str] = {}
502
+ for key, value in headers.items():
503
+ if key.lower() == "authorization" or key.lower() in secret_lower:
504
+ redacted[key] = REDACTED
505
+ else:
506
+ redacted[key] = value
507
+ return redacted
508
+
509
+
510
+ # ---------------------------------------------------------------------------
511
+ # 请求构造(执行与预览/测试共用)
512
+ # ---------------------------------------------------------------------------
513
+
514
+
515
+ class RenderedRequest(BaseModel):
516
+ """渲染后的请求(发送与预览共用同一份结构)。"""
517
+
518
+ model_config = ConfigDict(arbitrary_types_allowed=True)
519
+
520
+ method: str
521
+ url: str
522
+ headers: Dict[str, str]
523
+ query: Dict[str, str]
524
+ body_mode: str
525
+ body_text: Optional[str] = None
526
+ json_body: Any = None
527
+ form: List[Tuple[str, str]] = Field(default_factory=list)
528
+ multipart: List[Tuple[str, str]] = Field(default_factory=list)
529
+ content_type: Optional[str] = None
530
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
531
+ verify_tls: bool = True
532
+ follow_redirects: bool = True
533
+ max_redirects: int = 5
534
+ auth_mode: str = "none"
535
+
536
+
537
+ def _render_kv(items: Sequence[KVItem], values: Dict[str, str], names: Sequence[str]) -> List[KVItem]:
538
+ rendered: List[KVItem] = []
539
+ for item in items:
540
+ if not item.enabled or not item.key:
541
+ continue
542
+ rendered.append(
543
+ KVItem(
544
+ key=render_vars(item.key, values, names),
545
+ value=render_vars(item.value, values, names),
546
+ enabled=True,
547
+ secret=item.secret,
548
+ )
549
+ )
550
+ return rendered
551
+
552
+
553
+ def render_http_request(
554
+ spec: HttpRequestSpec,
555
+ values: Dict[str, str],
556
+ var_names: Optional[Sequence[str]] = None,
557
+ credential_name: Optional[str] = None,
558
+ redact: bool = False,
559
+ ) -> RenderedRequest:
560
+ """渲染请求规格 → RenderedRequest(不发送)。
561
+
562
+ ``redact=True`` 时把 Authorization / ``secret=true`` 的值替换为 ``***``
563
+ (预览与日志用;实际发送用 redact=False 的那一份)。
564
+ """
565
+ names = list(var_names or [])
566
+ headers: Dict[str, str] = {}
567
+ secret_headers: List[str] = []
568
+ for item in _render_kv(spec.headers, values, names):
569
+ headers[item.key] = item.value
570
+ if item.secret:
571
+ secret_headers.append(item.key)
572
+
573
+ query: Dict[str, str] = {}
574
+ secret_query: List[str] = []
575
+ for item in _render_kv(spec.query, values, names):
576
+ query[item.key] = item.value
577
+ if item.secret:
578
+ secret_query.append(item.key)
579
+
580
+ # 命名凭证:先展开成请求头/查询参数(含 secret 标记),再定稿 RenderedRequest
581
+ # (pydantic 校验会拷贝 dict,构造后再改本地 dict 不会生效)
582
+ if spec.auth.type == "credential" and credential_name:
583
+ cred = get_credential(credential_name)
584
+ if isinstance(cred, ApiKeyCredential):
585
+ if cred.in_ == "header":
586
+ headers[cred.key] = cred.value
587
+ secret_headers.append(cred.key)
588
+ else:
589
+ query[cred.key] = cred.value
590
+ secret_query.append(cred.key)
591
+
592
+ rendered = RenderedRequest(
593
+ method=spec.method,
594
+ url=render_vars(spec.url, values, names),
595
+ headers=headers,
596
+ query=query,
597
+ body_mode=spec.body.mode,
598
+ timeout_seconds=spec.options.timeout_seconds,
599
+ verify_tls=spec.options.verify_tls,
600
+ follow_redirects=spec.options.follow_redirects,
601
+ max_redirects=spec.options.max_redirects,
602
+ auth_mode="credential" if spec.auth.type == "credential" else "none",
603
+ )
604
+
605
+ if spec.body.mode == "json":
606
+ rendered.body_text = render_vars(spec.body.json_text, values, names)
607
+ elif spec.body.mode == "text":
608
+ rendered.body_text = render_vars(spec.body.text, values, names)
609
+ rendered.content_type = spec.body.content_type or "text/plain"
610
+ elif spec.body.mode == "form":
611
+ rendered.form = [
612
+ (item.key, item.value) for item in _render_kv(spec.body.form, values, names)
613
+ ]
614
+ elif spec.body.mode == "multipart":
615
+ rendered.multipart = [
616
+ (item.key, item.value)
617
+ for item in _render_kv(spec.body.multipart, values, names)
618
+ ]
619
+
620
+ if redact:
621
+ rendered.headers = _redact_headers(rendered.headers, secret_headers)
622
+ rendered.query = _redact_headers(rendered.query, secret_query)
623
+ if rendered.body_text:
624
+ rendered.body_text = _redact_body(rendered.body_text)
625
+ return rendered
626
+
627
+
628
+ def _redact_body(text: str) -> str:
629
+ """粗粒度脱敏请求体里的密文样式键值(尽力而为,非保证)。"""
630
+ return re.sub(
631
+ r'("(?:password|passwd|secret|token|client_secret|api_key)"\s*:\s*)"[^"]*"',
632
+ rf"\1\"{REDACTED}\"",
633
+ text,
634
+ flags=re.IGNORECASE,
635
+ )
636
+
637
+
638
+ def _new_client(request: RenderedRequest) -> httpx.Client:
639
+ """按任务配置建客户端:TLS 校验 / 重定向策略是 Client 级参数。"""
640
+ return httpx.Client(
641
+ verify=request.verify_tls,
642
+ follow_redirects=request.follow_redirects,
643
+ max_redirects=request.max_redirects,
644
+ )
645
+
646
+
647
+ def _pairs_to_mapping(pairs: Sequence[Tuple[str, str]]) -> Dict[str, Any]:
648
+ """``[(key, value)]`` → ``{key: value}``。
649
+
650
+ httpx 0.28 只接受 Mapping(旧版可传列表),重复键累成列表以保留多次提交
651
+ 的语义(urlencode 会展开 list 值)。
652
+ """
653
+ mapping: Dict[str, Any] = {}
654
+ for key, value in pairs:
655
+ if key in mapping:
656
+ if isinstance(mapping[key], list):
657
+ mapping[key].append(value)
658
+ else:
659
+ mapping[key] = [mapping[key], value]
660
+ else:
661
+ mapping[key] = value
662
+ return mapping
663
+
664
+
665
+ def _request_kwargs(request: RenderedRequest, auth: Optional[httpx.Auth]) -> Dict[str, Any]:
666
+ """RenderedRequest → httpx 请求参数(执行与测试共用,行为一致)。"""
667
+ kwargs: Dict[str, Any] = {
668
+ "method": request.method,
669
+ "url": request.url,
670
+ "headers": request.headers or None,
671
+ "params": request.query or None,
672
+ "timeout": request.timeout_seconds,
673
+ }
674
+ if auth is not None:
675
+ kwargs["auth"] = auth
676
+
677
+ if request.body_mode == "json" and request.body_text:
678
+ try:
679
+ kwargs["json"] = json.loads(request.body_text)
680
+ except (TypeError, ValueError) as exc:
681
+ raise ValueError(f"请求体不是合法 JSON:{exc}") from exc
682
+ elif request.body_mode == "text":
683
+ kwargs["content"] = (request.body_text or "").encode("utf-8")
684
+ kwargs["headers"] = {
685
+ **(request.headers or {}),
686
+ "Content-Type": request.content_type or "text/plain",
687
+ }
688
+ elif request.body_mode == "form" and request.form:
689
+ kwargs["data"] = _pairs_to_mapping(request.form)
690
+ elif request.body_mode == "multipart" and request.multipart:
691
+ kwargs["files"] = [(key, (None, value)) for key, value in request.multipart]
692
+
693
+ return kwargs
694
+
695
+
696
+ # ---------------------------------------------------------------------------
697
+ # 发送与成功判定
698
+ # ---------------------------------------------------------------------------
699
+
700
+
701
+ class _BearerAuth(httpx.Auth):
702
+ """Bearer 认证(httpx 0.28 起移除了 ``BearerAuth``,这里自实现)。
703
+
704
+ 走 ``auth_flow`` 而非在渲染期直接写 header:与 ``BasicAuth`` 行为一致,
705
+ 预览出的请求头里不出现真实密钥,也就不存在脱敏遗漏。
706
+ """
707
+
708
+ def __init__(self, token: str):
709
+ self.token = token
710
+
711
+ def auth_flow(self, request: httpx.Request):
712
+ if self.token:
713
+ request.headers["Authorization"] = f"Bearer {self.token}"
714
+ yield request
715
+
716
+
717
+ def _build_auth(cred: Optional[ApiCredentialSpec]) -> Optional[httpx.Auth]:
718
+ if isinstance(cred, BasicCredential):
719
+ return httpx.BasicAuth(cred.username, cred.password)
720
+ if isinstance(cred, BearerCredential):
721
+ return _BearerAuth(cred.token)
722
+ if isinstance(cred, OAuth2ClientCredentials):
723
+ return _BearerAuth(_fetch_oauth_token(cred))
724
+ return None
725
+
726
+
727
+ def _elapsed_ms(start: float) -> int:
728
+ return round((time.monotonic() - start) * 1000)
729
+
730
+
731
+ def _body_and_checks(
732
+ spec: HttpRequestSpec, response: httpx.Response
733
+ ) -> Tuple[Any, Optional[str], bool, Dict[str, Any], bool]:
734
+ """解析响应体 + 执行 JSON 断言。
735
+
736
+ 返回 ``(留档 body, 完整文本, 是否截断, verify 结果, 状态码是否通过)``;
737
+ 断言针对 **完整**响应体执行(截断只影响留档,不影响判定)。
738
+ """
739
+ limit = max(spec.response.truncate_kb, 0) * 1024
740
+ raw = response.content
741
+ full_text = response.text
742
+ truncated = limit > 0 and len(raw) > limit
743
+ text = full_text[:limit] if truncated else full_text
744
+
745
+ checks: List[Dict[str, Any]] = []
746
+ payload: Any = None
747
+ parse_error: Optional[str] = None
748
+ if text.strip():
749
+ try:
750
+ payload = json.loads(full_text)
751
+ except (TypeError, ValueError) as exc:
752
+ parse_error = f"响应体不是合法 JSON({exc})"
753
+
754
+ for check in spec.verify.json_checks:
755
+ if not check.enabled:
756
+ continue
757
+ if payload is None:
758
+ checks.append(
759
+ {
760
+ "path": check.path,
761
+ "op": check.op,
762
+ "expected": check.value,
763
+ "actual": None,
764
+ "passed": False,
765
+ "error": parse_error or "响应体为空,无法执行 JSON 断言",
766
+ }
767
+ )
768
+ continue
769
+ checks.append(_run_json_check(payload, check))
770
+
771
+ ranges = parse_status_codes(spec.verify.status_codes)
772
+ status_ok = any(lo <= response.status_code <= hi for lo, hi in ranges)
773
+ failed = [c for c in checks if not c["passed"]]
774
+
775
+ error: Optional[str] = None
776
+ if not status_ok:
777
+ error = (
778
+ f"响应状态码 {response.status_code} 不在允许范围 "
779
+ f"{spec.verify.status_codes} 内;响应摘录: {_truncate_text(text)}"
780
+ )
781
+ elif failed:
782
+ error = (
783
+ f"响应断言不通过({failed[0].get('error') or failed[0]['path']});"
784
+ f"响应摘录: {_truncate_text(text)}"
785
+ )
786
+
787
+ verify_result = {
788
+ "passed": status_ok and not failed,
789
+ "checks": checks,
790
+ "error": error,
791
+ }
792
+
793
+ if spec.response.store_body == "none":
794
+ stored: Any = None
795
+ elif spec.response.store_body == "text" or parse_error:
796
+ stored = text
797
+ else:
798
+ try:
799
+ stored = json.loads(text)
800
+ except (TypeError, ValueError):
801
+ stored = text
802
+
803
+ return stored, text, truncated, verify_result, status_ok
804
+
805
+
806
+ def _build_output(
807
+ spec: HttpRequestSpec,
808
+ request: RenderedRequest,
809
+ credential_name: Optional[str],
810
+ response: httpx.Response,
811
+ elapsed_ms: int,
812
+ stored_body: Any,
813
+ text: str,
814
+ truncated: bool,
815
+ verify_result: Dict[str, Any],
816
+ ) -> Dict[str, Any]:
817
+ """组装任务输出(落 storage,run 详情页 PrettyJson 直接可读)。"""
818
+ secret_headers = [item.key for item in spec.headers if item.secret]
819
+ secret_query = [item.key for item in spec.query if item.secret]
820
+ cred = get_credential(credential_name) if credential_name else None
821
+ if isinstance(cred, ApiKeyCredential):
822
+ if cred.in_ == "header":
823
+ secret_headers.append(cred.key)
824
+ else:
825
+ secret_query.append(cred.key)
826
+
827
+ captured = {}
828
+ # httpx 会把响应头名统一小写;按用户配置的原始大小写回填,便于对照配置
829
+ wanted = {
830
+ name.strip().lower(): name.strip()
831
+ for name in spec.response.capture_headers
832
+ if name.strip()
833
+ }
834
+ for key, value in response.headers.items():
835
+ configured = wanted.get(key.lower())
836
+ if configured:
837
+ captured[configured] = value
838
+
839
+ captured = _redact_headers(captured, secret_headers)
840
+
841
+ body_preview = request.body_text if request.body_mode in ("json", "text") else None
842
+ if request.body_mode in ("form", "multipart"):
843
+ body_preview = json.dumps(
844
+ dict(request.form or request.multipart), ensure_ascii=False
845
+ )
846
+ if body_preview:
847
+ body_preview = _truncate_text(_redact_body(body_preview), 2000)
848
+
849
+ return {
850
+ "request": {
851
+ "method": request.method,
852
+ "url": request.url,
853
+ "headers": _redact_headers(request.headers, secret_headers),
854
+ "query": _redact_headers(request.query, secret_query),
855
+ "body_preview": body_preview,
856
+ "auth": (
857
+ describe_credential(credential_name, cred).get("summary")
858
+ if cred and credential_name
859
+ else None
860
+ ),
861
+ },
862
+ "status_code": response.status_code,
863
+ "elapsed_ms": elapsed_ms,
864
+ "response_headers": captured,
865
+ "body": stored_body,
866
+ "body_bytes": len(response.content),
867
+ "body_truncated": truncated,
868
+ "verify": verify_result,
869
+ }
870
+
871
+
872
+ def execute_http_task(
873
+ spec: HttpRequestSpec,
874
+ credential_name: Optional[str],
875
+ values: Dict[str, str],
876
+ var_names: Optional[Sequence[str]] = None,
877
+ ) -> Dict[str, Any]:
878
+ """执行一次 HTTP 任务(同步阻塞,调用方负责放线程池)。
879
+
880
+ 返回任务输出 dict(见 ``_build_output``);**成功判定不通过时抛
881
+ ValueError**(error 指明失败断言/状态码 + 响应摘录),由任务框架记为
882
+ run FAILED 并触发通知链(同 SQL 任务的报错路径)。
883
+ """
884
+ request = render_http_request(spec, values, var_names, credential_name)
885
+ start = time.monotonic()
886
+ cred = get_credential(credential_name) if request.auth_mode == "credential" else None
887
+ auth = _build_auth(cred)
888
+
889
+ try:
890
+ with _new_client(request) as client:
891
+ response = client.request(**_request_kwargs(request, auth))
892
+ except httpx.HTTPError as exc:
893
+ raise ValueError(
894
+ _translate_http_error(exc, request.timeout_seconds)
895
+ ) from exc
896
+ elapsed_ms = _elapsed_ms(start)
897
+
898
+ stored_body, text, truncated, verify_result, _status_ok = _body_and_checks(
899
+ spec, response
900
+ )
901
+ output = _build_output(
902
+ spec,
903
+ request,
904
+ credential_name,
905
+ response,
906
+ elapsed_ms,
907
+ stored_body,
908
+ text,
909
+ truncated,
910
+ verify_result,
911
+ )
912
+ if not verify_result["passed"]:
913
+ raise HttpVerifyError(verify_result["error"] or "响应断言不通过", output)
914
+ return output
915
+
916
+
917
+ class HttpVerifyError(Exception):
918
+ """成功判定不通过:携带完整输出(调用方可先记日志再抛出)。"""
919
+
920
+ def __init__(self, message: str, output: Dict[str, Any]):
921
+ super().__init__(message)
922
+ self.output = output
923
+
924
+
925
+ def test_http_request(
926
+ spec: HttpRequestSpec,
927
+ credential_name: Optional[str],
928
+ values: Dict[str, str],
929
+ var_names: Optional[Sequence[str]] = None,
930
+ ) -> Dict[str, Any]:
931
+ """测试请求:真实发一次,失败也返回结果(同 test_connection 约定)。
932
+
933
+ 返回 ``{"ok": bool, "elapsed_ms": int, "error": str|None, "preview": {...},
934
+ "status_code": int|None, "output": {...}|None}``。
935
+ """
936
+ try:
937
+ request = render_http_request(spec, values, var_names, credential_name, redact=True)
938
+ except ValueError as exc:
939
+ return {
940
+ "ok": False,
941
+ "elapsed_ms": 0,
942
+ "error": str(exc),
943
+ "preview": None,
944
+ "status_code": None,
945
+ "output": None,
946
+ }
947
+
948
+ try:
949
+ output = execute_http_task(spec, credential_name, values, var_names)
950
+ return {
951
+ "ok": True,
952
+ "elapsed_ms": output["elapsed_ms"],
953
+ "error": None,
954
+ "preview": request.model_dump(),
955
+ "status_code": output["status_code"],
956
+ "output": output,
957
+ }
958
+ except HttpVerifyError as exc:
959
+ return {
960
+ "ok": False,
961
+ "elapsed_ms": exc.output.get("elapsed_ms", 0),
962
+ "error": str(exc),
963
+ "preview": request.model_dump(),
964
+ "status_code": exc.output.get("status_code"),
965
+ "output": exc.output,
966
+ }
967
+ except ValueError as exc:
968
+ return {
969
+ "ok": False,
970
+ "elapsed_ms": 0,
971
+ "error": str(exc),
972
+ "preview": request.model_dump(),
973
+ "status_code": None,
974
+ "output": None,
975
+ }
976
+ except Exception as exc: # 兜底:测试端点不应 500
977
+ _logger.warning("HTTP test request failed unexpectedly", exc_info=True)
978
+ return {
979
+ "ok": False,
980
+ "elapsed_ms": 0,
981
+ "error": _translate_http_error(exc, spec.options.timeout_seconds),
982
+ "preview": request.model_dump(),
983
+ "status_code": None,
984
+ "output": None,
985
+ }