ms-cli 0.2.0__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 (67) hide show
  1. ad_cli/__init__.py +6 -0
  2. ad_cli/__main__.py +6 -0
  3. ad_cli/auth.py +351 -0
  4. ad_cli/cli.py +278 -0
  5. ad_cli/discovery.py +243 -0
  6. ad_cli/dynamic.py +816 -0
  7. ad_cli/errors.py +45 -0
  8. ad_cli/http.py +424 -0
  9. ad_cli/invoke.py +652 -0
  10. ad_cli/main.py +703 -0
  11. cann_cli/__init__.py +6 -0
  12. cann_cli/__main__.py +6 -0
  13. cann_cli/auth.py +351 -0
  14. cann_cli/cli.py +278 -0
  15. cann_cli/discovery.py +243 -0
  16. cann_cli/dynamic.py +816 -0
  17. cann_cli/errors.py +45 -0
  18. cann_cli/http.py +424 -0
  19. cann_cli/invoke.py +652 -0
  20. cann_cli/main.py +703 -0
  21. ms_cli/__init__.py +6 -0
  22. ms_cli/__main__.py +6 -0
  23. ms_cli/auth.py +351 -0
  24. ms_cli/cli.py +278 -0
  25. ms_cli/discovery.py +243 -0
  26. ms_cli/dynamic.py +816 -0
  27. ms_cli/errors.py +45 -0
  28. ms_cli/http.py +424 -0
  29. ms_cli/invoke.py +652 -0
  30. ms_cli/main.py +703 -0
  31. ms_cli-0.2.0.dist-info/METADATA +444 -0
  32. ms_cli-0.2.0.dist-info/RECORD +67 -0
  33. ms_cli-0.2.0.dist-info/WHEEL +5 -0
  34. ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
  35. ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
  36. ms_cli-0.2.0.dist-info/top_level.txt +5 -0
  37. oed_cli/__init__.py +6 -0
  38. oed_cli/__main__.py +6 -0
  39. oed_cli/auth.py +1629 -0
  40. oed_cli/cli.py +297 -0
  41. oed_cli/defaults.toml +44 -0
  42. oed_cli/discovery.py +243 -0
  43. oed_cli/dynamic.py +816 -0
  44. oed_cli/errors.py +45 -0
  45. oed_cli/http.py +423 -0
  46. oed_cli/invoke.py +651 -0
  47. oed_cli/main.py +782 -0
  48. ogd_cli/__init__.py +6 -0
  49. ogd_cli/__main__.py +6 -0
  50. ogd_cli/auth.py +351 -0
  51. ogd_cli/cli.py +278 -0
  52. ogd_cli/discovery.py +243 -0
  53. ogd_cli/dynamic.py +816 -0
  54. ogd_cli/errors.py +45 -0
  55. ogd_cli/http.py +424 -0
  56. ogd_cli/invoke.py +652 -0
  57. ogd_cli/main.py +703 -0
  58. oud_cli/__init__.py +6 -0
  59. oud_cli/__main__.py +6 -0
  60. oud_cli/auth.py +351 -0
  61. oud_cli/cli.py +278 -0
  62. oud_cli/discovery.py +243 -0
  63. oud_cli/dynamic.py +816 -0
  64. oud_cli/errors.py +45 -0
  65. oud_cli/http.py +424 -0
  66. oud_cli/invoke.py +652 -0
  67. oud_cli/main.py +703 -0
