simple-module-remote 0.0.50__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.
- simple_module_remote/__init__.py +12 -0
- simple_module_remote/commands/__init__.py +1 -0
- simple_module_remote/commands/api_cmd.py +157 -0
- simple_module_remote/commands/auth_cmd.py +166 -0
- simple_module_remote/commands/doctor_cmd.py +157 -0
- simple_module_remote/commands/env_cmd.py +198 -0
- simple_module_remote/commands/generated.py +50 -0
- simple_module_remote/commands/root.py +186 -0
- simple_module_remote/commands/runtime.py +263 -0
- simple_module_remote/commands/schema_cmd.py +155 -0
- simple_module_remote/commands/schema_fetch.py +129 -0
- simple_module_remote/commands/schema_source.py +181 -0
- simple_module_remote/config/__init__.py +1 -0
- simple_module_remote/config/_file_store.py +182 -0
- simple_module_remote/config/_private_dir.py +191 -0
- simple_module_remote/config/credentials.py +296 -0
- simple_module_remote/config/environments.py +186 -0
- simple_module_remote/config/paths.py +32 -0
- simple_module_remote/config/resolve.py +96 -0
- simple_module_remote/curated/__init__.py +1 -0
- simple_module_remote/generate/__init__.py +1 -0
- simple_module_remote/generate/body.py +198 -0
- simple_module_remote/generate/confirm.py +38 -0
- simple_module_remote/generate/context.py +38 -0
- simple_module_remote/generate/emit.py +278 -0
- simple_module_remote/generate/execute.py +220 -0
- simple_module_remote/generate/naming.py +69 -0
- simple_module_remote/generate/operations.py +181 -0
- simple_module_remote/generate/pagination.py +80 -0
- simple_module_remote/generate/pairs.py +22 -0
- simple_module_remote/generate/params.py +210 -0
- simple_module_remote/generate/prepare.py +134 -0
- simple_module_remote/generate/tree.py +59 -0
- simple_module_remote/generate/trust.py +42 -0
- simple_module_remote/generate/validate.py +136 -0
- simple_module_remote/http/__init__.py +1 -0
- simple_module_remote/http/client.py +292 -0
- simple_module_remote/http/errors.py +59 -0
- simple_module_remote/http/safety.py +124 -0
- simple_module_remote/output/__init__.py +1 -0
- simple_module_remote/output/reasons.py +17 -0
- simple_module_remote/output/render.py +149 -0
- simple_module_remote/output/sanitize.py +32 -0
- simple_module_remote/py.typed +0 -0
- simple_module_remote/schema/__init__.py +1 -0
- simple_module_remote/schema/cache.py +187 -0
- simple_module_remote/schema/loader.py +56 -0
- simple_module_remote-0.0.50.dist-info/METADATA +73 -0
- simple_module_remote-0.0.50.dist-info/RECORD +51 -0
- simple_module_remote-0.0.50.dist-info/WHEEL +4 -0
- simple_module_remote-0.0.50.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""The click command generated for one OpenAPI operation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.commands.runtime import state_of
|
|
10
|
+
from simple_module_remote.generate.operations import Operation
|
|
11
|
+
from simple_module_remote.generate.pagination import pagination_style
|
|
12
|
+
from simple_module_remote.generate.params import (
|
|
13
|
+
click_params_for,
|
|
14
|
+
json_response_schema,
|
|
15
|
+
returns_list,
|
|
16
|
+
success_is_json,
|
|
17
|
+
)
|
|
18
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
19
|
+
|
|
20
|
+
__all__ = ["operation_command"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def operation_command(op: Operation, root: dict) -> click.Command:
|
|
24
|
+
pageable = (
|
|
25
|
+
returns_list(op, root) and pagination_style(op, json_response_schema(op, root)) is not None
|
|
26
|
+
)
|
|
27
|
+
params = click_params_for(op, list_returning=pageable)
|
|
28
|
+
for param in params:
|
|
29
|
+
if isinstance(param, click.Option) and param.help:
|
|
30
|
+
param.help = sanitize(param.help)
|
|
31
|
+
|
|
32
|
+
def callback(**values: Any) -> None:
|
|
33
|
+
ctx = click.get_current_context()
|
|
34
|
+
state = state_of(ctx)
|
|
35
|
+
code = state.run(op, values)
|
|
36
|
+
if code:
|
|
37
|
+
ctx.exit(code)
|
|
38
|
+
|
|
39
|
+
route = sanitize(f"{op.method} {op.path}")
|
|
40
|
+
summary = sanitize(op.summary)
|
|
41
|
+
text = sanitize(op.description) or summary
|
|
42
|
+
if not success_is_json(op, root):
|
|
43
|
+
text += "\n\nThe response is not JSON: redirect stdout or use --out FILE."
|
|
44
|
+
return click.Command(
|
|
45
|
+
op.name,
|
|
46
|
+
params=params,
|
|
47
|
+
callback=callback,
|
|
48
|
+
help=f"{text}\n\n{route}" if text else route,
|
|
49
|
+
short_help=summary or None,
|
|
50
|
+
)
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""``build_cli``: the root group with generated and built-in commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from simple_module_remote import __version__ as engine_version
|
|
13
|
+
from simple_module_remote.commands.api_cmd import api
|
|
14
|
+
from simple_module_remote.commands.auth_cmd import login, logout, whoami
|
|
15
|
+
from simple_module_remote.commands.doctor_cmd import doctor
|
|
16
|
+
from simple_module_remote.commands.env_cmd import env_group
|
|
17
|
+
from simple_module_remote.commands.generated import operation_command
|
|
18
|
+
from simple_module_remote.commands.runtime import SCHEMA_BUNDLED, AppState, CliError
|
|
19
|
+
from simple_module_remote.commands.schema_cmd import schema_group
|
|
20
|
+
from simple_module_remote.commands.schema_source import (
|
|
21
|
+
SCHEMA_SOURCES,
|
|
22
|
+
RootFlags,
|
|
23
|
+
SchemaChoice,
|
|
24
|
+
choose_schema,
|
|
25
|
+
peek_root_flags,
|
|
26
|
+
)
|
|
27
|
+
from simple_module_remote.config.credentials import KeyringBackend
|
|
28
|
+
from simple_module_remote.generate.tree import build_groups
|
|
29
|
+
from simple_module_remote.schema.loader import load_schema
|
|
30
|
+
|
|
31
|
+
__all__ = ["build_cli"]
|
|
32
|
+
|
|
33
|
+
LOGIN_COMMAND = "login"
|
|
34
|
+
RAW_GROUP = "raw"
|
|
35
|
+
ENV_PARAM = "env"
|
|
36
|
+
SCHEMA_PARAM = "schema_source"
|
|
37
|
+
BUILTINS = (env_group, login, logout, whoami, doctor, schema_group, api)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _RootGroup(click.Group):
|
|
41
|
+
"""Reports every usage error with exit code 1; installs the generated groups per run."""
|
|
42
|
+
|
|
43
|
+
bundled: SchemaChoice
|
|
44
|
+
_generated: tuple[str, ...] = ()
|
|
45
|
+
|
|
46
|
+
def install(self, groups: list[click.Group]) -> None:
|
|
47
|
+
"""Replace the generated groups (top level and under ``raw``) with ``groups``."""
|
|
48
|
+
for name in self._generated:
|
|
49
|
+
self.commands.pop(name, None)
|
|
50
|
+
raw = click.Group(RAW_GROUP, help="Generated commands, mirrored under raw.")
|
|
51
|
+
for group in groups:
|
|
52
|
+
self.add_command(group)
|
|
53
|
+
raw.add_command(group)
|
|
54
|
+
self.add_command(raw)
|
|
55
|
+
self._generated = (*(g.name for g in groups if g.name), RAW_GROUP)
|
|
56
|
+
|
|
57
|
+
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
|
|
58
|
+
state = ctx.obj
|
|
59
|
+
if isinstance(state, AppState):
|
|
60
|
+
flags = self._with_defaults(ctx, peek_root_flags(args))
|
|
61
|
+
choice = choose_schema(
|
|
62
|
+
cli=state.cli,
|
|
63
|
+
defaults_path=state.defaults_path,
|
|
64
|
+
environ=state.environ,
|
|
65
|
+
flags=flags,
|
|
66
|
+
bundled=self.bundled,
|
|
67
|
+
factory=operation_command,
|
|
68
|
+
)
|
|
69
|
+
state.use_schema(choice.source, choice.path, choice.root, choice.meta, choice.note)
|
|
70
|
+
state.preselected = (
|
|
71
|
+
(flags.env, *choice.selected) if choice.selected is not None else None
|
|
72
|
+
)
|
|
73
|
+
self.install(choice.groups)
|
|
74
|
+
builtin = flags.command in {cmd.name for cmd in BUILTINS}
|
|
75
|
+
if choice.error and flags.command is not None and not builtin:
|
|
76
|
+
raise CliError(choice.error)
|
|
77
|
+
return super().parse_args(ctx, args)
|
|
78
|
+
|
|
79
|
+
@staticmethod
|
|
80
|
+
def _with_defaults(ctx: click.Context, flags: RootFlags) -> RootFlags:
|
|
81
|
+
"""Fill flags absent from the arguments from a wrapper's ``default_map``."""
|
|
82
|
+
# Click's own lookup: a callable default is called, as click will when parsing.
|
|
83
|
+
env = flags.env if flags.env is not None else ctx.lookup_default(ENV_PARAM)
|
|
84
|
+
schema = flags.schema if flags.schema is not None else ctx.lookup_default(SCHEMA_PARAM)
|
|
85
|
+
return RootFlags(
|
|
86
|
+
env if isinstance(env, str) else None,
|
|
87
|
+
schema if isinstance(schema, str) else None,
|
|
88
|
+
flags.command,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def make_context(self, *args: Any, **kwargs: Any) -> click.Context:
|
|
92
|
+
try:
|
|
93
|
+
return super().make_context(*args, **kwargs)
|
|
94
|
+
except click.exceptions.NoArgsIsHelpError:
|
|
95
|
+
raise # click's own behaviour: show the help (exit 2 in click 8.2+)
|
|
96
|
+
except click.UsageError as exc:
|
|
97
|
+
raise self._as_cli_error(exc) from None
|
|
98
|
+
|
|
99
|
+
def invoke(self, ctx: click.Context) -> Any:
|
|
100
|
+
try:
|
|
101
|
+
return super().invoke(ctx)
|
|
102
|
+
except click.exceptions.NoArgsIsHelpError:
|
|
103
|
+
raise
|
|
104
|
+
except click.UsageError as exc:
|
|
105
|
+
raise self._as_cli_error(exc) from None
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _as_cli_error(exc: click.UsageError) -> CliError:
|
|
109
|
+
if exc.ctx is not None and exc.ctx.command.name == LOGIN_COMMAND:
|
|
110
|
+
# Arguments of `login` may be a token: never echo them back.
|
|
111
|
+
return CliError("invalid use of login: see `login --help`")
|
|
112
|
+
# Only click's own parse errors point at --help; our own refusals are not usage slips.
|
|
113
|
+
hint = " (see --help)" if type(exc) is not click.UsageError else ""
|
|
114
|
+
return CliError(f"{exc.format_message()}{hint}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _show_version(
|
|
118
|
+
name: str, version: str
|
|
119
|
+
) -> Callable[[click.Context, click.Parameter, bool], None]:
|
|
120
|
+
def callback(ctx: click.Context, param: click.Parameter, value: bool) -> None:
|
|
121
|
+
if value and not ctx.resilient_parsing:
|
|
122
|
+
click.echo(f"{name} {version} (simple_module_remote {engine_version})")
|
|
123
|
+
ctx.exit()
|
|
124
|
+
|
|
125
|
+
return callback
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_cli(
|
|
129
|
+
name: str,
|
|
130
|
+
schema_path: Path,
|
|
131
|
+
defaults_path: Path | None = None,
|
|
132
|
+
*,
|
|
133
|
+
version: str = "0",
|
|
134
|
+
transport: httpx.BaseTransport | None = None,
|
|
135
|
+
keyring_backend: KeyringBackend | None = None,
|
|
136
|
+
) -> click.Group:
|
|
137
|
+
"""Assemble the CLI: built-ins, generated groups at top level and again under ``raw``.
|
|
138
|
+
|
|
139
|
+
``schema_path`` is the bundled schema; each invocation may swap in the selected
|
|
140
|
+
environment's live schema (``schema sync``) before parsing its arguments.
|
|
141
|
+
"""
|
|
142
|
+
schema = load_schema(schema_path)
|
|
143
|
+
groups = build_groups(schema, operation_command)
|
|
144
|
+
state = AppState(
|
|
145
|
+
cli=name,
|
|
146
|
+
version=version,
|
|
147
|
+
schema_path=schema_path,
|
|
148
|
+
defaults_path=defaults_path,
|
|
149
|
+
root=schema,
|
|
150
|
+
bundled_root=schema,
|
|
151
|
+
transport=transport,
|
|
152
|
+
backend=keyring_backend,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
root = _RootGroup(
|
|
156
|
+
name,
|
|
157
|
+
callback=state.begin,
|
|
158
|
+
params=[
|
|
159
|
+
click.Option(["--env", "-e", ENV_PARAM], help="Environment to use."),
|
|
160
|
+
click.Option(["--tenant", "tenant"], help="Tenant (slug or id) to act for."),
|
|
161
|
+
click.Option(
|
|
162
|
+
["--version"],
|
|
163
|
+
is_flag=True,
|
|
164
|
+
is_eager=True,
|
|
165
|
+
expose_value=False,
|
|
166
|
+
callback=_show_version(name, version),
|
|
167
|
+
help="Show the version and exit.",
|
|
168
|
+
),
|
|
169
|
+
click.Option(
|
|
170
|
+
["--schema", SCHEMA_PARAM],
|
|
171
|
+
type=click.Choice(SCHEMA_SOURCES),
|
|
172
|
+
expose_value=False,
|
|
173
|
+
help=(
|
|
174
|
+
"Command schema: live (the environment's schema from `schema sync`) or "
|
|
175
|
+
"bundled. Default: live when synced for this URL, else bundled."
|
|
176
|
+
),
|
|
177
|
+
),
|
|
178
|
+
],
|
|
179
|
+
help=f"{name}: command line for the app's REST API.",
|
|
180
|
+
)
|
|
181
|
+
root.context_settings = {"obj": state}
|
|
182
|
+
root.bundled = SchemaChoice(SCHEMA_BUNDLED, schema_path, schema, groups)
|
|
183
|
+
for builtin in BUILTINS:
|
|
184
|
+
root.add_command(builtin)
|
|
185
|
+
root.install(groups)
|
|
186
|
+
return root
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Shared per-invocation state for the root group and its commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Generator, Mapping
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from simple_module_remote import __version__ as engine_version
|
|
17
|
+
from simple_module_remote.config.credentials import (
|
|
18
|
+
CredentialError,
|
|
19
|
+
CredentialStore,
|
|
20
|
+
KeyringBackend,
|
|
21
|
+
login_hint,
|
|
22
|
+
)
|
|
23
|
+
from simple_module_remote.config.environments import (
|
|
24
|
+
Config,
|
|
25
|
+
ConfigError,
|
|
26
|
+
Environment,
|
|
27
|
+
load_config,
|
|
28
|
+
select_env,
|
|
29
|
+
validate_tenant,
|
|
30
|
+
)
|
|
31
|
+
from simple_module_remote.config.resolve import ResolvedToken, resolve_credential
|
|
32
|
+
from simple_module_remote.generate.context import RunContext
|
|
33
|
+
from simple_module_remote.generate.execute import run_operation
|
|
34
|
+
from simple_module_remote.generate.operations import Operation
|
|
35
|
+
from simple_module_remote.http.client import ApiClient
|
|
36
|
+
from simple_module_remote.http.errors import EXIT_USAGE, REDIRECT_MIN, ApiError, UnsafePathError
|
|
37
|
+
from simple_module_remote.schema.cache import CacheMeta
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"SCHEMA_BUNDLED",
|
|
41
|
+
"SCHEMA_LIVE",
|
|
42
|
+
"WHOAMI_PATH",
|
|
43
|
+
"AppState",
|
|
44
|
+
"CliError",
|
|
45
|
+
"fetch_whoami",
|
|
46
|
+
"state_of",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
WHOAMI_PATH = "/api/_meta/whoami"
|
|
50
|
+
SCHEMA_BUNDLED = "bundled"
|
|
51
|
+
SCHEMA_LIVE = "live"
|
|
52
|
+
WHOAMI_FIELDS = ("id", "email", "auth_kind")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CliError(click.ClickException):
|
|
56
|
+
"""A usage or configuration failure: message to stderr, exit code 1."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, message: str, code: int = EXIT_USAGE) -> None:
|
|
59
|
+
super().__init__(message)
|
|
60
|
+
self.exit_code = code # ty: ignore[invalid-attribute-access]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class AppState:
|
|
65
|
+
cli: str
|
|
66
|
+
version: str
|
|
67
|
+
schema_path: Path
|
|
68
|
+
defaults_path: Path | None
|
|
69
|
+
root: dict
|
|
70
|
+
transport: httpx.BaseTransport | None = None
|
|
71
|
+
backend: KeyringBackend | None = None
|
|
72
|
+
environ: Mapping[str, str] = field(default_factory=lambda: os.environ)
|
|
73
|
+
flag_env: str | None = None
|
|
74
|
+
# The schema this invocation uses (see commands/schema_source.py).
|
|
75
|
+
schema_source: str = SCHEMA_BUNDLED
|
|
76
|
+
schema_meta: CacheMeta | None = None
|
|
77
|
+
schema_note: str = ""
|
|
78
|
+
# The bundled schema: the only one whose `x-cli-safe` may waive a confirmation.
|
|
79
|
+
bundled_root: dict = field(default_factory=dict)
|
|
80
|
+
# The environment resolved before parsing, as ``(--env value, env, explicit)``; the
|
|
81
|
+
# schema was chosen for it, so requests in this invocation must use the same one.
|
|
82
|
+
preselected: tuple[str | None, Environment, bool] | None = None
|
|
83
|
+
flag_tenant: str | None = None
|
|
84
|
+
_store: CredentialStore | None = None
|
|
85
|
+
_tokens: dict[tuple[str, str | None, str], ResolvedToken] = field(default_factory=dict)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def user_agent(self) -> str:
|
|
89
|
+
return f"{self.cli}/{self.version} simple_module_remote/{engine_version}"
|
|
90
|
+
|
|
91
|
+
def use_schema(
|
|
92
|
+
self, source: str, path: Path, root: dict, meta: CacheMeta | None, note: str
|
|
93
|
+
) -> None:
|
|
94
|
+
self.schema_source, self.schema_path, self.root = source, path, root
|
|
95
|
+
self.schema_meta, self.schema_note = meta, note
|
|
96
|
+
|
|
97
|
+
def begin(self, env: str | None, tenant: str | None) -> None:
|
|
98
|
+
"""Start an invocation: set the root flags and forget tokens from earlier ones."""
|
|
99
|
+
if tenant is not None:
|
|
100
|
+
with self.guard():
|
|
101
|
+
validate_tenant(tenant)
|
|
102
|
+
if self.preselected is not None and self.preselected[0] != env:
|
|
103
|
+
raise CliError("could not read --env before parsing: put it before the command")
|
|
104
|
+
self.flag_env = env
|
|
105
|
+
self.flag_tenant = tenant
|
|
106
|
+
self._tokens.clear()
|
|
107
|
+
|
|
108
|
+
@contextmanager
|
|
109
|
+
def guard(self) -> Generator[None]:
|
|
110
|
+
"""Turn configuration and credential failures into exit-code-1 errors."""
|
|
111
|
+
try:
|
|
112
|
+
yield
|
|
113
|
+
except (ConfigError, CredentialError, UnsafePathError) as exc:
|
|
114
|
+
raise CliError(str(exc)) from None
|
|
115
|
+
|
|
116
|
+
def config(self) -> Config:
|
|
117
|
+
with self.guard():
|
|
118
|
+
return load_config(self.cli, self.defaults_path)
|
|
119
|
+
|
|
120
|
+
def select(self) -> tuple[Environment, bool]:
|
|
121
|
+
if self.preselected is not None and self.preselected[0] == self.flag_env:
|
|
122
|
+
return self.preselected[1], self.preselected[2]
|
|
123
|
+
config = self.config()
|
|
124
|
+
try:
|
|
125
|
+
return select_env(config, self.flag_env, self.environ, self.cli)
|
|
126
|
+
except ConfigError as exc:
|
|
127
|
+
hint = ""
|
|
128
|
+
if not config.envs:
|
|
129
|
+
hint = (
|
|
130
|
+
f"\nno environments are configured yet: `{self.cli} env add <name> --url URL`, "
|
|
131
|
+
f"`{self.cli} env use <name>`, then `{self.cli} login --token`"
|
|
132
|
+
)
|
|
133
|
+
raise CliError(f"{exc}{hint}") from None
|
|
134
|
+
|
|
135
|
+
def tenant(self, env: Environment) -> str | None:
|
|
136
|
+
return self.flag_tenant or env.tenant
|
|
137
|
+
|
|
138
|
+
def store(self) -> CredentialStore:
|
|
139
|
+
if self._store is None:
|
|
140
|
+
with self.guard():
|
|
141
|
+
self._store = CredentialStore(self.cli, backend=self.backend)
|
|
142
|
+
return self._store
|
|
143
|
+
|
|
144
|
+
def _resolved(self, env: Environment, explicit: bool) -> ResolvedToken:
|
|
145
|
+
key = (env.name, self.tenant(env), env.origin)
|
|
146
|
+
if key not in self._tokens:
|
|
147
|
+
with self.guard():
|
|
148
|
+
self._tokens[key] = resolve_credential(
|
|
149
|
+
self.store(), env, self.tenant(env), self.environ, self.cli, explicit
|
|
150
|
+
)
|
|
151
|
+
return self._tokens[key]
|
|
152
|
+
|
|
153
|
+
def token(self, env: Environment, explicit: bool) -> str:
|
|
154
|
+
return self._resolved(env, explicit).token
|
|
155
|
+
|
|
156
|
+
def client(self, env: Environment, token: str | None) -> ApiClient:
|
|
157
|
+
with self.guard():
|
|
158
|
+
return ApiClient(
|
|
159
|
+
env,
|
|
160
|
+
token,
|
|
161
|
+
user_agent=self.user_agent,
|
|
162
|
+
transport=self.transport,
|
|
163
|
+
on_wait=lambda delay: click.echo(
|
|
164
|
+
f"rate limited (HTTP 429): waiting {delay:g}s before retrying", err=True
|
|
165
|
+
),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def run_context(self, env: Environment, explicit: bool) -> RunContext:
|
|
169
|
+
def make_client() -> ApiClient:
|
|
170
|
+
resolved = self._resolved(env, explicit)
|
|
171
|
+
client = self.client(env, resolved.token)
|
|
172
|
+
run_ctx.tenant = resolved.tenant_label # one canonical name
|
|
173
|
+
return client
|
|
174
|
+
|
|
175
|
+
run_ctx = RunContext(
|
|
176
|
+
env=env,
|
|
177
|
+
client_factory=make_client,
|
|
178
|
+
is_tty=sys.stdout.isatty(),
|
|
179
|
+
interactive=sys.stdin.isatty() and sys.stderr.isatty(),
|
|
180
|
+
login_hint=login_hint(self.cli, env, self.tenant(env)),
|
|
181
|
+
tenant=self.tenant(env),
|
|
182
|
+
stdout=sys.stdout,
|
|
183
|
+
stderr=sys.stderr,
|
|
184
|
+
stdin=sys.stdin,
|
|
185
|
+
prompt=lambda text: click.prompt(text, default="", show_default=False, err=True),
|
|
186
|
+
root=self.root,
|
|
187
|
+
schema_hint=self.schema_hint(env),
|
|
188
|
+
)
|
|
189
|
+
return run_ctx
|
|
190
|
+
|
|
191
|
+
def schema_hint(self, env: Environment) -> str:
|
|
192
|
+
"""What to say after a 404/422 from a generated command: the schema may be stale."""
|
|
193
|
+
if self.schema_source == SCHEMA_LIVE:
|
|
194
|
+
return (
|
|
195
|
+
f"hint: the server may have changed: run `{self.cli} --env {env.name} schema sync`"
|
|
196
|
+
)
|
|
197
|
+
return (
|
|
198
|
+
"hint: this command comes from the bundled schema, which may not match the server; "
|
|
199
|
+
f"run `{self.cli} --env {env.name} schema sync`"
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def run(self, op: Operation, values: dict[str, Any], *, generated: bool = True) -> int:
|
|
203
|
+
"""Select the environment and execute ``op``; returns the process exit code."""
|
|
204
|
+
env, explicit = self.select()
|
|
205
|
+
run_ctx = self.run_context(env, explicit)
|
|
206
|
+
if not generated:
|
|
207
|
+
run_ctx.schema_hint = "" # `api METHOD PATH` is not tied to the schema
|
|
208
|
+
with self.guard():
|
|
209
|
+
return run_operation(run_ctx, op, values)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def state_of(ctx: click.Context) -> AppState:
|
|
213
|
+
state = ctx.find_root().obj
|
|
214
|
+
assert isinstance(state, AppState)
|
|
215
|
+
return state
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _strings(value: object) -> bool:
|
|
219
|
+
return isinstance(value, list) and all(isinstance(v, str) for v in value)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _safe_tenant(value: object, client: ApiClient) -> bool:
|
|
223
|
+
"""A tenant id/slug from the server: ``None`` or a bounded printable word without the token."""
|
|
224
|
+
if value is None:
|
|
225
|
+
return True
|
|
226
|
+
if not isinstance(value, str):
|
|
227
|
+
return False
|
|
228
|
+
try:
|
|
229
|
+
validate_tenant(value)
|
|
230
|
+
except ConfigError:
|
|
231
|
+
return False
|
|
232
|
+
return client.redact(value) == value # a reflected token must not reach the screen or disk
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _is_identity(data: dict) -> bool:
|
|
236
|
+
if not {"scopes", "tenant_id", "roles"} <= data.keys():
|
|
237
|
+
return False
|
|
238
|
+
optional_text = data["tenant_id"] is None or isinstance(data["tenant_id"], str)
|
|
239
|
+
scopes = data.get("scopes")
|
|
240
|
+
return (
|
|
241
|
+
all(isinstance(data.get(field), str) for field in WHOAMI_FIELDS)
|
|
242
|
+
and optional_text
|
|
243
|
+
and (scopes is None or _strings(scopes))
|
|
244
|
+
and _strings(data["roles"])
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def fetch_whoami(client: ApiClient) -> dict:
|
|
249
|
+
"""``GET /api/_meta/whoami``; raises :class:`ApiError` on any non-2xx or non-JSON reply."""
|
|
250
|
+
response = client.request("GET", WHOAMI_PATH, follow=False)
|
|
251
|
+
if response.status_code >= REDIRECT_MIN:
|
|
252
|
+
raise ApiError(response.status_code)
|
|
253
|
+
try:
|
|
254
|
+
data = response.json()
|
|
255
|
+
except ValueError:
|
|
256
|
+
raise ApiError(response.status_code, message="whoami response is not JSON") from None
|
|
257
|
+
if not isinstance(data, dict):
|
|
258
|
+
raise ApiError(response.status_code, message="whoami response is not an object")
|
|
259
|
+
if not _is_identity(data) or not all(
|
|
260
|
+
_safe_tenant(data.get(key), client) for key in ("tenant_id", "tenant_slug")
|
|
261
|
+
):
|
|
262
|
+
raise ApiError(response.status_code, message="whoami response is not an identity document")
|
|
263
|
+
return data
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""``schema status`` and ``schema sync``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.commands.runtime import SCHEMA_LIVE, AppState, CliError, state_of
|
|
10
|
+
from simple_module_remote.commands.schema_fetch import (
|
|
11
|
+
OPENAPI_PATH,
|
|
12
|
+
fetch_schema,
|
|
13
|
+
replayable_etag,
|
|
14
|
+
vet_schema,
|
|
15
|
+
)
|
|
16
|
+
from simple_module_remote.config._private_dir import PrivateDir, PrivateDirError
|
|
17
|
+
from simple_module_remote.config.environments import Environment, validate_env_name
|
|
18
|
+
from simple_module_remote.http.errors import AUTH_STATUSES, ApiError, exit_code_for
|
|
19
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
20
|
+
from simple_module_remote.schema.cache import (
|
|
21
|
+
LOCK_FILENAME,
|
|
22
|
+
CacheMeta,
|
|
23
|
+
SchemaCacheError,
|
|
24
|
+
load_from,
|
|
25
|
+
open_cache,
|
|
26
|
+
touch_in,
|
|
27
|
+
write_to,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = ["format_age", "schema_fingerprint", "schema_group", "schema_info"]
|
|
31
|
+
|
|
32
|
+
FINGERPRINT_CHARS = 12
|
|
33
|
+
MAX_VERSION_CHARS = 64
|
|
34
|
+
OPENAPI_PERMISSION = "host.openapi.read"
|
|
35
|
+
HTTP_OK = 200
|
|
36
|
+
HTTP_NOT_MODIFIED = 304
|
|
37
|
+
HTTP_NOT_FOUND = 404
|
|
38
|
+
_UNITS = ((86400, "d"), (3600, "h"), (60, "m"))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def schema_fingerprint(data: bytes) -> str:
|
|
42
|
+
return hashlib.sha256(data).hexdigest()[:FINGERPRINT_CHARS]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def schema_info(root: dict) -> str:
|
|
46
|
+
info = root.get("info")
|
|
47
|
+
version = info.get("version") if isinstance(info, dict) else None
|
|
48
|
+
return sanitize(str(version))[:MAX_VERSION_CHARS] if version else "unknown"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def format_age(seconds: float | None) -> str:
|
|
52
|
+
if seconds is None:
|
|
53
|
+
return "unknown"
|
|
54
|
+
for size, unit in _UNITS:
|
|
55
|
+
if seconds >= size:
|
|
56
|
+
return f"{int(seconds // size)}{unit}"
|
|
57
|
+
return f"{int(seconds)}s"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@click.group("schema", help="Inspect or refresh the command schema.")
|
|
61
|
+
def schema_group() -> None:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@schema_group.command("status", help="Show where the schema comes from, its version and age.")
|
|
66
|
+
@click.pass_context
|
|
67
|
+
def status(ctx: click.Context) -> None:
|
|
68
|
+
state = state_of(ctx)
|
|
69
|
+
meta = state.schema_meta
|
|
70
|
+
click.echo(f"source: {state.schema_source}")
|
|
71
|
+
click.echo(f"path: {state.schema_path}")
|
|
72
|
+
click.echo(f"version: {schema_info(state.root)}")
|
|
73
|
+
fingerprint = (
|
|
74
|
+
meta.fingerprint[:FINGERPRINT_CHARS]
|
|
75
|
+
if meta is not None
|
|
76
|
+
else schema_fingerprint(state.schema_path.read_bytes())
|
|
77
|
+
)
|
|
78
|
+
click.echo(f"fingerprint: {fingerprint}")
|
|
79
|
+
if state.schema_source == SCHEMA_LIVE and meta is not None:
|
|
80
|
+
click.echo(f"age: {format_age(meta.age_seconds())} (fetched {meta.fetched_at})")
|
|
81
|
+
elif state.schema_note:
|
|
82
|
+
click.echo(f"live: {sanitize(state.schema_note)}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _refusal(state: AppState, env: Environment, status: int) -> CliError:
|
|
86
|
+
message = f"schema sync failed: HTTP {status}"
|
|
87
|
+
if status in AUTH_STATUSES:
|
|
88
|
+
message += (
|
|
89
|
+
f"\nhint: the token needs the {OPENAPI_PERMISSION} permission; "
|
|
90
|
+
f"check the login with `{state.cli} --env {env.name} whoami`"
|
|
91
|
+
)
|
|
92
|
+
elif status == HTTP_NOT_FOUND:
|
|
93
|
+
message += f"\nhint: this server has no {OPENAPI_PATH} route (an older version?)"
|
|
94
|
+
return CliError(message, code=exit_code_for(status))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _cached_meta(store: PrivateDir, env: Environment) -> CacheMeta | None:
|
|
98
|
+
try:
|
|
99
|
+
cached = load_from(store, env.name, env.url, env.origin)
|
|
100
|
+
except SchemaCacheError:
|
|
101
|
+
return None # unusable: fetch it again in full
|
|
102
|
+
return cached.meta if cached is not None else None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _sync(state: AppState, env: Environment, explicit: bool) -> str:
|
|
106
|
+
token = state.token(env, explicit)
|
|
107
|
+
with open_cache(state.cli, env.name, create=True) as store, store.locked(LOCK_FILENAME):
|
|
108
|
+
previous = _cached_meta(store, env)
|
|
109
|
+
etag = replayable_etag(previous.etag) if previous else None
|
|
110
|
+
headers = {"If-None-Match": etag} if etag else {}
|
|
111
|
+
with state.client(env, token) as client:
|
|
112
|
+
try:
|
|
113
|
+
fetched = fetch_schema(client, headers)
|
|
114
|
+
except ApiError as exc:
|
|
115
|
+
raise CliError(
|
|
116
|
+
sanitize(f"schema sync failed: {exc.message}"), exit_code_for(0)
|
|
117
|
+
) from None
|
|
118
|
+
if fetched.status == HTTP_NOT_MODIFIED:
|
|
119
|
+
if previous is None or not etag:
|
|
120
|
+
raise CliError(
|
|
121
|
+
"schema sync failed: the server answered 304 Not Modified "
|
|
122
|
+
"to a request that sent no validator",
|
|
123
|
+
exit_code_for(0),
|
|
124
|
+
)
|
|
125
|
+
current = _cached_meta(store, env)
|
|
126
|
+
if current is None or current.fingerprint != previous.fingerprint:
|
|
127
|
+
raise SchemaCacheError("the cache changed during the sync; run it again")
|
|
128
|
+
meta = touch_in(store, previous)
|
|
129
|
+
return f"unchanged ({meta.fingerprint[:FINGERPRINT_CHARS]})"
|
|
130
|
+
if fetched.status != HTTP_OK:
|
|
131
|
+
raise _refusal(state, env, fetched.status)
|
|
132
|
+
vet_schema(fetched.data, client)
|
|
133
|
+
meta = write_to(store, env.url, env.origin, fetched.data, fetched.etag)
|
|
134
|
+
return f"updated ({meta.fingerprint[:FINGERPRINT_CHARS]})"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@schema_group.command("sync", help=f"Fetch and cache the environment's schema ({OPENAPI_PATH}).")
|
|
138
|
+
@click.option("--env", "-e", "env_name", help="Environment to sync (default: the root --env).")
|
|
139
|
+
@click.pass_context
|
|
140
|
+
def sync(ctx: click.Context, env_name: str | None) -> None:
|
|
141
|
+
state = state_of(ctx)
|
|
142
|
+
if env_name is not None:
|
|
143
|
+
if state.flag_env is not None and state.flag_env != env_name:
|
|
144
|
+
raise CliError(
|
|
145
|
+
f"conflicting environments: --env {state.flag_env} before the command and "
|
|
146
|
+
f"--env {env_name} after it; pass one"
|
|
147
|
+
)
|
|
148
|
+
with state.guard():
|
|
149
|
+
state.flag_env = validate_env_name(env_name)
|
|
150
|
+
env, explicit = state.select()
|
|
151
|
+
try:
|
|
152
|
+
outcome = _sync(state, env, explicit)
|
|
153
|
+
except (SchemaCacheError, PrivateDirError) as exc:
|
|
154
|
+
raise CliError(sanitize(f"schema sync failed: {exc}")) from None
|
|
155
|
+
click.echo(f"schema for {env.name!r} {outcome}; commands for {env.url} now use it")
|