Skip to content

Commit 5cb9be7

Browse files
committed
Reduce RFC payloads and reuse browser roadmap views
1 parent 1532547 commit 5cb9be7

10 files changed

Lines changed: 360 additions & 68 deletions

File tree

‎doc/architecture/SPEC/rfc_service.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@
4545

4646
## 不变量
4747

48+
- **轻量交互。** `view=summary/detail` 为可选投影;默认 SDK 与导出契约保持完整。
49+
建议由授权分页接口读取。来源权限索引只存活于当前事务,撤销后重新计算。
50+
通用静态资源支持 gzip/ETag;登录页和私有数据保持 `no-store`。操作结果直接
51+
更新视图,复用未变的 Markdown 和 SVG 布局,更新状态/负责人而不重画;退出
52+
清除内存视图。保存过程只序列化模型一次,并保留原有规范化版本摘要。
53+
4854
- **路线图交互。** 保留源 Mermaid 的 LR 轨道、关系与上下文节点,工作状态、
4955
新增依赖和验收来自当前跟踪模型;明确的依赖决策覆盖源关系,人工删除与新增
5056
工作会反映在图中,不固定轨道数量。

‎doc/features/rfc-service.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ Source diagrams contribute only limited flowchart topology, never executable
7070
callbacks, settings, or styles. Application event handlers supply node actions.
7171
SVG styles come from the existing same-origin stylesheet, preserving the CSP.
7272

73+
The browser requests `view=summary` for RFC lists and `view=detail` for details
74+
and mutation results. These are additive compact projections; the default SDK
75+
responses and full exports remain unchanged. Suggestions are fetched from the
76+
authorized `rfcs.suggestions` endpoint in pages of 50 instead of downloading the
77+
whole discovery history. Permission filtering and counting use a transaction-local
78+
source index, rebuilt on every request so revoked grants take effect immediately.
79+
80+
Generic static assets support gzip and ETag revalidation. Authenticated data and
81+
the login shell remain `no-store`. Saves reuse the returned RFC projection,
82+
preserve scroll, zoom, and unsaved prose edits, and update SVG labels and colors
83+
without recomputing unchanged layouts. Unchanged Markdown DOM is reused; offscreen
84+
prose and task sections defer layout. Background refresh skips unchanged content
85+
and pauses during editing or an open task dialog. No private data is persisted in
86+
browser storage, and signing out clears the in-memory view state.
87+
7388
Use `request ACTION --data FILE` for all versioned actions; `--data -` reads a
7489
JSON object from stdin. It supports user administration, grants, tokens, RFCs,
7590
operations and audit history without placing credentials in arguments.

‎src/infermatrix_copilot/rfc_service/application.py‎

Lines changed: 67 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -161,14 +161,13 @@ def _rfc(self, con, principal, rfc_id, role="reader"):
161161
self._require(con, principal, row["repo_id"], role, rfc_id)
162162
return dict(row)
163163

164-
def _view(self, con, principal, row):
165-
model = json.loads(row["model"])
164+
def _view(self, con, principal, row, parsed_model=None):
165+
model = dict(parsed_model) if parsed_model is not None else json.loads(row["model"])
166+
visible = self._view_visibility(con, principal, row["repo_id"])
166167
model["observations"] = {link: item for link, item in model.get("observations", {}).items()
167-
if self._visible_source(con, principal, row["repo_id"], item.get("source"))}
168-
model["suggestions"] = [s for s in model.get("suggestions", []) if self._visible_source(
169-
con, principal, row["repo_id"], s.get("evidence", {}).get("source"))]
170-
model["features"] = [f for f in model.get("features", []) if self._visible_source(
171-
con, principal, row["repo_id"], f.get("auto_source"))]
168+
if visible(item.get("source"))}
169+
model["suggestions"] = [s for s in model.get("suggestions", []) if visible(s.get("evidence", {}).get("source"))]
170+
model["features"] = [dict(f) for f in model.get("features", []) if visible(f.get("auto_source"))]
172171
if "last_discovery" in model:
173172
model["last_discovery"] = {"proposed": sum(s.get("status") == "proposed" for s in model["suggestions"]),
174173
"applied": sum(s.get("status") == "applied" for s in model["suggestions"])}
@@ -198,13 +197,36 @@ def _view(self, con, principal, row):
198197
"updated": row["updated"], "role": role, "can_write": ROLES.get(role, 0) >= 2,
199198
"can_publish": ROLES.get(role, 0) >= 3}
200199

