@duanz/pi-d-reach 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/SKILL.md +480 -0
- package/fanout-defaults.example.json +33 -0
- package/package.json +52 -4
- package/plugin/index.ts +4097 -0
- package/plugin/pwa.ts +1078 -0
- package/plugin/scripts/fanout.sh +1944 -0
- package/plugin/scripts/load_key.sh +36 -0
- package/plugin/scripts/mcp_call.py +137 -0
- package/plugin/scripts/pdf2text.py +39 -0
- package/plugin/scripts/quota.py +281 -0
- package/plugin/scripts/quota_probe.py +272 -0
- package/plugin/scripts/render.mjs +234 -0
- package/plugin/scripts/route_config.py +156 -0
- package/references/channels.md +226 -0
- package/references/cn-reach.md +153 -0
- package/references/dev.md +65 -0
- package/references/finance.md +84 -0
- package/references/scrape.md +283 -0
- package/references/search.md +308 -0
- package/references/social.md +76 -0
- package/references/video.md +82 -0
- package/scripts/fanout.sh +1944 -0
- package/scripts/load_key.sh +36 -0
- package/scripts/mcp_call.py +137 -0
- package/scripts/quota.py +281 -0
- package/scripts/quota_probe.py +272 -0
- package/scripts/route_config.py +156 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""D-Reach 额度官方校准(quota probe)。
|
|
3
|
+
|
|
4
|
+
本地 quota.json 记的是「我们发过几次请求」,不是「厂商还剩多少」。
|
|
5
|
+
本脚本去各家官方接口取真实额度,写进 quota.json 的 `_official` 段,
|
|
6
|
+
不覆盖本地计数 —— 两者互为校验:本地计数漏记时,官方数字能纠回来。
|
|
7
|
+
|
|
8
|
+
quota_probe.py 校准并打印人类可读结果
|
|
9
|
+
quota_probe.py --json 机器可读
|
|
10
|
+
quota_probe.py --quiet fanout 结束时静默调用(只在异常时出声)
|
|
11
|
+
|
|
12
|
+
已确认可查(2026-10-28 实测):
|
|
13
|
+
firecrawl GET /v2/team/credit-usage → remainingCredits / planCredits / 账期
|
|
14
|
+
tinyfish MCP get_wallet → 钱包余额(search/fetch 本身 $0)
|
|
15
|
+
未开放 / 权限不足(如实记录,不猜):
|
|
16
|
+
brightdata token 无 account 读权限(/customer/balance 403)
|
|
17
|
+
exa 官方团队接口需申请 access
|
|
18
|
+
jina 只有 dashboard,无公开额度 API
|
|
19
|
+
langsearch 官方只给 token 日额度,无查询端点
|
|
20
|
+
"""
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
import urllib.request
|
|
27
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
FILE = Path(os.environ.get("D_REACH_QUOTA_FILE") or Path.home() / ".agent-reach/quota.json")
|
|
32
|
+
KEY_SH = Path(__file__).with_name("load_key.sh")
|
|
33
|
+
TIMEOUT = 12
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def key(name):
|
|
37
|
+
"""走 load_key.sh,与全技能同一条查找链(env → ~/.config/agents/env → .env)。"""
|
|
38
|
+
import subprocess
|
|
39
|
+
try:
|
|
40
|
+
out = subprocess.run(
|
|
41
|
+
["sh", str(KEY_SH), name, ""],
|
|
42
|
+
capture_output=True, text=True, timeout=8,
|
|
43
|
+
)
|
|
44
|
+
return out.stdout.strip() or None
|
|
45
|
+
except Exception:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get(url, headers):
|
|
50
|
+
req = urllib.request.Request(url, headers=headers)
|
|
51
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
|
52
|
+
return json.loads(r.read().decode("utf-8", "replace"))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def probe_firecrawl():
|
|
56
|
+
k = key("FIRECRAWL_API_KEY")
|
|
57
|
+
if not k:
|
|
58
|
+
return {"state": "no_key"}
|
|
59
|
+
d = _get("https://api.firecrawl.dev/v2/team/credit-usage",
|
|
60
|
+
{"Authorization": f"Bearer {k}"})
|
|
61
|
+
box = d.get("data") or {}
|
|
62
|
+
return {
|
|
63
|
+
"state": "ok",
|
|
64
|
+
"remaining": box.get("remainingCredits"),
|
|
65
|
+
"total": box.get("planCredits"),
|
|
66
|
+
"period_start": box.get("billingPeriodStart"),
|
|
67
|
+
"period_end": box.get("billingPeriodEnd"),
|
|
68
|
+
"source": "api:/v2/team/credit-usage",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def probe_tinyfish():
|
|
73
|
+
"""TinyFish 走 hosted MCP:initialize 拿 session,再调 get_wallet。"""
|
|
74
|
+
k = key("TINYFISH_API_KEY")
|
|
75
|
+
if not k:
|
|
76
|
+
return {"state": "no_key"}
|
|
77
|
+
url = "https://agent.tinyfish.ai/mcp"
|
|
78
|
+
|
|
79
|
+
def rpc(payload, sid=None):
|
|
80
|
+
hdr = {"Content-Type": "application/json",
|
|
81
|
+
"Accept": "application/json, text/event-stream",
|
|
82
|
+
"X-API-Key": k}
|
|
83
|
+
if sid:
|
|
84
|
+
hdr["Mcp-Session-Id"] = sid
|
|
85
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=hdr)
|
|
86
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
|
87
|
+
raw = r.read().decode("utf-8", "replace")
|
|
88
|
+
return dict(r.headers), raw
|
|
89
|
+
|
|
90
|
+
hdrs, _ = rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
|
91
|
+
"params": {"protocolVersion": "2024-11-05", "capabilities": {},
|
|
92
|
+
"clientInfo": {"name": "d-reach-probe", "version": "1"}}})
|
|
93
|
+
sid = hdrs.get("Mcp-Session-Id") or hdrs.get("mcp-session-id")
|
|
94
|
+
_, raw = rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
|
|
95
|
+
"params": {"name": "get_wallet", "arguments": {}}}, sid)
|
|
96
|
+
m = re.search(r"\{.*\}", raw, re.S)
|
|
97
|
+
if not m:
|
|
98
|
+
return {"state": "error", "error": "响应里没有 JSON"}
|
|
99
|
+
body = json.loads(m.group(0))
|
|
100
|
+
text = ""
|
|
101
|
+
for c in (body.get("result") or {}).get("content") or []:
|
|
102
|
+
if c.get("type") == "text":
|
|
103
|
+
text = c.get("text") or ""
|
|
104
|
+
break
|
|
105
|
+
try:
|
|
106
|
+
wallet = json.loads(text)
|
|
107
|
+
except Exception:
|
|
108
|
+
return {"state": "error", "error": "wallet 解析失败"}
|
|
109
|
+
return {
|
|
110
|
+
"state": "ok",
|
|
111
|
+
"balance": wallet.get("available_balance"),
|
|
112
|
+
"currency": wallet.get("currency"),
|
|
113
|
+
"as_of": wallet.get("as_of"),
|
|
114
|
+
"source": "mcp:get_wallet",
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def probe_brightdata():
|
|
119
|
+
k = key("BRIGHTDATA_APITOKEN")
|
|
120
|
+
if not k:
|
|
121
|
+
return {"state": "no_key"}
|
|
122
|
+
try:
|
|
123
|
+
_get("https://api.brightdata.com/customer/balance", {"Authorization": f"Bearer {k}"})
|
|
124
|
+
return {"state": "ok", "source": "api:/customer/balance"}
|
|
125
|
+
except urllib.error.HTTPError as e:
|
|
126
|
+
if e.code in (401, 403):
|
|
127
|
+
return {"state": "no_permission",
|
|
128
|
+
"error": "token 没有 account 读取权限(在控制台 Settings→Users 勾选后再试)"}
|
|
129
|
+
return {"state": "error", "error": f"HTTP {e.code}"}
|
|
130
|
+
except Exception as e:
|
|
131
|
+
return {"state": "error", "error": str(e)[:80]}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def unimplemented(reason):
|
|
135
|
+
return {"state": "unavailable", "error": reason}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def probe_zhihu():
|
|
139
|
+
"""知乎开放平台:/api/v1/quota 一次拿到全部 9 项能力当日限免额度,不消耗业务额度。"""
|
|
140
|
+
k = key("ZHIHU_SEARCH_API_KEY")
|
|
141
|
+
if not k:
|
|
142
|
+
return {"state": "no_key"}
|
|
143
|
+
d = _get("https://developer.zhihu.com/api/v1/quota",
|
|
144
|
+
{"Authorization": f"Bearer {k}", "X-Request-Timestamp": str(int(time.time()))})
|
|
145
|
+
if d.get("Code") not in (0, None):
|
|
146
|
+
return {"state": "error", "error": f'{d.get("Code")}: {d.get("Message")}'}
|
|
147
|
+
items = [
|
|
148
|
+
{
|
|
149
|
+
"id": it.get("APIID"),
|
|
150
|
+
"name": it.get("APIName"),
|
|
151
|
+
"total": it.get("TotalQuota"),
|
|
152
|
+
"used": it.get("TotalUsed"),
|
|
153
|
+
"remaining": it.get("RemainingQuota"),
|
|
154
|
+
}
|
|
155
|
+
for it in (d.get("Data") or [])
|
|
156
|
+
]
|
|
157
|
+
return {"state": "ok", "items": items, "source": "api:/api/v1/quota"}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
PROBES = {
|
|
161
|
+
"firecrawl": probe_firecrawl,
|
|
162
|
+
"tinyfish": probe_tinyfish,
|
|
163
|
+
"zhihu": probe_zhihu,
|
|
164
|
+
"exa": lambda: unimplemented("官方 usage 接口需向 support 申请 access,默认不可用"),
|
|
165
|
+
"jina_reader": lambda: unimplemented("只有 dashboard 看余额,没有公开额度 API"),
|
|
166
|
+
"langsearch": lambda: unimplemented("官方只给 token 日额度,没有查询端点"),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def load():
|
|
171
|
+
try:
|
|
172
|
+
return json.loads(FILE.read_text())
|
|
173
|
+
except Exception:
|
|
174
|
+
return {}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def save(d):
|
|
178
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
+
tmp = FILE.with_suffix(FILE.suffix + ".tmp")
|
|
180
|
+
tmp.write_text(json.dumps(d, indent=2))
|
|
181
|
+
tmp.replace(FILE)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def run(max_age=0):
|
|
185
|
+
"""max_age>0 时:如果上次校准已在 N 秒内,直接复用,不重复请求厂商接口。"""
|
|
186
|
+
if max_age:
|
|
187
|
+
old = (load().get("_official") or {})
|
|
188
|
+
stamps = [v.get("probed_at") for v in old.values() if v.get("state") == "ok"]
|
|
189
|
+
if stamps:
|
|
190
|
+
try:
|
|
191
|
+
last = max(datetime.fromisoformat(t) for t in stamps)
|
|
192
|
+
if (datetime.now(timezone.utc) - last).total_seconds() < max_age:
|
|
193
|
+
return old
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
with ThreadPoolExecutor(max_workers=len(PROBES)) as ex:
|
|
197
|
+
futs = {name: ex.submit(fn) for name, fn in PROBES.items()}
|
|
198
|
+
out = {}
|
|
199
|
+
for name, fut in futs.items():
|
|
200
|
+
try:
|
|
201
|
+
out[name] = fut.result()
|
|
202
|
+
except Exception as e:
|
|
203
|
+
out[name] = {"state": "error", "error": str(e)[:100]}
|
|
204
|
+
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
205
|
+
for v in out.values():
|
|
206
|
+
v["probed_at"] = stamp
|
|
207
|
+
d = load()
|
|
208
|
+
d["_official"] = out
|
|
209
|
+
save(d)
|
|
210
|
+
return out
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def render(out, as_json=False):
|
|
214
|
+
if as_json:
|
|
215
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
216
|
+
return
|
|
217
|
+
lines = []
|
|
218
|
+
for name, v in out.items():
|
|
219
|
+
st = v.get("state")
|
|
220
|
+
if st == "ok":
|
|
221
|
+
if name == "firecrawl":
|
|
222
|
+
rem, tot = v.get("remaining"), v.get("total")
|
|
223
|
+
pct = f"({rem / tot * 100:.0f}% 剩余)" if rem is not None and tot else ""
|
|
224
|
+
lines.append(f" {name:12s} ✅ 剩余 {rem}/{tot} credits{pct} 账期至 {str(v.get('period_end'))[:10]}")
|
|
225
|
+
elif name == "tinyfish":
|
|
226
|
+
lines.append(f" {name:12s} ✅ 钱包 {v.get('balance')} {v.get('currency')}(search/fetch 本身 $0)")
|
|
227
|
+
elif name == "zhihu":
|
|
228
|
+
parts = [f"{i.get('name')} {i.get('remaining')}/{i.get('total')}"
|
|
229
|
+
for i in (v.get("items") or [])]
|
|
230
|
+
lines.append(f" {name:12s} ✅ " + " · ".join(parts) + "(当日限免)")
|
|
231
|
+
else:
|
|
232
|
+
lines.append(f" {name:12s} ✅ {v.get('source')}")
|
|
233
|
+
elif st == "no_key":
|
|
234
|
+
lines.append(f" {name:12s} 🔇 未配置 key")
|
|
235
|
+
elif st == "unavailable":
|
|
236
|
+
lines.append(f" {name:12s} ⚪ 无公开接口:{v.get('error')}")
|
|
237
|
+
elif st == "no_permission":
|
|
238
|
+
lines.append(f" {name:12s} ⚠️ {v.get('error')}")
|
|
239
|
+
else:
|
|
240
|
+
lines.append(f" {name:12s} ❌ {v.get('error')}")
|
|
241
|
+
print("官方额度校准(写入 quota.json 的 _official 段)")
|
|
242
|
+
print("\n".join(lines))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def main(argv):
|
|
246
|
+
as_json = "--json" in argv
|
|
247
|
+
quiet = "--quiet" in argv
|
|
248
|
+
max_age = 600 if quiet else 0 # fanout 高频调用时 10 分钟内复用上次结果
|
|
249
|
+
for i, a in enumerate(argv):
|
|
250
|
+
if a == "--max-age" and i + 1 < len(argv):
|
|
251
|
+
max_age = int(argv[i + 1])
|
|
252
|
+
try:
|
|
253
|
+
out = run(max_age)
|
|
254
|
+
except Exception as e:
|
|
255
|
+
if not quiet:
|
|
256
|
+
print(f"[quota_probe] 校准失败:{e}", file=sys.stderr)
|
|
257
|
+
return 1
|
|
258
|
+
if not quiet:
|
|
259
|
+
render(out, as_json)
|
|
260
|
+
else:
|
|
261
|
+
ok = [k for k, v in out.items() if v.get("state") == "ok"]
|
|
262
|
+
# 只报还在 PROBES 里的通道 —— 已退役的(如 brightdata)留在 quota.json 里的
|
|
263
|
+
# 旧异常不该每轮都喊一次
|
|
264
|
+
bad = [k for k, v in out.items()
|
|
265
|
+
if k in PROBES and v.get("state") in ("error", "no_permission")]
|
|
266
|
+
if bad:
|
|
267
|
+
print(f"[quota_probe] 校准异常:{', '.join(bad)}(其余 {len(ok)} 家正常)", file=sys.stderr)
|
|
268
|
+
return 0
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Canonical D-Reach default-route config parser for fanout, plugin, and gateway."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RegistryError(ValueError):
|
|
12
|
+
"""SECTIONS 与 BASE_CHANNELS / DEEP_CHANNELS 不同步 —— 是代码问题,不是配置问题。"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_routes(script_path: Path, base_arg: str, deep_arg: str):
|
|
16
|
+
source = script_path.read_text(encoding="utf-8")
|
|
17
|
+
match = re.search(r"(?ms)^SECTIONS = \[\n(.*?)^\]", source)
|
|
18
|
+
if not match:
|
|
19
|
+
raise RegistryError("Could not parse SECTIONS route registry")
|
|
20
|
+
|
|
21
|
+
entries = []
|
|
22
|
+
for entry in re.split(r"\n(?= \()", match.group(1)):
|
|
23
|
+
label = re.match(r'\s*\("([a-z]+)",\s*"([^"]+)"', entry)
|
|
24
|
+
if not label:
|
|
25
|
+
continue
|
|
26
|
+
deep = re.search(r",\s*(True|False)\s*\)", entry)
|
|
27
|
+
entries.append(
|
|
28
|
+
{
|
|
29
|
+
"key": label.group(1),
|
|
30
|
+
"name": label.group(2),
|
|
31
|
+
"tier": "deep" if deep and deep.group(1) == "True" else "base",
|
|
32
|
+
}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
base_keys = base_arg.split()
|
|
36
|
+
deep_keys = deep_arg.split()
|
|
37
|
+
if not entries:
|
|
38
|
+
raise RegistryError("No route entries found in SECTIONS")
|
|
39
|
+
if len(set(base_keys)) != len(base_keys) or len(set(deep_keys)) != len(deep_keys):
|
|
40
|
+
raise RegistryError("Duplicate route key in BASE_CHANNELS or DEEP_CHANNELS")
|
|
41
|
+
if set(base_keys) & set(deep_keys):
|
|
42
|
+
raise RegistryError("Route key appears in both BASE_CHANNELS and DEEP_CHANNELS")
|
|
43
|
+
route_keys = {entry["key"] for entry in entries}
|
|
44
|
+
if route_keys != set(base_keys) | set(deep_keys):
|
|
45
|
+
raise RegistryError("SECTIONS does not match BASE_CHANNELS and DEEP_CHANNELS")
|
|
46
|
+
for entry in entries:
|
|
47
|
+
expected_tier = "deep" if entry["key"] in set(deep_keys) else "base"
|
|
48
|
+
if entry["tier"] != expected_tier:
|
|
49
|
+
raise RegistryError(f"Route tier mismatch for {entry['key']}")
|
|
50
|
+
return entries, base_keys, deep_keys
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def read_list(config, name, allowed):
|
|
54
|
+
values = config.get(name)
|
|
55
|
+
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
|
56
|
+
raise ValueError(f"{name} 必须是字符串数组")
|
|
57
|
+
|
|
58
|
+
result = []
|
|
59
|
+
allowed_set = set(allowed)
|
|
60
|
+
for raw in values:
|
|
61
|
+
value = raw.strip()
|
|
62
|
+
if not value or "," in value:
|
|
63
|
+
raise ValueError(f"{name} 每项必须是一个通道名")
|
|
64
|
+
if value not in allowed_set:
|
|
65
|
+
raise ValueError(f"{name} 含不适用的通道:{value}")
|
|
66
|
+
if value not in result:
|
|
67
|
+
result.append(value)
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_data(script_path: Path, defaults_path: Path, base_arg: str, deep_arg: str):
|
|
72
|
+
entries, base_keys, deep_keys = parse_routes(script_path, base_arg, deep_arg)
|
|
73
|
+
try:
|
|
74
|
+
try:
|
|
75
|
+
raw_config = defaults_path.read_text(encoding="utf-8")
|
|
76
|
+
except FileNotFoundError:
|
|
77
|
+
enabled_base, enabled_deep = base_keys, deep_keys
|
|
78
|
+
else:
|
|
79
|
+
config = json.loads(raw_config)
|
|
80
|
+
if not isinstance(config, dict):
|
|
81
|
+
raise ValueError("配置顶层必须是对象")
|
|
82
|
+
enabled_base = read_list(config, "enabledByDefault", base_keys)
|
|
83
|
+
enabled_deep = read_list(config, "enabledForDeep", deep_keys)
|
|
84
|
+
error = ""
|
|
85
|
+
except Exception as exc:
|
|
86
|
+
enabled_base, enabled_deep = [], []
|
|
87
|
+
error = f"defaults: {exc}"
|
|
88
|
+
|
|
89
|
+
base_set, deep_set = set(enabled_base), set(enabled_deep)
|
|
90
|
+
channels = []
|
|
91
|
+
for entry in entries:
|
|
92
|
+
is_deep = entry["tier"] == "deep"
|
|
93
|
+
channels.append(
|
|
94
|
+
{
|
|
95
|
+
**entry,
|
|
96
|
+
"default_on": not is_deep and entry["key"] in base_set,
|
|
97
|
+
"deep_on": is_deep and entry["key"] in deep_set,
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
return {
|
|
101
|
+
"enabledByDefault": enabled_base,
|
|
102
|
+
"enabledForDeep": enabled_deep,
|
|
103
|
+
"defaults_error": error,
|
|
104
|
+
"channels": channels,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def main():
|
|
109
|
+
parser = argparse.ArgumentParser()
|
|
110
|
+
parser.add_argument("--script", required=True, type=Path)
|
|
111
|
+
parser.add_argument("--defaults", required=True, type=Path)
|
|
112
|
+
parser.add_argument("--base", required=True)
|
|
113
|
+
parser.add_argument("--deep", required=True)
|
|
114
|
+
parser.add_argument("--format", choices=("json", "table", "lists"), required=True)
|
|
115
|
+
args = parser.parse_args()
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
data = load_data(args.script, args.defaults, args.base, args.deep)
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
prefix = "route-registry: " if isinstance(exc, RegistryError) else "defaults: "
|
|
121
|
+
data = {
|
|
122
|
+
"enabledByDefault": [],
|
|
123
|
+
"enabledForDeep": [],
|
|
124
|
+
"defaults_error": prefix + str(exc),
|
|
125
|
+
"channels": [],
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if args.format == "json":
|
|
129
|
+
print(json.dumps(data, ensure_ascii=False))
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
if args.format == "lists":
|
|
133
|
+
if data["defaults_error"]:
|
|
134
|
+
print(data["defaults_error"], file=sys.stderr)
|
|
135
|
+
return 2
|
|
136
|
+
print(",".join(data["enabledByDefault"]) + "|" + ",".join(data["enabledForDeep"]))
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
for channel in data["channels"]:
|
|
140
|
+
if channel["tier"] == "deep":
|
|
141
|
+
state = " [deep-on]" if channel["deep_on"] else " [not-deep]"
|
|
142
|
+
else:
|
|
143
|
+
state = " [default-on]" if channel["default_on"] else " [not-default]"
|
|
144
|
+
print(f" {channel['key']:10s} {channel['tier']:4s} {channel['name']}{state}")
|
|
145
|
+
if data["defaults_error"]:
|
|
146
|
+
error = data["defaults_error"]
|
|
147
|
+
if error.startswith("route-registry: "):
|
|
148
|
+
print(f"\n 路由注册表不一致(改代码,不是改配置):{error[len('route-registry: '):]}")
|
|
149
|
+
else:
|
|
150
|
+
print(f"\n 默认启用配置有误:{error[len('defaults: '):]}")
|
|
151
|
+
print('\n 用法: fanout.sh "<query>" [--deep] [--n N] [--on key1,key2] [--en "<english>"]')
|
|
152
|
+
return 2 if data["defaults_error"] else 0
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
raise SystemExit(main())
|