oed_cli/cli.py ADDED
@@ -0,0 +1,297 @@
1
+ """Click command surface for ``oed``.
2
+
3
+ Reserved (built-in) commands:
4
+ oed --version
5
+ oed info
6
+ oed services
7
+ oed schema <service>[.<method>]
8
+ oed cache {show,clear,refresh}
9
+ oed auth {status,token,logout,login,login --manual}
10
+
11
+ Dynamic dispatch (``oed <service> <method> ...``) lives in :mod:`oed_cli.main`
12
+ and is documented in ``docs/cli-design.md`` (v0.2).
13
+
14
+ ``oed --help`` additionally lists every auto-discovered service so newcomers
15
+ can see what the CLI exposes without reading docs first.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import datetime as dt
21
+ import json
22
+ import sys
23
+ from typing import Any
24
+
25
+ import click
26
+
27
+ from . import __version__
28
+ from .auth import auth_group, run_login
29
+ from .discovery import (
30
+ CACHE_TTL_SECONDS,
31
+ DiscoveryFeed,
32
+ ServiceMeta,
33
+ current_community,
34
+ fetch_discovery,
35
+ fetch_spec,
36
+ )
37
+ from .errors import OedError
38
+ from .http import resolve_gateway
39
+
40
+
41
+ def _print_json(data: Any, *, error: bool = False) -> None:
42
+ click.echo(json.dumps(data, ensure_ascii=False, indent=2), err=error, color=False)
43
+
44
+
45
+ def _resolve_feed(*, force_refresh: bool) -> DiscoveryFeed:
46
+ try:
47
+ return fetch_discovery(community=None, force_refresh=force_refresh)
48
+ except OedError as exc:
49
+ _print_json(exc.to_dict(), error=True)
50
+ sys.exit(exc.code)
51
+
52
+
53
+ class OedCli(click.Group):
54
+ """Click group that decorates ``--help`` with the live discovery feed.
55
+
56
+ Falls back gracefully if the gateway is unreachable / the cache is empty:
57
+ no extra section in that case, the standard help still renders.
58
+ """
59
+
60
+ def get_help(self, ctx: click.Context) -> str:
61
+ original = super().get_help(ctx)
62
+ extra = self._services_help_section()
63
+ return f"{original}\n\n{extra}" if extra else original
64
+
65
+ @staticmethod
66
+ def _services_help_section() -> str | None:
67
+ try:
68
+ feed = fetch_discovery()
69
+ except Exception:
70
+ return None
71
+ community = current_community()
72
+ services = feed.for_community(community)
73
+ if not services:
74
+ return None
75
+
76
+ widths = {"name": max(len(s.service_name) for s in services)}
77
+ rows: list[str] = []
78
+ for s in services:
79
+ desc = (s.description or s.title or "").strip().split("\n", 1)[0]
80
+ if len(desc) > 78:
81
+ desc = desc[:75] + "..."
82
+ rows.append(f" {s.service_name.ljust(widths['name'])} {desc}")
83
+
84
+ first = services[0].service_name
85
+ title = (
86
+ f"Auto-discovered services (community='{community}', "
87
+ f"{len(services)} service{'' if len(services) == 1 else 's'} "
88
+ f"resolved live from the gateway):"
89
+ )
90
+ return (
91
+ f"{title}\n\n"
92
+ + "\n".join(rows)
93
+ + "\n\n"
94
+ "Every declared query / path parameter on an operation is exposed\n"
95
+ "as its own --<kebab-case> flag. Use `oed <service> --help` to list\n"
96
+ "operations, then `oed <service> <operation> --help` to see the\n"
97
+ "flags for that operation. For the full spec: `oed schema <service>`.\n"
98
+ "\n"
99
+ "Quickstart:\n"
100
+ f" oed {first} # list operations\n"
101
+ f" oed cve getSecurityNoticeByCveId --cve-id CVE-2019-10082\n"
102
+ f" oed meeting listMeetings --date 2026-07-29\n"
103
+ )
104
+
105
+
106
+ def _format_service(service: ServiceMeta, *, age_s: float | None) -> dict[str, Any]:
107
+ out: dict[str, Any] = {
108
+ "name": service.name,
109
+ "service_name": service.service_name,
110
+ "community": service.community,
111
+ "title": service.title,
112
+ "version": service.version,
113
+ }
114
+ if service.description:
115
+ out["description"] = service.description
116
+ if service.base_url:
117
+ out["base_url"] = service.base_url
118
+ if age_s is not None:
119
+ out["fetched_seconds_ago"] = round(age_s, 1)
120
+ return out
121
+
122
+
123
+ @click.group(
124
+ cls=OedCli,
125
+ context_settings={"help_option_names": ["-h", "--help"]},
126
+ invoke_without_command=True,
127
+ )
128
+ @click.version_option(version=__version__, prog_name="oed")
129
+ @click.option(
130
+ "--no-color",
131
+ is_flag=True,
132
+ default=True,
133
+ help="Disable ANSI colors in output (default: true, AI-friendly).",
134
+ )
135
+ @click.pass_context
136
+ def cli(ctx: click.Context, no_color: bool) -> None:
137
+ """oed — openEuler Infra command line. Auto-discovered, AI-friendly."""
138
+ ctx.ensure_object(dict)
139
+ ctx.obj["no_color"] = no_color
140
+
141
+
142
+ # Register reserved sub-groups from sibling modules.
143
+ cli.add_command(auth_group)
144
+
145
+
146
+ @cli.command("login")
147
+ @click.option(
148
+ "--manual",
149
+ "-m",
150
+ is_flag=True,
151
+ help="Paste token + cookie from terminal instead of using device-flow.",
152
+ )
153
+ def login_cmd(manual: bool) -> None:
154
+ """Shortcut for ``oed auth login`` (device-flow login)."""
155
+
156
+ run_login(manual)
157
+
158
+
159
+ @cli.command("info")
160
+ def info() -> None:
161
+ """Show gateway reachability and the discovery snapshot summary."""
162
+ import time
163
+
164
+ feed = _resolve_feed(force_refresh=False)
165
+ age = time.time() - feed.fetched_at
166
+
167
+ services = feed.services
168
+ payload = {
169
+ "ok": True,
170
+ "oed_version": __version__,
171
+ "gateway": resolve_gateway(),
172
+ "community": current_community(),
173
+ "services_total": len(services),
174
+ "communities_seen": sorted({s.community for s in services}),
175
+ "cache": {
176
+ "ttl_seconds": CACHE_TTL_SECONDS,
177
+ "stale": age >= CACHE_TTL_SECONDS,
178
+ "fetched_seconds_ago": round(age, 1),
179
+ "fetched_at_iso": dt.datetime.fromtimestamp(
180
+ feed.fetched_at, tz=dt.timezone.utc
181
+ ).isoformat(),
182
+ },
183
+ }
184
+ _print_json(payload)
185
+
186
+
187
+ @cli.command("services")
188
+ @click.option("--community", default=None, help="Limit to one community (default: current).")
189
+ @click.option("--refresh", is_flag=True, help="Force re-fetch the discovery feed first.")
190
+ def services_cmd(community: str | None, refresh: bool) -> None:
191
+ """List services in the discovery feed."""
192
+ import time
193
+
194
+ feed = _resolve_feed(force_refresh=refresh)
195
+ target = community or current_community()
196
+ items = [s for s in feed.services if s.community == target]
197
+ age = time.time() - feed.fetched_at
198
+ _print_json([_format_service(s, age_s=age) for s in items])
199
+
200
+
201
+ @cli.command("schema")
202
+ @click.argument("target")
203
+ @click.option("--refresh", is_flag=True, help="Force re-fetch the discovery feed first.")
204
+ def schema_cmd(target: str, refresh: bool) -> None:
205
+ """Print OpenAPI 3.x spec for SERVICE[.METHOD] from the current community."""
206
+ if "." in target:
207
+ service_name, method = target.split(".", 1)
208
+ else:
209
+ service_name, method = target, None
210
+
211
+ feed = _resolve_feed(force_refresh=refresh)
212
+ community = current_community()
213
+ try:
214
+ service = feed.find_service(community, service_name)
215
+ except OedError as exc:
216
+ _print_json(exc.to_dict(), error=True)
217
+ sys.exit(exc.code)
218
+
219
+ try:
220
+ spec = fetch_spec(service)
221
+ except OedError as exc:
222
+ _print_json(exc.to_dict(), error=True)
223
+ sys.exit(exc.code)
224
+
225
+ if method is None:
226
+ _print_json(spec)
227
+ return
228
+
229
+ paths: dict[str, Any] = spec.get("paths", {})
230
+ matches: list[dict[str, Any]] = []
231
+ for path, item in paths.items():
232
+ for verb, op in item.items():
233
+ if verb.lower() not in {"get", "post", "put", "patch", "delete", "head", "options"}:
234
+ continue
235
+ if op.get("operationId") == method or method in (path, f"{verb.upper()} {path}"):
236
+ matches.append({"path": path, "method": verb.upper(), "operation": op})
237
+ if not matches:
238
+ _print_json(
239
+ {
240
+ "ok": False,
241
+ "code": 4,
242
+ "error": "method_not_found",
243
+ "message": f"no path matches method '{method}' on service '{service_name}'",
244
+ "available_paths": sorted(paths.keys()),
245
+ },
246
+ error=True,
247
+ )
248
+ sys.exit(4)
249
+
250
+ _print_json({"service": service.name, "matches": matches})
251
+
252
+
253
+ @cli.group()
254
+ def cache() -> None:
255
+ """Manage the local discovery cache."""
256
+
257
+
258
+ @cache.command("show")
259
+ def cache_show() -> None:
260
+ from .discovery import _cache_path
261
+
262
+ p = _cache_path()
263
+ if not p.is_file():
264
+ _print_json({"cached": False, "path": str(p)})
265
+ return
266
+ stat = p.stat()
267
+ _print_json(
268
+ {
269
+ "cached": True,
270
+ "path": str(p),
271
+ "size_bytes": stat.st_size,
272
+ "modified_iso": dt.datetime.fromtimestamp(
273
+ stat.st_mtime, tz=dt.timezone.utc
274
+ ).isoformat(),
275
+ "ttl_seconds": CACHE_TTL_SECONDS,
276
+ }
277
+ )
278
+
279
+
280
+ @cache.command("clear")
281
+ def cache_clear() -> None:
282
+ from .discovery import _cache_path
283
+
284
+ p = _cache_path()
285
+ if p.is_file():
286
+ p.unlink()
287
+ _print_json({"ok": True, "cleared": str(p)})
288
+
289
+
290
+ @cache.command("refresh")
291
+ def cache_refresh() -> None:
292
+ feed = fetch_discovery(community=None, force_refresh=True)
293
+ _print_json({"ok": True, "services_total": len(feed.services)})
294
+
295
+
296
+ if __name__ == "__main__":
297
+ cli()
oed_cli/defaults.toml ADDED
@@ -0,0 +1,44 @@
1
+ # oed-cli defaults — bundled into the wheel, read by `oed_cli.auth.load_defaults`.
2
+ #
3
+ # Override priority (highest wins):
4
+ # 1. environment variable (OED_APP_ID, OED_DEVICE_URL, OED_AUTHORIZE_URL, OED_TOKEN_URL, OED_USERINFO_URL)
5
+ # 2. this file
6
+ #
7
+ # Edit this file in a fork build to point at your own openEuler usercenter
8
+ # deployment without recompiling.
9
+
10
+ [oauth]
11
+ # Public OAuth client identifier (RFC 8628 §3.1: device-flow clients MUST be public).
12
+ client_id = "623c3c2f1eca5ad5fca6c58a"
13
+
14
+ # openEuler oneid/oidc issuer URL. Used as MSAL oidc_authority for OIDC discovery.
15
+ # MSAL will fetch {device_url}/.well-known/openid-configuration to discover endpoints.
16
+ # Must include at least one path segment (MSAL requirement).
17
+ # When oneid deploys RFC 8628, update this to the actual OIDC issuer URL.
18
+ # Override with OED_DEVICE_URL env var for testing.
19
+ device_url = "https://omapi.osinfra.cn/oneid/oidc"
20
+
21
+ # Granular endpoint overrides (set these individually for fork builds):
22
+ authorize_url = "https://omapi.osinfra.cn/oneid/oidc/authorize"
23
+ token_url = "https://omapi.osinfra.cn/oneid/oidc/token"
24
+ device_authorization_url = "https://omapi.osinfra.cn/oneid/oidc/device/code"
25
+
26
+ # OAuth scopes requested at device-flow initiation. Hardcoded in
27
+ # src/oed_cli/auth.py as `_BASE_SCOPES` (email + id_token) because these
28
+ # are part of the wire contract with openEuler oneid; reading them from
29
+ # this file caused stale-TOML footguns (shipped wheel didn't include
30
+ # `id_token` and silent refresh broke). Override at runtime with the
31
+ # `OED_SCOPES` env var (comma-separated).
32
+ #
33
+ # MSAL auto-appends the reserved scopes (openid/profile/offline_access)
34
+ # and REFUSES them if passed explicitly, so this key is intentionally
35
+ # omitted — see `_BASE_SCOPES` in auth.py for the source of truth.
36
+
37
+ userinfo_url = "https://omapi.osinfra.cn/oneid/oidc/user"
38
+
39
+ # Per-user CLI service allow-list. Fetched ONCE at `oed auth login` success
40
+ # (after /token returns) and cached in auth.json as a `allowlist` field.
41
+ # Subsequent CLI invocations only consult the local cache — no per-call
42
+ # HTTP fetch. Response shape: {"data": "service-a,service-b,..."}.
43
+ # Override with OED_USER_DATA_URL env var for fork / test deployments.
44
+ cli_user_data_url = "https://omapi.osinfra.cn/oneid/oidc/device/user-data"
oed_cli/discovery.py ADDED
@@ -0,0 +1,243 @@
1
+ """Discovery feed retrieval, parsing and local caching.
2
+
3
+ Reads ``https://api-gateway.osinfra.cn/discovery/apis`` (per ``context/discoverAPI.md``)
4
+ and caches the parsed feed under ``~/.cache/oed-cli/discovery.json``. A fresh
5
+ fetch happens only when the cache is older than :data:`CACHE_TTL_SECONDS`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ import platform
14
+ import time
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from .errors import NotFoundError
20
+ from .http import apis_url, get_json
21
+
22
+ CACHE_TTL_SECONDS = 600 # 10 minutes
23
+ # Tolerance for clock skew when judging cache freshness. A cached
24
+ # ``__oed_fetched_at`` strictly newer than ``now + _CLOCK_SKEW_SECONDS`` is
25
+ # treated as a poisoned cache (issue #22): an attacker who can write the
26
+ # cache file can set a future timestamp so ``now - fetched_at`` is always
27
+ # negative and the TTL check never expires the entry. Rejecting future
28
+ # timestamps closes the "never-expires" bypass. 300s absorbs legitimate NTP
29
+ # drift between the writing process and a later reader. NOTE: kept in sync
30
+ # with ``dynamic._CLOCK_SKEW_SECONDS`` — both must use the same value.
31
+ _CLOCK_SKEW_SECONDS = 300
32
+ DEFAULT_COMMUNITY = "openeuler"
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ServiceMeta:
37
+ name: str
38
+ service_name: str
39
+ community: str
40
+ title: str
41
+ version: str
42
+ description: str
43
+ base_url: str
44
+
45
+ @classmethod
46
+ def from_raw(cls, raw: dict[str, Any]) -> ServiceMeta:
47
+ return cls(
48
+ name=raw["name"],
49
+ service_name=raw["service_name"],
50
+ community=raw["community"],
51
+ title=raw.get("title", ""),
52
+ version=raw.get("version", ""),
53
+ description=raw.get("description", ""),
54
+ base_url=raw.get("base_url", ""),
55
+ )
56
+
57
+
58
+ @dataclass
59
+ class DiscoveryFeed:
60
+ fetched_at: float
61
+ raw: dict[str, Any]
62
+ services: list[ServiceMeta] = field(default_factory=list)
63
+
64
+ def for_community(self, community: str) -> list[ServiceMeta]:
65
+ return [s for s in self.services if s.community == community]
66
+
67
+ def find_service(self, community: str, service_name: str) -> ServiceMeta:
68
+ for s in self.services:
69
+ if s.community == community and s.service_name == service_name:
70
+ return s
71
+ raise NotFoundError(
72
+ f"service '{service_name}' not found in community '{community}'",
73
+ kind="service_not_found",
74
+ hint="Run `oed services` to see the registered services.",
75
+ )
76
+
77
+
78
+ def _cache_dir() -> Path:
79
+ override = os.environ.get("OED_CACHE_DIR")
80
+ if override:
81
+ return Path(override).expanduser()
82
+ if platform.system() == "Windows":
83
+ base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
84
+ return base / "oed-cli" / "cache"
85
+ xdg = os.environ.get("XDG_CACHE_HOME")
86
+ base = Path(xdg) if xdg else Path.home() / ".cache"
87
+ return base / "oed-cli"
88
+
89
+
90
+ def _cache_path() -> Path:
91
+ return _cache_dir() / "discovery.json"
92
+
93
+
94
+ def auth_token_path() -> Path:
95
+ """Path to the auth.json file (sibling of ``discovery.json``).
96
+
97
+ Lives under the same XDG / Windows-LOCALAPPDATA cache directory as the
98
+ discovery feed, so a single ``OED_CACHE_DIR`` override covers both.
99
+ """
100
+ return _cache_dir() / "auth.json"
101
+
102
+
103
+ def ag_token_path(service: str = "ag") -> Path:
104
+ """Path to an AtomGit (``ag``) PAT plaintext-fallback file.
105
+
106
+ Lives under a ``tokens/`` subdir of the cache dir so ``oed cache clear``
107
+ (which only unlinks ``discovery.json``) can never wipe credentials. The
108
+ real secret prefers the OS keystore via :class:`oed_cli.auth._SecureStore`;
109
+ this file is only the 0600 fallback when keyring is unreachable.
110
+ """
111
+
112
+ return _cache_dir() / "tokens" / f"{service}.json"
113
+
114
+
115
+ def _read_cache(path: Path) -> DiscoveryFeed | None:
116
+ if not path.is_file():
117
+ return None
118
+ try:
119
+ raw = json.loads(path.read_text(encoding="utf-8"))
120
+ except (OSError, json.JSONDecodeError):
121
+ return None
122
+ return _materialize(raw)
123
+
124
+
125
+ def _materialize(raw: dict[str, Any]) -> DiscoveryFeed | None:
126
+ """Build a :class:`DiscoveryFeed` from a raw cache dict.
127
+
128
+ Returns ``None`` (→ caller refetches) when the cache is poisoned: a
129
+ ``__oed_fetched_at`` timestamp in the future beyond :data:`_CLOCK_SKEW_SECONDS`
130
+ would otherwise make the TTL check never expire the entry (issue #22).
131
+ """
132
+
133
+ fetched_at = float(raw.get("__oed_fetched_at", 0))
134
+ if fetched_at > time.time() + _CLOCK_SKEW_SECONDS:
135
+ return None
136
+ services = [ServiceMeta.from_raw(s) for s in raw.get("services", [])]
137
+ return DiscoveryFeed(fetched_at=fetched_at, raw=raw, services=services)
138
+
139
+
140
+ def _atomic_write_json(path: Path, data: dict[str, Any], *, mode: int | None = None) -> None:
141
+ """Write ``data`` as JSON to ``path`` atomically (tmp + replace).
142
+
143
+ Cache files are public data (discovery feed / OpenAPI specs), so by
144
+ default no restrictive perms are forced — only the torn-write race is
145
+ closed. Used by both the discovery feed cache and the per-service spec
146
+ cache (see :mod:`oed_cli.dynamic`) so a crash mid-write never leaves a
147
+ half-written file that a later read would parse as corrupt.
148
+
149
+ When ``mode`` is given (e.g. ``0o600``) the temp file is chmod'd before
150
+ the atomic replace, so the final file honors it. This is used for the
151
+ spec cache and the integrity ledger: a non-owner must NOT be able to
152
+ write a forged ``repr_digest`` (that would let a tampered spec pass local
153
+ verification). The brief pre-chmod window only exposes a public hash, so
154
+ read-leakage is harmless; what matters is blocking non-owner writes.
155
+ """
156
+
157
+ tmp = path.with_suffix(path.suffix + ".tmp")
158
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
159
+ if mode is not None:
160
+ with contextlib.suppress(OSError):
161
+ os.chmod(tmp, mode)
162
+ try:
163
+ tmp.replace(path)
164
+ except OSError:
165
+ # Best-effort: a failed replace (e.g. cross-device tmp) leaves the
166
+ # .tmp behind but never corrupts the existing cache. Callers treat
167
+ # cache write failures as non-fatal.
168
+ with contextlib.suppress(OSError):
169
+ tmp.unlink(missing_ok=True)
170
+ raise
171
+
172
+
173
+ def _write_cache(path: Path, feed: DiscoveryFeed) -> None:
174
+ payload = {
175
+ "__oed_fetched_at": feed.fetched_at,
176
+ "services": [s.__dict__ for s in feed.services],
177
+ }
178
+ try:
179
+ path.parent.mkdir(parents=True, exist_ok=True)
180
+ _atomic_write_json(path, payload)
181
+ except OSError:
182
+ # Cache is best-effort; failures here are not fatal.
183
+ pass
184
+
185
+
186
+ def _fetch_remote(community: str | None) -> DiscoveryFeed:
187
+ """Hit the gateway. If ``community`` is provided, request that variant so the
188
+ payload layout matches the per-community view; otherwise request the global
189
+ payload which is keyed by community."""
190
+
191
+ if community:
192
+ data = get_json(apis_url(), params={"community": community})
193
+ services: list[ServiceMeta] = []
194
+ if isinstance(data, list):
195
+ services = [ServiceMeta.from_raw(s) for s in data]
196
+ else:
197
+ data = get_json(apis_url())
198
+ services = []
199
+ communities = data.get("communities", {}) if isinstance(data, dict) else {}
200
+ if isinstance(communities, dict):
201
+ for arr in communities.values():
202
+ if isinstance(arr, list):
203
+ services.extend(ServiceMeta.from_raw(s) for s in arr)
204
+
205
+ raw_payload = data if isinstance(data, dict) else {"services": data}
206
+ return DiscoveryFeed(
207
+ fetched_at=time.time(), raw=raw_payload, services=services
208
+ )
209
+
210
+
211
+ def fetch_discovery(*, community: str | None = None, force_refresh: bool = False) -> DiscoveryFeed:
212
+ """Return the discovery feed, using cache when fresh."""
213
+
214
+ cache_file = _cache_path()
215
+ cached = None if force_refresh else _read_cache(cache_file)
216
+ if cached is not None and (time.time() - cached.fetched_at) < CACHE_TTL_SECONDS:
217
+ return cached
218
+
219
+ feed = _fetch_remote(community)
220
+ _write_cache(cache_file, feed)
221
+ return feed
222
+
223
+
224
+ def fetch_spec(service: ServiceMeta) -> dict[str, Any]:
225
+ """Return the OpenAPI 3.x spec for one service, parsed JSON.
226
+
227
+ Delegates to :func:`oed_cli.dynamic.fetch_service_spec`, which adds a
228
+ per-service file cache, ``If-None-Match``/304 negotiation, and
229
+ ``Repr-Digest`` verification (plus the local-cache integrity guards).
230
+ Previously this entry point fetched fresh on every call and discarded the
231
+ returned ETag, so 304 never fired and the spec body was re-downloaded each
232
+ time — the cached fetcher fixes that without changing this function's
233
+ contract (parsed JSON, or raises :class:`NotFoundError`). The import is
234
+ deferred to avoid a discovery ↔ dynamic import cycle.
235
+ """
236
+
237
+ from .dynamic import fetch_service_spec # deferred: avoid import cycle
238
+
239
+ return fetch_service_spec(service)
240
+
241
+
242
+ def current_community() -> str:
243
+ return os.environ.get("OED_COMMUNITY", DEFAULT_COMMUNITY)