200+
@staticmethod
201+
def _compact_view(view, mode):
202+
if mode not in ("detail", "summary"):
203+
return view
204+
counts = {}
205+
for suggestion in view.get("suggestions", []):
206+
state = suggestion.get("status", "proposed")
207+
counts[state] = counts.get(state, 0) + 1
208+
fields = {"id", "repo_id", "title", "revision", "content_digest", "source", "state",
209+
"enrolled", "restricted", "updated", "role", "can_write", "can_publish",
210+
"implementation", "acceptance", "complete", "sync_status", "freshness",
211+
"next_actions", "last_discovery", "legacy_namespace", "namespace"}
212+
if mode == "detail":
213+
fields |= {"body", "features", "criteria", "scope", "auto_add", "max_auto_additions",
214+
"grants", "historical_claims", "historical_priorities", "ambiguities"}
215+
return {**{key: value for key, value in view.items() if key in fields},
216+
"suggestion_counts": counts, "suggestions_total": sum(counts.values()),
217+
"feature_count": len(view.get("features", [])), "criterion_count": len(view.get("criteria", []))}
218+
201219
def _save(self, con, principal, row, model, body=None, title=None):
202220
body = row["body"] if body is None else body
203221
title = row["title"] if title is None else title
204-
revision = digest(encode({"body": body, "title": title, "model": model}))
222+
serialized = encode(model)
223+
# Same canonical revision, without encoding the large model twice.
224+
revision = digest('{"body":' + encode(body) + ',"model":' + serialized + ',"title":' + encode(title) + '}')
225+
updated = self.clock()
205226
con.execute("UPDATE rfcs SET title=?,body=?,model=?,revision=?,updated=? WHERE id=?",
206-
(title, body, encode(model), revision, self.clock(), row["id"]))
207-
return self._view(con, principal, dict(con.execute("SELECT * FROM rfcs WHERE id=?", (row["id"],)).fetchone()))
227+
(title, body, serialized, revision, updated, row["id"]))
228+
current = {**row, "title": title, "body": body, "model": serialized, "revision": revision, "updated": updated}
229+
return self._view(con, principal, current, parsed_model=model)
208230

209231
def dispatch(self, principal, action, payload=None):
210232
payload = payload or {}
@@ -226,7 +248,10 @@ def dispatch(self, principal, action, payload=None):
226248
return {"source": ref.to_dict(), "title": fetched.get("title", "Imported RFC"), "body": fetched["body"], "revision": fetched.get("revision", ""), "content_digest": content_digest(fetched.get("title", "Imported RFC"), fetched["body"])}
227249
with self.store.transaction() as con:
228250
principal = self._current(con, principal)
229-
return self._dispatch(con, principal, action, payload)
251+
result = self._dispatch(con, principal, action, payload)
252+
if isinstance(result, dict) and "repo_id" in result and "features" in result:
253+
result = self._compact_view(result, payload.get("view"))
254+
return result
230255

231256
def _dispatch(self, con, p, action, data):
232257
now = self.clock()
@@ -361,7 +386,7 @@ def _dispatch(self, con, p, action, data):
361386
view = self._view(con, p, dict(row))
362387
if data.get("query") and data["query"].casefold() not in (view["title"] + view["body"]).casefold():
363388
continue
364-
result.append(view)
389+
result.append(self._compact_view(view, data.get("view")))
365390
return {"rfcs": result}
366391
if action == "rfcs.draft":
367392
rid = data.get("repo_id", "")
@@ -650,6 +675,36 @@ def _visible_source(self, con, principal, repo_id, source):
650675
except RFCError:
651676
return False
652677

