fusion-artifacts-engine 0.7.18__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.
- fusion_artifacts_engine/__init__.py +0 -0
- fusion_artifacts_engine/__main__.py +263 -0
- fusion_artifacts_engine/ai_client.py +54 -0
- fusion_artifacts_engine/auto_identifier.py +148 -0
- fusion_artifacts_engine/compactor.py +164 -0
- fusion_artifacts_engine/config.py +462 -0
- fusion_artifacts_engine/default_config.yaml +144 -0
- fusion_artifacts_engine/dsl_parser.py +231 -0
- fusion_artifacts_engine/engine.py +1372 -0
- fusion_artifacts_engine/gateway_client.py +396 -0
- fusion_artifacts_engine/ipc_consumer.py +321 -0
- fusion_artifacts_engine/long_context.py +392 -0
- fusion_artifacts_engine/metrics.py +144 -0
- fusion_artifacts_engine/models.py +168 -0
- fusion_artifacts_engine/office_ingest.py +365 -0
- fusion_artifacts_engine/rate_limiter.py +82 -0
- fusion_artifacts_engine/ref_parser.py +77 -0
- fusion_artifacts_engine/render.py +184 -0
- fusion_artifacts_engine/rpc/__init__.py +0 -0
- fusion_artifacts_engine/rpc/errors.py +61 -0
- fusion_artifacts_engine/rpc/event_bus.py +95 -0
- fusion_artifacts_engine/rpc/methods.py +1365 -0
- fusion_artifacts_engine/rpc/server.py +1279 -0
- fusion_artifacts_engine/section_index.py +189 -0
- fusion_artifacts_engine/share.py +326 -0
- fusion_artifacts_engine/storage/__init__.py +0 -0
- fusion_artifacts_engine/storage/base.py +270 -0
- fusion_artifacts_engine/storage/sqlite_storage.py +2813 -0
- fusion_artifacts_engine/token_budget.py +119 -0
- fusion_artifacts_engine/token_counter.py +80 -0
- fusion_artifacts_engine/tracing.py +132 -0
- fusion_artifacts_engine/utils.py +170 -0
- fusion_artifacts_engine/visual_dispatcher.py +135 -0
- fusion_artifacts_engine/visual_error_boundary.py +52 -0
- fusion_artifacts_engine/visual_primitives/__init__.py +34 -0
- fusion_artifacts_engine/visual_primitives/array_grid.py +66 -0
- fusion_artifacts_engine/visual_primitives/base.py +79 -0
- fusion_artifacts_engine/visual_primitives/bucket_divider.py +66 -0
- fusion_artifacts_engine/visual_primitives/data_chart.py +65 -0
- fusion_artifacts_engine/visual_primitives/flow_card.py +101 -0
- fusion_artifacts_engine/visual_primitives/geometry_2d.py +80 -0
- fusion_artifacts_engine/visual_primitives/isometric_3d.py +82 -0
- fusion_artifacts_engine/visual_primitives/tape_diagram.py +58 -0
- fusion_artifacts_engine/visual_primitives/track_timeline.py +58 -0
- fusion_artifacts_engine/webui_dist/assets/abnfDiagram-WEYOIA3C-2ebtMp5N.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/architectureDiagram-ZHVYKT53-COvSzFYy.js +36 -0
- fusion_artifacts_engine/webui_dist/assets/blockDiagram-RJAE7QA3-CsO2Iy8b.js +140 -0
- fusion_artifacts_engine/webui_dist/assets/c4Diagram-XDPPPE54-dFggQosH.js +38 -0
- fusion_artifacts_engine/webui_dist/assets/channel-BXYZthxM.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-2E7WHVMD-B93QdjG6.js +88 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-2Q5K7J3B-DHEJLJup.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-4EMNKR2T-OGUUH-PY.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-55XCU76K-CKbux1-g.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-5VM5RSS4-CPHhHyIF.js +15 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-JWPE2WC7-CJSxuarC.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-VQ5W62QI-LHItmtfv.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-XXDRQBXY-BRYBW56M.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-ZCHMQSOR-cGbkforM.js +2 -0
- fusion_artifacts_engine/webui_dist/assets/classDiagram-v2-4MYWR3UA-RVdXT7ne.js +217 -0
- fusion_artifacts_engine/webui_dist/assets/cose-bilkent-JH36ORCC-C1hy4K0b.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/cynefin-EF2NZ3EQ-D8ytFvIy.js +141 -0
- fusion_artifacts_engine/webui_dist/assets/cynefinDiagram-WF24UDRP-9iOV04Va.js +62 -0
- fusion_artifacts_engine/webui_dist/assets/cytoscape.esm-BLAcgzS2.js +331 -0
- fusion_artifacts_engine/webui_dist/assets/dagre-NK4GIZVX-zE4dzUJh.js +4 -0
- fusion_artifacts_engine/webui_dist/assets/defaultLocale-5voVPcsN.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-CBK3MWTC-BrXmQtKM.js +24 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-I5XIIV2D-Bctxj8zx.js +24 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-ODIL2UCW-DfDzzeod.js +30 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-PFBEJUXE-BGZKfFXu.js +3 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-RJA3I4VV-CXB6A2jx.js +41 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-TYUNFSNR-gfqyjmIj.js +200 -0
- fusion_artifacts_engine/webui_dist/assets/ebnfDiagram-V4P3TTPT-CZ1BZkcl.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/elk-QONTBCTQ-C5YzS41r.js +27 -0
- fusion_artifacts_engine/webui_dist/assets/erDiagram-KYQIGQAA-B-DYTd4O.js +99 -0
- fusion_artifacts_engine/webui_dist/assets/flowDiagram-IUGLLWBU-IRAKfxcJ.js +213 -0
- fusion_artifacts_engine/webui_dist/assets/ganttDiagram-R7GPNTJY-DRdmsg6i.js +292 -0
- fusion_artifacts_engine/webui_dist/assets/gitGraphDiagram-PDYL7XHY-B0QL_KrV.js +106 -0
- fusion_artifacts_engine/webui_dist/assets/graph-Bn3Yngep.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/index-CCsQ6nhB.js +374 -0
- fusion_artifacts_engine/webui_dist/assets/index-Cw23dyL1.css +1 -0
- fusion_artifacts_engine/webui_dist/assets/infoDiagram-MVDRKAX5-DMlVkZRb.js +2 -0
- fusion_artifacts_engine/webui_dist/assets/init-DDsq4BXF.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/ishikawaDiagram-HPEHV2GE-yZW7Bvw7.js +70 -0
- fusion_artifacts_engine/webui_dist/assets/journeyDiagram-BOSHW7O7-C0UaOGz2.js +139 -0
- fusion_artifacts_engine/webui_dist/assets/kanban-definition-FNSA4HC5-D2VjWSCv.js +89 -0
- fusion_artifacts_engine/webui_dist/assets/katex-Be3d8Y4U.js +257 -0
- fusion_artifacts_engine/webui_dist/assets/linear-B0L4ZWGd.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/mermaid.core-C0Fw4Tzk.js +314 -0
- fusion_artifacts_engine/webui_dist/assets/mindmap-definition-6OY57UG3-Dy3WTB5p.js +98 -0
- fusion_artifacts_engine/webui_dist/assets/ordinal-_ShbN0yz.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/pegDiagram-ECIUJNBX-Cdm0XnAV.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/pieDiagram-GNMPY74T-TrdpBRYl.js +39 -0
- fusion_artifacts_engine/webui_dist/assets/quadrantDiagram-D57K4MC3-N1OmHTjQ.js +7 -0
- fusion_artifacts_engine/webui_dist/assets/railroadDiagram-Y72NRBL7-DhZcDSX6.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/requirementDiagram-EQYSW5RA-CGmfo0LK.js +84 -0
- fusion_artifacts_engine/webui_dist/assets/sankeyDiagram-SY24JHO5-CnAXR6RI.js +40 -0
- fusion_artifacts_engine/webui_dist/assets/sequenceDiagram-BLEHNHQU-Divp82Qv.js +169 -0
- fusion_artifacts_engine/webui_dist/assets/sizeCapture-INFHLROL-BxUSO2gs.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/stateDiagram-v2-A6IESKWZ-Ch2o3gee.js +291 -0
- fusion_artifacts_engine/webui_dist/assets/swimlanes-B3ENRKFQ-CBnYOtut.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/swimlanesDiagram-AYQRV4AK-Bdp49byx.js +8 -0
- fusion_artifacts_engine/webui_dist/assets/timeline-definition-JXYKGLGB-Cp8DPlck.js +120 -0
- fusion_artifacts_engine/webui_dist/assets/usecaseDiagram-WPOLBNNX-CcF_Y4cE.js +370 -0
- fusion_artifacts_engine/webui_dist/assets/vennDiagram-Q3Y3IDCW-Dplzp3gZ.js +34 -0
- fusion_artifacts_engine/webui_dist/assets/wardleyDiagram-IVAIDKWA-fKoKxoZw.js +78 -0
- fusion_artifacts_engine/webui_dist/assets/xychartDiagram-4URNHDU4-DRVZF7Gc.js +7 -0
- fusion_artifacts_engine/webui_dist/favicon.svg +1 -0
- fusion_artifacts_engine/webui_dist/index.html +14 -0
- fusion_artifacts_engine-0.7.18.dist-info/METADATA +1115 -0
- fusion_artifacts_engine-0.7.18.dist-info/RECORD +114 -0
- fusion_artifacts_engine-0.7.18.dist-info/WHEEL +5 -0
- fusion_artifacts_engine-0.7.18.dist-info/entry_points.txt +2 -0
- fusion_artifacts_engine-0.7.18.dist-info/licenses/LICENSE +201 -0
- fusion_artifacts_engine-0.7.18.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import stat
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from fusion_artifacts_engine.utils import get_package_version
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
# #75: web-shell integration (service registration plane added after Config
|
|
16
|
+
# Phase 3.3). On startup the engine self-registers its shell manifest with
|
|
17
|
+
# fusion-gateway (idempotent upsert), then heartbeats periodically.
|
|
18
|
+
# #82: the registration body omits api_key — the gateway issues an
|
|
19
|
+
# fm-<module>-<hex> service key (raw_key returned exactly once), which the
|
|
20
|
+
# engine persists and uses for heartbeats and re-registration. The proxy
|
|
21
|
+
# injects the same fm- key via manifest.api_key, so the engine auth layer
|
|
22
|
+
# must accept it (rpc/server.py _is_authed).
|
|
23
|
+
|
|
24
|
+
_MODULE_TITLE = "Artifacts"
|
|
25
|
+
_MODULE_PATH = "/artifacts"
|
|
26
|
+
_MODULE_ICON = "Package"
|
|
27
|
+
_MODULE_CATEGORY = "platform"
|
|
28
|
+
_MODULE_DEVICES = ["desktop"]
|
|
29
|
+
|
|
30
|
+
# #82: minimum interval between re-registrations after a 403/404 heartbeat.
|
|
31
|
+
# A gateway restart wipes the manifest store — one re-registration re-issues a
|
|
32
|
+
# key and recovers; but for non-self-healable states (admin-revoked key) the
|
|
33
|
+
# cooldown prevents a 15s log/call storm of admin-key attempts.
|
|
34
|
+
_REREGISTER_COOLDOWN_SECONDS = 300
|
|
35
|
+
|
|
36
|
+
# #104: key-drift probe interval. Both the gateway heartbeat plane and the
|
|
37
|
+
# re-registration plane accept the "previous key" inside KeyRotationGrace
|
|
38
|
+
# (default 24h) — an engine holding a stale key keeps getting 200 heartbeats
|
|
39
|
+
# while the data plane (proxy injects the current key) is already rejected;
|
|
40
|
+
# symptom is shell-proxy -32600 for up to a full grace window. The probe goes
|
|
41
|
+
# through the upsert self-heal plane: the response key_id is always the
|
|
42
|
+
# gateway's current key id (same on the retained branch), so comparing it
|
|
43
|
+
# with the locally persisted key_id detects drift inside the grace window;
|
|
44
|
+
# the follow-up admin re-register triggers a #460 rotation for new plaintext.
|
|
45
|
+
_KEY_PROBE_INTERVAL_SECONDS = 600
|
|
46
|
+
|
|
47
|
+
# _is_authed compares the service key on every request; cache by (path, mtime)
|
|
48
|
+
# to avoid repeated disk reads.
|
|
49
|
+
_key_file_cache: dict[str, tuple[float, str]] = {}
|
|
50
|
+
_key_file_cache_lock = threading.Lock()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load_service_key(path: Path) -> str:
|
|
54
|
+
try:
|
|
55
|
+
mtime = path.stat().st_mtime
|
|
56
|
+
except OSError:
|
|
57
|
+
return ""
|
|
58
|
+
key = str(path)
|
|
59
|
+
with _key_file_cache_lock:
|
|
60
|
+
cached = _key_file_cache.get(key)
|
|
61
|
+
if cached is not None and cached[0] == mtime:
|
|
62
|
+
return cached[1]
|
|
63
|
+
try:
|
|
64
|
+
content = path.read_text(encoding="utf-8").strip()
|
|
65
|
+
except OSError as e:
|
|
66
|
+
logger.warning("gateway service key read failed %s: %s", path, e)
|
|
67
|
+
return ""
|
|
68
|
+
with _key_file_cache_lock:
|
|
69
|
+
_key_file_cache[key] = (mtime, content)
|
|
70
|
+
return content
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def save_service_key(path: Path, raw_key: str) -> None:
|
|
74
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
76
|
+
tmp.write_text(raw_key.strip(), encoding="utf-8")
|
|
77
|
+
os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)
|
|
78
|
+
tmp.replace(path)
|
|
79
|
+
with _key_file_cache_lock:
|
|
80
|
+
_key_file_cache.pop(str(path), None)
|
|
81
|
+
logger.info("gateway service key persisted to %s", path)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def key_id_path(key_path: Path) -> Path:
|
|
85
|
+
# #104: key_id sidecar (<key_file>.keyid). The key file itself stays plain
|
|
86
|
+
# text (rpc/server.py _is_authed reads it directly); the key_id lives in a
|
|
87
|
+
# sidecar so the two never interfere.
|
|
88
|
+
return key_path.with_name(key_path.name + ".keyid")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def load_key_id(key_path: Path) -> str:
|
|
92
|
+
try:
|
|
93
|
+
return key_id_path(key_path).read_text(encoding="utf-8").strip()
|
|
94
|
+
except OSError:
|
|
95
|
+
return ""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def save_key_id(key_path: Path, key_id: str) -> None:
|
|
99
|
+
p = key_id_path(key_path)
|
|
100
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
tmp = p.with_suffix(".tmp")
|
|
102
|
+
tmp.write_text(key_id.strip(), encoding="utf-8")
|
|
103
|
+
os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)
|
|
104
|
+
tmp.replace(p)
|
|
105
|
+
logger.info("gateway service key_id persisted to %s", p)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class GatewayClient:
|
|
109
|
+
def __init__(self, config, host: str, port: int) -> None:
|
|
110
|
+
self._config = config
|
|
111
|
+
self._host = host
|
|
112
|
+
self._port = port
|
|
113
|
+
self._module_id = config.gateway_module_id
|
|
114
|
+
self._base_url = config.gateway_url.rstrip("/")
|
|
115
|
+
self._interval = max(5, int(config.gateway_heartbeat_interval))
|
|
116
|
+
self._key_path: Path = config.gateway_service_key_path
|
|
117
|
+
self._service_key = load_service_key(self._key_path)
|
|
118
|
+
self._last_reregister = 0.0
|
|
119
|
+
self._last_probe = 0.0
|
|
120
|
+
self._divergent_keyid = False
|
|
121
|
+
self._register_lock = threading.Lock()
|
|
122
|
+
self._stop = threading.Event()
|
|
123
|
+
self._thread: threading.Thread | None = None
|
|
124
|
+
self._client = httpx.Client(timeout=5.0)
|
|
125
|
+
|
|
126
|
+
def _manifest_payload(self) -> dict:
|
|
127
|
+
# #82: omit api_key — the gateway issues/retains the fm- service key
|
|
128
|
+
# based on this (#261 K1). Sending api_key takes the module-supplied
|
|
129
|
+
# credential path and drops the issued key; heartbeats then 403 forever.
|
|
130
|
+
return {
|
|
131
|
+
"id": self._module_id,
|
|
132
|
+
"title": _MODULE_TITLE,
|
|
133
|
+
"title_en": _MODULE_TITLE,
|
|
134
|
+
"version": get_package_version(),
|
|
135
|
+
"path": _MODULE_PATH,
|
|
136
|
+
"icon": _MODULE_ICON,
|
|
137
|
+
"entry": f"/shell/{self._module_id}/",
|
|
138
|
+
# health hits this process directly (same pattern as carvideo/surl):
|
|
139
|
+
# unauthenticated liveness, gateway probes do not need a shell session.
|
|
140
|
+
"health": f"http://{self._host}:{self._port}/healthz",
|
|
141
|
+
"devices": list(_MODULE_DEVICES),
|
|
142
|
+
"category": _MODULE_CATEGORY,
|
|
143
|
+
# #232 dynamic proxy: upstream makes /shell/<id>/ work with no gateway config change
|
|
144
|
+
"upstream": f"http://{self._host}:{self._port}",
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
def _register_candidates(self) -> list[tuple[str, str]]:
|
|
148
|
+
# fm- key first (#369 self-heal / idempotent re-register); admin key is
|
|
149
|
+
# for first bootstrap only.
|
|
150
|
+
candidates: list[tuple[str, str]] = []
|
|
151
|
+
if self._service_key:
|
|
152
|
+
candidates.append(("service-key", self._service_key))
|
|
153
|
+
admin_key = self._config.gateway_admin_key or ""
|
|
154
|
+
if admin_key and admin_key != self._service_key:
|
|
155
|
+
candidates.append(("admin-key", admin_key))
|
|
156
|
+
return candidates
|
|
157
|
+
|
|
158
|
+
def register(self, force_admin: bool = False) -> bool:
|
|
159
|
+
with self._register_lock:
|
|
160
|
+
if force_admin:
|
|
161
|
+
# #104: drift self-heal only — skip the service-key candidate and
|
|
162
|
+
# re-register with the admin key directly (#460: an admin-plane
|
|
163
|
+
# re-register rotates the key and returns the new plaintext).
|
|
164
|
+
admin_key = self._config.gateway_admin_key or ""
|
|
165
|
+
candidates = [("admin-key", admin_key)] if admin_key else []
|
|
166
|
+
else:
|
|
167
|
+
candidates = self._register_candidates()
|
|
168
|
+
if not candidates:
|
|
169
|
+
logger.warning(
|
|
170
|
+
"gateway registration skipped: no service key (key_file=%s) and no "
|
|
171
|
+
"gateway.admin_key configured",
|
|
172
|
+
self._key_path,
|
|
173
|
+
)
|
|
174
|
+
return False
|
|
175
|
+
url = f"{self._base_url}/api/v1/shell/manifests"
|
|
176
|
+
payload = self._manifest_payload()
|
|
177
|
+
for label, credential in candidates:
|
|
178
|
+
try:
|
|
179
|
+
resp = self._client.post(
|
|
180
|
+
url, json=payload, headers={"Authorization": f"Bearer {credential}"}
|
|
181
|
+
)
|
|
182
|
+
except httpx.HTTPError as e:
|
|
183
|
+
logger.warning("gateway registration request failed (%s): %s", label, e)
|
|
184
|
+
continue
|
|
185
|
+
if resp.status_code == 200:
|
|
186
|
+
self._accept_register_response(resp, label)
|
|
187
|
+
return True
|
|
188
|
+
logger.info(
|
|
189
|
+
"gateway registration not accepted (%s, status=%s), trying next credential",
|
|
190
|
+
label,
|
|
191
|
+
resp.status_code,
|
|
192
|
+
)
|
|
193
|
+
logger.warning("gateway registration rejected by all credentials")
|
|
194
|
+
return False
|
|
195
|
+
|
|
196
|
+
def _accept_register_response(self, resp, label: str) -> None:
|
|
197
|
+
raw_key = ""
|
|
198
|
+
key_id = ""
|
|
199
|
+
try:
|
|
200
|
+
data = json.loads(resp.text or "{}")
|
|
201
|
+
raw_key = data.get("raw_key") or ""
|
|
202
|
+
key_id = data.get("key_id") or ""
|
|
203
|
+
except (ValueError, AttributeError):
|
|
204
|
+
logger.debug("gateway register response not JSON, assuming no issued key")
|
|
205
|
+
if raw_key:
|
|
206
|
+
self._service_key = raw_key
|
|
207
|
+
try:
|
|
208
|
+
save_service_key(self._key_path, raw_key)
|
|
209
|
+
except OSError as e:
|
|
210
|
+
logger.error("gateway service key persist failed %s: %s", self._key_path, e)
|
|
211
|
+
if key_id:
|
|
212
|
+
try:
|
|
213
|
+
save_key_id(self._key_path, key_id)
|
|
214
|
+
except OSError as e:
|
|
215
|
+
logger.error("gateway key_id persist failed: %s", e)
|
|
216
|
+
elif label == "service-key" and key_id:
|
|
217
|
+
# #104: on the retained branch the key_id is the gateway's CURRENT
|
|
218
|
+
# key id. Compare with the locally persisted value: a mismatch means
|
|
219
|
+
# the engine holds a stale key (the grace-window "previous key",
|
|
220
|
+
# whose drift the heartbeat plane masks with 200s). probe_key_state
|
|
221
|
+
# then heals via an admin re-register rotation; with no local record
|
|
222
|
+
# the first probe just seeds the baseline.
|
|
223
|
+
stored = load_key_id(self._key_path)
|
|
224
|
+
if not stored:
|
|
225
|
+
try:
|
|
226
|
+
save_key_id(self._key_path, key_id)
|
|
227
|
+
except OSError as e:
|
|
228
|
+
logger.error("gateway key_id persist failed: %s", e)
|
|
229
|
+
logger.info("gateway key_id baseline recorded (%s)", key_id)
|
|
230
|
+
elif stored != key_id:
|
|
231
|
+
self._divergent_keyid = True
|
|
232
|
+
logger.warning(
|
|
233
|
+
"gateway service key divergence detected: engine holds "
|
|
234
|
+
"key_id=%s, gateway current=%s (stale key masked by "
|
|
235
|
+
"heartbeat grace window)",
|
|
236
|
+
stored,
|
|
237
|
+
key_id,
|
|
238
|
+
)
|
|
239
|
+
elif not self._service_key:
|
|
240
|
+
# A gateway upsert re-register may not issue a new key (record
|
|
241
|
+
# retained) — re-read the key file first (an earlier instance may
|
|
242
|
+
# have persisted a valid key) and reuse it silently when present.
|
|
243
|
+
stored = load_service_key(self._key_path)
|
|
244
|
+
if stored:
|
|
245
|
+
self._service_key = stored
|
|
246
|
+
logger.info(
|
|
247
|
+
"gateway registered (%s) without raw_key; retained persisted key from %s",
|
|
248
|
+
label,
|
|
249
|
+
self._key_path,
|
|
250
|
+
)
|
|
251
|
+
else:
|
|
252
|
+
logger.warning(
|
|
253
|
+
"gateway registered (%s) but returned no raw_key and no stored key — "
|
|
254
|
+
"heartbeat will fail; ask an admin to rotate the service key",
|
|
255
|
+
label,
|
|
256
|
+
)
|
|
257
|
+
else:
|
|
258
|
+
logger.info("gateway registration accepted (%s, existing key retained)", label)
|
|
259
|
+
|
|
260
|
+
def heartbeat_once(self) -> bool:
|
|
261
|
+
if not self._service_key:
|
|
262
|
+
# First bootstrap or lost key file: registering doubles as keepalive
|
|
263
|
+
# (upsert refreshes lastHeartbeat). A keyless registration that gets
|
|
264
|
+
# no raw_key would spin in place — apply the same cooldown window to
|
|
265
|
+
# avoid a register+warn loop every interval (seen live in v0.7.3).
|
|
266
|
+
now = time.time()
|
|
267
|
+
if now - self._last_reregister < _REREGISTER_COOLDOWN_SECONDS:
|
|
268
|
+
return False
|
|
269
|
+
self._last_reregister = now
|
|
270
|
+
return self.register()
|
|
271
|
+
url = f"{self._base_url}/api/v1/shell/manifests/{self._module_id}/heartbeat"
|
|
272
|
+
try:
|
|
273
|
+
resp = self._client.post(
|
|
274
|
+
url, json={}, headers={"Authorization": f"Bearer {self._service_key}"}
|
|
275
|
+
)
|
|
276
|
+
if resp.status_code == 200:
|
|
277
|
+
# #110: gateway #485 exposes key drift on the 200 heartbeat
|
|
278
|
+
# itself — X-Fusion-Key-State: stale means the heartbeat matched
|
|
279
|
+
# the rotated-out key inside the grace window while the data
|
|
280
|
+
# plane (proxy injects the current key) is already rejected.
|
|
281
|
+
# Older gateways send no header and keep today's behavior (the
|
|
282
|
+
# 403 path recovers after grace). On the signal, re-register via
|
|
283
|
+
# the admin key immediately (#460 returns fresh plaintext),
|
|
284
|
+
# cooldown-gated against rotation flapping. The heartbeat itself
|
|
285
|
+
# succeeded, so return True and keep the failure counter clean.
|
|
286
|
+
if resp.headers.get("X-Fusion-Key-State") == "stale":
|
|
287
|
+
now = time.time()
|
|
288
|
+
if now - self._last_reregister >= _REREGISTER_COOLDOWN_SECONDS:
|
|
289
|
+
self._last_reregister = now
|
|
290
|
+
logger.warning(
|
|
291
|
+
"gateway heartbeat 200 but key state=stale (rotated out, "
|
|
292
|
+
"grace window), re-registering via admin key module=%s",
|
|
293
|
+
self._module_id,
|
|
294
|
+
)
|
|
295
|
+
self.register(force_admin=True)
|
|
296
|
+
return True
|
|
297
|
+
# 404 manifest_unknown: gateway restart wiped the store;
|
|
298
|
+
# 403 heartbeat_forbidden: no matching service-key record for this
|
|
299
|
+
# module (store rebuilt / key lost). Either way re-register once —
|
|
300
|
+
# the gateway issues a fresh fm- key. Cooldown prevents a 15s loop.
|
|
301
|
+
if resp.status_code in (403, 404):
|
|
302
|
+
now = time.time()
|
|
303
|
+
if now - self._last_reregister < _REREGISTER_COOLDOWN_SECONDS:
|
|
304
|
+
logger.warning(
|
|
305
|
+
"gateway heartbeat %d; re-register skipped (cooldown %.0fs left)",
|
|
306
|
+
resp.status_code,
|
|
307
|
+
_REREGISTER_COOLDOWN_SECONDS - (now - self._last_reregister),
|
|
308
|
+
)
|
|
309
|
+
return False
|
|
310
|
+
self._last_reregister = now
|
|
311
|
+
logger.warning(
|
|
312
|
+
"gateway heartbeat %d (manifest gone), re-registering module=%s",
|
|
313
|
+
resp.status_code,
|
|
314
|
+
self._module_id,
|
|
315
|
+
)
|
|
316
|
+
return self.register()
|
|
317
|
+
logger.warning(
|
|
318
|
+
"gateway heartbeat failed: status=%s body=%s",
|
|
319
|
+
resp.status_code,
|
|
320
|
+
resp.text[:200],
|
|
321
|
+
)
|
|
322
|
+
except httpx.HTTPError as e:
|
|
323
|
+
logger.warning("gateway heartbeat request failed: %s", e)
|
|
324
|
+
return False
|
|
325
|
+
|
|
326
|
+
def probe_key_state(self) -> bool:
|
|
327
|
+
# #104: periodic key-drift probe. A 200 heartbeat does not prove the
|
|
328
|
+
# key is current (the grace window lets the previous key pass the
|
|
329
|
+
# heartbeat plane), so on its own interval run one service-key
|
|
330
|
+
# re-register and compare the response key_id; on drift, heal via an
|
|
331
|
+
# admin re-register rotation (#460 returns new plaintext).
|
|
332
|
+
now = time.time()
|
|
333
|
+
if now - self._last_probe < _KEY_PROBE_INTERVAL_SECONDS:
|
|
334
|
+
return True
|
|
335
|
+
self._last_probe = now
|
|
336
|
+
if not self._service_key:
|
|
337
|
+
# No key yet — the heartbeat_once bootstrap registration path
|
|
338
|
+
# handles issuance; nothing to probe.
|
|
339
|
+
return True
|
|
340
|
+
self._divergent_keyid = False
|
|
341
|
+
if not self.register():
|
|
342
|
+
return False
|
|
343
|
+
if self._divergent_keyid:
|
|
344
|
+
logger.warning(
|
|
345
|
+
"self-healing stale gateway service key via admin re-register (module=%s)",
|
|
346
|
+
self._module_id,
|
|
347
|
+
)
|
|
348
|
+
return self.register(force_admin=True)
|
|
349
|
+
return True
|
|
350
|
+
|
|
351
|
+
def _loop(self) -> None:
|
|
352
|
+
# Periodic heartbeat. Failures do not exit the loop (transient gateway
|
|
353
|
+
# restarts self-heal); warnings are throttled instead.
|
|
354
|
+
fail_streak = 0
|
|
355
|
+
while not self._stop.wait(self._interval):
|
|
356
|
+
self.probe_key_state()
|
|
357
|
+
ok = self.heartbeat_once()
|
|
358
|
+
if ok:
|
|
359
|
+
fail_streak = 0
|
|
360
|
+
continue
|
|
361
|
+
fail_streak += 1
|
|
362
|
+
if fail_streak == 1 or fail_streak % 10 == 0:
|
|
363
|
+
logger.warning(
|
|
364
|
+
"gateway heartbeat failing (streak=%d, module=%s)",
|
|
365
|
+
fail_streak,
|
|
366
|
+
self._module_id,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
def start(self) -> bool:
|
|
370
|
+
if not self.register():
|
|
371
|
+
# Start the heartbeat thread even on registration failure — if the
|
|
372
|
+
# failure was transient (gateway down), the heartbeat loop retries
|
|
373
|
+
# via the register() bootstrap path with no manual intervention.
|
|
374
|
+
logger.info("gateway registration incomplete, heartbeat loop will retry")
|
|
375
|
+
self._thread = threading.Thread(
|
|
376
|
+
target=self._loop, name="fae-gateway-heartbeat", daemon=True
|
|
377
|
+
)
|
|
378
|
+
self._thread.start()
|
|
379
|
+
logger.info(
|
|
380
|
+
"gateway client started (url=%s module=%s interval=%ds)",
|
|
381
|
+
self._base_url,
|
|
382
|
+
self._module_id,
|
|
383
|
+
self._interval,
|
|
384
|
+
)
|
|
385
|
+
return True
|
|
386
|
+
|
|
387
|
+
def stop(self) -> None:
|
|
388
|
+
self._stop.set()
|
|
389
|
+
if self._thread is not None:
|
|
390
|
+
self._thread.join(timeout=self._interval + 2)
|
|
391
|
+
self._thread = None
|
|
392
|
+
try:
|
|
393
|
+
self._client.close()
|
|
394
|
+
except Exception as e: # noqa: BLE001
|
|
395
|
+
logger.debug("gateway client close: %s", e)
|
|
396
|
+
logger.info("gateway client stopped")
|