678+
def _view_visibility(self, con, principal, repo_id):
679+
"""Build an ACL index for this transaction only; never cache user authority."""
680+
roots = {r["id"]: r["root"] for r in con.execute("SELECT id,root FROM repositories")}
681+
blocked, blocked_paths = set(), set()
682+
aliases = {"pull_request": "pr", "pull": "pr"}
683+
684+
def identity(ref):
685+
repository = ref.repository.casefold() if ref.provider == "github" else ref.repository
686+
return ref.provider, repository, aliases.get(ref.kind, ref.kind), ref.identifier or ref.path
687+
688+
for row in con.execute("SELECT id,repo_id,source FROM rfcs WHERE source!='{}'"):
689+
if ROLES.get(self._role(con, principal, row["repo_id"], row["id"]), 0) >= 1:
690+
continue
691+
ref = SourceRef.from_dict(json.loads(row["source"]))
692+
blocked.add(identity(ref))
693+
if ref.provider == "local":
694+
blocked_paths.add((Path(roots[row["repo_id"]]) / (ref.path or ref.identifier)).resolve())
695+
696+
def visible(source):
697+
if not source:
698+
return True
699+
try:
700+
ref = SourceRef.from_dict(source)
701+
if ref.provider == "local" and repo_id in roots:
702+
return (Path(roots[repo_id]) / (ref.path or ref.identifier)).resolve() not in blocked_paths
703+
return identity(ref) not in blocked
704+
except RFCError:
705+
return False
706+
return visible
707+
653708
@staticmethod
654709
def _features(features, validate=True):
655710
if not isinstance(features, list):

‎src/infermatrix_copilot/rfc_service/http.py‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77

88
import ipaddress
99
import json
10+
import gzip
11+
import hashlib
12+
from functools import lru_cache
1013
from http.cookies import CookieError, SimpleCookie
1114
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
1215
from importlib.resources import files
@@ -41,6 +44,27 @@
4144
)
4245

4346

47+
@lru_cache(maxsize=16)
48+
def _asset(name):
49+
body = files(__package__).joinpath("web", name).read_bytes()
50+
return body, gzip.compress(body, compresslevel=5, mtime=0), 'W/"' + hashlib.sha256(body).hexdigest() + '"'
51+
52+
53+
def _accepts_gzip(value):
54+
preferences = {}
55+
for part in value.lower().split(","):
56+
name, *parameters = part.strip().split(";")
57+
quality = 1.0
58+
for parameter in parameters:
59+
if parameter.strip().startswith("q="):
60+
try:
61+
quality = float(parameter.strip()[2:])
62+
except ValueError:
63+
quality = 0.0
64+
preferences[name] = quality
65+
return preferences.get("gzip", preferences.get("*", 0.0)) > 0
66+
67+
4468
def _loopback(host: str) -> bool:
4569
if host.lower() == "localhost":
4670
return True
@@ -82,10 +106,16 @@ def log_message(self, format: str, *args: Any) -> None:
82106

83107
def _send(self, status: int, body: bytes = b"", *, content_type: str = "application/json; charset=utf-8",
84108
headers: dict[str, str] | None = None) -> None:
109+
headers = dict(headers or {})
110+
if status == 200 and len(body) >= 1024 and "Content-Encoding" not in headers and _accepts_gzip(self.headers.get("Accept-Encoding", "")):
111+
body = gzip.compress(body, compresslevel=5, mtime=0)
112+
headers["Content-Encoding"] = "gzip"
113+
headers.setdefault("Vary", "Accept-Encoding")
85114
self.send_response(status)
86115
self.send_header("Content-Type", content_type)
87-
self.send_header("Content-Length", str(len(body)))
88-
self.send_header("Cache-Control", "no-store")
116+
if status not in (204, 304):
117+
self.send_header("Content-Length", str(len(body)))
118+
self.send_header("Cache-Control", headers.pop("Cache-Control", "no-store"))
89119
self.send_header("X-Content-Type-Options", "nosniff")
90120
self.send_header("Referrer-Policy", "no-referrer")
91121
self.send_header("X-Frame-Options", "DENY")
@@ -197,8 +227,17 @@ def _get(self) -> None:
197227
path, query = self._path()
198228
if path in _STATIC:
199229
name, mime = _STATIC[path]
200-
body = files(__package__).joinpath("web", name).read_bytes()
201-
self._send(200, body, content_type=mime)
230+
body, compressed, etag = _asset(name)
231+
headers = {}
232+
if name != "index.html":
233+
headers = {"ETag": etag, "Cache-Control": "public, max-age=0, must-revalidate"}
234+
if etag in [value.strip() for value in self.headers.get("If-None-Match", "").split(",")]:
235+
self._send(304, content_type=mime, headers=headers)
236+
return
237+
if _accepts_gzip(self.headers.get("Accept-Encoding", "")):
238+
body = compressed
239+
headers["Content-Encoding"] = "gzip"
240+
self._send(200, body, content_type=mime, headers=headers)
202241
return
203242
# Authenticate before selecting a data route, including legacy aliases.
204243
principal = self._principal()

0 commit comments

Comments
 (0)