esr-client-sdk 1.0.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.
esr/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """env-plane settings for Python: typed settings from the local esr agent.
2
+
3
+ from esr import BaseSettings, field
4
+
5
+ class Settings(BaseSettings, project="shop", version="main"):
6
+ database_url: str
7
+ debug: bool = False
8
+ token: str = field(variable="SERVICE_TOKEN")
9
+
10
+ settings = Settings()
11
+
12
+ Standard library only. See README.md and docs/contracts.md §8.
13
+ """
14
+ from ._settings import BaseSettings, Json, SettingsError, field
15
+
16
+ __all__ = ["BaseSettings", "Json", "SettingsError", "field"]
17
+ __version__ = "1.0.0"
esr/_agent.py ADDED
@@ -0,0 +1,150 @@
1
+ """Client of the local channel (docs/contracts.md §7.1, §7.2): HTTP/1.1 with
2
+ JSON bodies over the agent's Unix socket or, for containers, over TCP with a
3
+ link token. Standard library only.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import http.client
8
+ import json
9
+ import os
10
+ import socket
11
+ from typing import Any, Mapping
12
+ from urllib.parse import urlsplit
13
+
14
+ CONNECT_TIMEOUT = 2.0 # seconds to connect
15
+ RESPONSE_TIMEOUT = 30.0 # seconds for the response
16
+ REPORT_TIMEOUT = 2.0 # override report and status lookup: best effort
17
+ MAX_BODY = 64 * 1024 * 1024
18
+ USER_AGENT = "esr-python/1"
19
+
20
+
21
+ class ConnectError(Exception):
22
+ """No connection to the agent. `reason` is short and has no values."""
23
+
24
+ def __init__(self, reason: str) -> None:
25
+ super().__init__(reason)
26
+ self.reason = reason
27
+
28
+
29
+ class ProtocolError(Exception):
30
+ """Connected, but no usable HTTP answer (timeout, hang-up, garbage)."""
31
+
32
+ def __init__(self, reason: str) -> None:
33
+ super().__init__(reason)
34
+ self.reason = reason
35
+
36
+
37
+ class Agent:
38
+ """Where the agent listens. Exactly one of `sock` / `url` is set."""
39
+
40
+ def __init__(self, *, sock: str | None = None, url: str | None = None, token: str | None = None) -> None:
41
+ self.sock = sock
42
+ self.url = url
43
+ self.token = token
44
+ self._host = ""
45
+ self._port = 0
46
+ self._base = ""
47
+ if url is not None:
48
+ parts = urlsplit(url)
49
+ try:
50
+ port = parts.port
51
+ except ValueError:
52
+ port = -1
53
+ if (parts.scheme != "http" or not parts.hostname or port == -1 or parts.query or parts.fragment
54
+ or parts.username is not None):
55
+ raise ConnectError("ESR_AGENT_URL must look like http://host:port")
56
+ self._host = parts.hostname
57
+ self._port = port or 80
58
+ self._base = parts.path.rstrip("/")
59
+
60
+ @property
61
+ def address(self) -> str:
62
+ """For messages: the socket path or the URL."""
63
+ return self.sock if self.sock is not None else (self.url or "").rstrip("/")
64
+
65
+ def request(self, method: str, path: str, body: Any = None, *,
66
+ response_timeout: float = RESPONSE_TIMEOUT) -> tuple[int, Any]:
67
+ """Returns (status, decoded JSON body or None if it is not JSON).
68
+
69
+ Raises ConnectError or ProtocolError.
70
+ """
71
+ headers = {"Accept": "application/json", "User-Agent": USER_AGENT, "Connection": "close"}
72
+ payload = None
73
+ if body is not None:
74
+ payload = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
75
+ headers["Content-Type"] = "application/json"
76
+ if self.sock is None and self.token:
77
+ headers["Authorization"] = "Bearer " + self.token
78
+ conn = _Connection(self, response_timeout)
79
+ try:
80
+ try:
81
+ conn.request(method, self._base + path, body=payload, headers=headers)
82
+ resp = conn.getresponse()
83
+ raw = resp.read() # raises IncompleteRead on a truncated body
84
+ status = resp.status
85
+ except ConnectError:
86
+ raise
87
+ except socket.timeout:
88
+ raise ProtocolError("no answer within %g seconds" % response_timeout) from None
89
+ except (http.client.HTTPException, OSError, ValueError):
90
+ raise ProtocolError("the connection broke before a complete answer arrived") from None
91
+ finally:
92
+ conn.close()
93
+ if len(raw) > MAX_BODY:
94
+ raise ProtocolError("the answer is too large")
95
+ try:
96
+ decoded = json.loads(raw.decode("utf-8")) if raw else None
97
+ except (ValueError, RecursionError):
98
+ decoded = None
99
+ return status, decoded
100
+
101
+
102
+ class _Connection(http.client.HTTPConnection):
103
+ def __init__(self, agent: Agent, response_timeout: float) -> None:
104
+ if agent.sock is not None:
105
+ super().__init__("esr-agent") # host name used over the socket (§7.1)
106
+ else:
107
+ super().__init__(agent._host, agent._port)
108
+ self._agent = agent
109
+ self._response_timeout = response_timeout
110
+
111
+ def connect(self) -> None:
112
+ agent = self._agent
113
+ try:
114
+ if agent.sock is not None:
115
+ if not hasattr(socket, "AF_UNIX"):
116
+ raise ConnectError("Unix sockets are not available on this platform; use ESR_AGENT_URL")
117
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
118
+ try:
119
+ s.settimeout(CONNECT_TIMEOUT)
120
+ s.connect(agent.sock)
121
+ except BaseException:
122
+ s.close()
123
+ raise
124
+ else:
125
+ s = socket.create_connection((agent._host, agent._port), CONNECT_TIMEOUT)
126
+ except socket.timeout:
127
+ raise ConnectError("no connection within %g seconds" % CONNECT_TIMEOUT) from None
128
+ except FileNotFoundError:
129
+ raise ConnectError("no socket there") from None
130
+ except ConnectionRefusedError:
131
+ raise ConnectError("nothing is listening") from None
132
+ except PermissionError:
133
+ raise ConnectError("permission denied") from None
134
+ except OSError as e:
135
+ raise ConnectError(e.strerror or type(e).__name__) from None
136
+ s.settimeout(self._response_timeout)
137
+ self.sock = s
138
+
139
+
140
+ def find_agent(environ: Mapping[str, str]) -> Agent:
141
+ """§7.1: ESR_AGENT_SOCK, then ESR_AGENT_URL (+ ESR_AGENT_TOKEN), then
142
+ $HOME/.esr/agent.sock. Empty variables count as unset."""
143
+ sock = environ.get("ESR_AGENT_SOCK")
144
+ if sock:
145
+ return Agent(sock=sock)
146
+ url = environ.get("ESR_AGENT_URL")
147
+ if url:
148
+ return Agent(url=url, token=environ.get("ESR_AGENT_TOKEN") or None)
149
+ home = environ.get("HOME") or environ.get("USERPROFILE") or os.path.expanduser("~")
150
+ return Agent(sock=os.path.join(home, ".esr", "agent.sock"))
esr/_core.py ADDED
@@ -0,0 +1,250 @@
1
+ """Pure rules of docs/contracts.md §8: variable names (§8.1), the .env format
2
+ (§8.3) and type coercion (§8.4). No I/O. The fixtures in sdk/conformance decide
3
+ what is right; the other libraries implement exactly the same rules.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import math
9
+ import re
10
+ from typing import Any
11
+
12
+ # ---------------------------------------------------------------- names (§8.1)
13
+
14
+ _UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
15
+ _LOWER = "abcdefghijklmnopqrstuvwxyz"
16
+ _DIGIT = "0123456789"
17
+ _TO_UPPER = str.maketrans(_LOWER, _UPPER)
18
+
19
+
20
+ def variable_name(field: str) -> str:
21
+ """`database_url`, `databaseUrl` and `DatabaseURL` are all `DATABASE_URL`.
22
+
23
+ Only ASCII letters take part in word splitting and upper-casing; anything
24
+ else is kept as it is (give such fields an explicit variable name).
25
+ """
26
+ words: list[str] = []
27
+ cur = ""
28
+ for i, c in enumerate(field):
29
+ if c in "_-":
30
+ if cur:
31
+ words.append(cur)
32
+ cur = ""
33
+ continue
34
+ if cur and c in _UPPER:
35
+ prev = field[i - 1]
36
+ nxt = field[i + 1] if i + 1 < len(field) else ""
37
+ if prev in _LOWER or prev in _DIGIT or (prev in _UPPER and nxt != "" and nxt in _LOWER):
38
+ words.append(cur)
39
+ cur = ""
40
+ cur += c
41
+ if cur:
42
+ words.append(cur)
43
+ return "_".join(words).translate(_TO_UPPER)
44
+
45
+
46
+ # ---------------------------------------------------------------- .env (§8.3)
47
+
48
+ _KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
49
+ _EXPORT = re.compile(r"export[ \t]+")
50
+ _ESCAPES = {"n": "\n", "r": "\r", "t": "\t", "\\": "\\", '"': '"'}
51
+ _BLANK = " \t"
52
+
53
+
54
+ def parse_dotenv(text: str) -> tuple[dict[str, str], list[int]]:
55
+ """Returns the values and the 1-based numbers of the invalid lines."""
56
+ if text.startswith("\ufeff"):
57
+ text = text[1:]
58
+ text = text.replace("\r\n", "\n")
59
+ lines = text.split("\n")
60
+ starts: list[int] = []
61
+ pos = 0
62
+ for line in lines:
63
+ starts.append(pos)
64
+ pos += len(line) + 1
65
+
66
+ values: dict[str, str] = {}
67
+ invalid: list[int] = []
68
+ i = 0
69
+ while i < len(lines):
70
+ line = lines[i]
71
+ lineno = i + 1
72
+ s = line.lstrip(_BLANK)
73
+ if s == "" or s.startswith("#"):
74
+ i += 1
75
+ continue
76
+ m = _EXPORT.match(s)
77
+ if m:
78
+ s = s[m.end():]
79
+ m = _KEY.match(s)
80
+ if not m:
81
+ invalid.append(lineno)
82
+ i += 1
83
+ continue
84
+ key = m.group(0)
85
+ rest = s[m.end():].lstrip(_BLANK)
86
+ if not rest.startswith("="):
87
+ invalid.append(lineno)
88
+ i += 1
89
+ continue
90
+ rest = rest[1:]
91
+ stripped = rest.lstrip(_BLANK)
92
+ if stripped[:1] in ('"', "'"):
93
+ quote = stripped[0]
94
+ # Offset in `text` of the character behind the opening quote.
95
+ j = starts[i] + (len(line) - len(stripped)) + 1
96
+ out: list[str] = []
97
+ closed = False
98
+ while j < len(text):
99
+ c = text[j]
100
+ if quote == '"' and c == "\\" and j + 1 < len(text):
101
+ n = text[j + 1]
102
+ out.append(_ESCAPES[n] if n in _ESCAPES else "\\" + n)
103
+ j += 2
104
+ continue
105
+ if c == quote:
106
+ closed = True
107
+ break
108
+ out.append(c)
109
+ j += 1
110
+ if not closed:
111
+ invalid.append(lineno)
112
+ i += 1
113
+ continue
114
+ eol = text.find("\n", j)
115
+ if eol == -1:
116
+ eol = len(text)
117
+ tail = text[j + 1:eol].lstrip(_BLANK)
118
+ if tail != "" and not tail.startswith("#"):
119
+ invalid.append(lineno)
120
+ i += 1
121
+ continue
122
+ values[key] = "".join(out)
123
+ i = text.count("\n", 0, j) + 1 # the line after the closing quote
124
+ continue
125
+ cut = len(rest)
126
+ for k, c in enumerate(rest):
127
+ if c == "#" and k > 0 and rest[k - 1] in _BLANK:
128
+ cut = k
129
+ break
130
+ values[key] = rest[:cut].strip(_BLANK)
131
+ i += 1
132
+ return values, invalid
133
+
134
+
135
+ # ---------------------------------------------------------------- coercion (§8.4)
136
+
137
+ TYPES = ("str", "int", "float", "bool", "list[str]", "list[int]", "list[float]", "list[bool]", "json")
138
+
139
+ _WS = " \t\n\r"
140
+ _INT = re.compile(r"[+-]?[0-9]+\Z")
141
+ _FLOAT = re.compile(r"[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?\Z")
142
+ _TRUE = frozenset(("1", "true", "t", "yes", "y", "on"))
143
+ _FALSE = frozenset(("0", "false", "f", "no", "n", "off"))
144
+ _INT_MIN, _INT_MAX = -(2**63), 2**63 - 1
145
+
146
+
147
+ class Invalid(Exception):
148
+ """The string cannot be coerced to the type. Carries nothing: values are
149
+ never put into messages."""
150
+
151
+
152
+ def _json_constant(_: str) -> Any:
153
+ raise Invalid()
154
+
155
+
156
+ def _json_float(text: str) -> float:
157
+ v = float(text)
158
+ if math.isinf(v):
159
+ raise Invalid()
160
+ return v
161
+
162
+
163
+ def _json_int(text: str) -> int:
164
+ v = int(text)
165
+ try:
166
+ float(v)
167
+ except OverflowError:
168
+ raise Invalid() from None
169
+ return v
170
+
171
+
172
+ def _parse_json(text: str) -> Any:
173
+ """Strict JSON; numbers that do not fit a double are invalid."""
174
+ try:
175
+ return json.loads(text, parse_constant=_json_constant, parse_float=_json_float, parse_int=_json_int)
176
+ except Invalid:
177
+ raise
178
+ except (ValueError, RecursionError):
179
+ raise Invalid() from None
180
+
181
+
182
+ def _lower_ascii(s: str) -> str:
183
+ return s.translate(str.maketrans(_UPPER, _LOWER))
184
+
185
+
186
+ def coerce(typ: str, s: str) -> Any:
187
+ """Coerce the string `s` to `typ` (one of TYPES) or raise Invalid."""
188
+ if typ == "str":
189
+ return s
190
+ if typ == "int":
191
+ t = s.strip(_WS)
192
+ if not _INT.match(t):
193
+ raise Invalid()
194
+ v = int(t)
195
+ if not _INT_MIN <= v <= _INT_MAX:
196
+ raise Invalid()
197
+ return v
198
+ if typ == "float":
199
+ t = s.strip(_WS)
200
+ if not _FLOAT.match(t):
201
+ raise Invalid()
202
+ f = float(t)
203
+ if math.isinf(f) or math.isnan(f):
204
+ raise Invalid()
205
+ return f
206
+ if typ == "bool":
207
+ t = _lower_ascii(s.strip(_WS))
208
+ if t in _TRUE:
209
+ return True
210
+ if t in _FALSE:
211
+ return False
212
+ raise Invalid()
213
+ if typ == "json":
214
+ return _parse_json(s.strip(_WS))
215
+ if typ.startswith("list[") and typ in TYPES:
216
+ el = typ[5:-1]
217
+ t = s.strip(_WS)
218
+ if t == "":
219
+ return []
220
+ if not t.startswith("["):
221
+ return [coerce(el, part.strip(_WS)) for part in t.split(",")]
222
+ arr = _parse_json(t)
223
+ if not isinstance(arr, list):
224
+ raise Invalid()
225
+ return [_coerce_json_element(el, x) for x in arr]
226
+ raise ValueError(f"unknown type {typ!r}")
227
+
228
+
229
+ def _coerce_json_element(el: str, x: Any) -> Any:
230
+ if isinstance(x, str):
231
+ return coerce(el, x)
232
+ if isinstance(x, bool):
233
+ if el != "bool":
234
+ raise Invalid()
235
+ return x
236
+ if isinstance(x, int):
237
+ if el == "int":
238
+ if not _INT_MIN <= x <= _INT_MAX:
239
+ raise Invalid()
240
+ return x
241
+ if el == "float":
242
+ return float(x) # cannot overflow: _json_int checked
243
+ raise Invalid()
244
+ if isinstance(x, float):
245
+ if el == "float":
246
+ return x
247
+ if el == "int" and x == math.floor(x) and abs(x) < 2**53:
248
+ return int(x)
249
+ raise Invalid()
250
+ raise Invalid()
esr/_settings.py ADDED
@@ -0,0 +1,426 @@
1
+ """Loading (docs/contracts.md §8.2), errors (§8.5) and the declaration idiom
2
+ (§8.1): a typed settings base class.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ import os
8
+ import sys
9
+ import types
10
+ import typing
11
+ from dataclasses import dataclass
12
+ from typing import Any, ClassVar, Mapping, TextIO
13
+
14
+ from . import _agent
15
+ from ._core import Invalid, TYPES, coerce, parse_dotenv, variable_name
16
+
17
+ # ---------------------------------------------------------------- errors (§8.5)
18
+
19
+ AGENT_UNAVAILABLE = "agent_unavailable"
20
+ NOT_SIGNED_IN = "not_signed_in"
21
+ FORBIDDEN = "forbidden"
22
+ NOT_FOUND = "not_found"
23
+ VERSION_MISMATCH = "version_mismatch"
24
+ SERVER_UNREACHABLE = "server_unreachable"
25
+ AGENT_ERROR = "agent_error"
26
+ INVALID_SETTINGS = "invalid_settings"
27
+
28
+
29
+ class SettingsError(Exception):
30
+ """Settings could not be loaded.
31
+
32
+ `code` is one of agent_unavailable, not_signed_in, forbidden, not_found,
33
+ version_mismatch, server_unreachable, agent_error, invalid_settings. For
34
+ invalid_settings, `missing` and `invalid` hold the variable names, sorted.
35
+ The message says what to do and never contains a value.
36
+ """
37
+
38
+ def __init__(self, code: str, message: str, missing: typing.Sequence[str] = (),
39
+ invalid: typing.Sequence[str] = ()) -> None:
40
+ super().__init__(message)
41
+ self.code = code
42
+ self.missing = list(missing)
43
+ self.invalid = list(invalid)
44
+
45
+
46
+ def _clip(text: Any, limit: int = 200) -> str:
47
+ """Agent-supplied text for a message: one line, printable, bounded."""
48
+ if not isinstance(text, str):
49
+ return ""
50
+ text = "".join(c if c.isprintable() else " " for c in text).strip()
51
+ return text[:limit] + ("…" if len(text) > limit else "")
52
+
53
+
54
+ def _unavailable(agent: _agent.Agent | None, reason: str) -> SettingsError:
55
+ if agent is not None and agent.sock is None:
56
+ return SettingsError(AGENT_UNAVAILABLE, (
57
+ f"esr: cannot reach the esr agent at {agent.address} (ESR_AGENT_URL): {reason}. "
58
+ "On the host, run `esr login` and then `esr link`, and put the ESR_AGENT_URL and ESR_AGENT_TOKEN it "
59
+ "prints into the container's environment. For tests and CI without an agent, set ESR_OFFLINE=1."))
60
+ where = f" at {agent.address}" if agent is not None else ""
61
+ return SettingsError(AGENT_UNAVAILABLE, (
62
+ f"esr: cannot reach the esr agent{where}: {reason}. "
63
+ "Run `esr login` to start it and sign in, then start the app again. In a deployment, start the app with "
64
+ "`esr run -- <command>`. For tests and CI without an agent, set ESR_OFFLINE=1."))
65
+
66
+
67
+ def _agent_failure(decl: "Declaration", agent: _agent.Agent, status: int, body: Any) -> SettingsError:
68
+ err = body.get("error") if isinstance(body, dict) else None
69
+ code = err.get("code") if isinstance(err, dict) else None
70
+ message = _clip(err.get("message")) if isinstance(err, dict) else ""
71
+ if not isinstance(code, str):
72
+ code = None
73
+ p, v = decl.project, decl.version
74
+ if status != 200:
75
+ if code == "not_signed_in":
76
+ return SettingsError(NOT_SIGNED_IN, "esr: the esr agent is not signed in. Run `esr login`, then start the app again.")
77
+ if code == "session_expired":
78
+ return SettingsError(NOT_SIGNED_IN, "esr: your esr session has expired. Run `esr login`, then start the app again.")
79
+ if code == "forbidden":
80
+ env = _environment(agent)
81
+ where = f'environment "{env}"' if env else "the agent's current environment (see `esr status`)"
82
+ return SettingsError(FORBIDDEN, (
83
+ f'esr: no access to project "{p}", version "{v}" in {where}. Ask an admin of your organisation for '
84
+ "access to this project and environment, or switch to an environment you may use with "
85
+ "`esr env use <name>`."))
86
+ if code == "not_found":
87
+ return SettingsError(NOT_FOUND, (
88
+ f'esr: project "{p}" or its version "{v}" does not exist (or you may not see it). Check project and '
89
+ "version in the settings declaration in the code, and the organisation in `esr status`."))
90
+ if code == "version_mismatch":
91
+ return SettingsError(VERSION_MISMATCH, (
92
+ f'esr: the deployment token is not for project "{p}", version "{v}" (or not for this environment). '
93
+ "Use the token of this deployment (ESR_TOKEN), or fix project and version in the settings declaration."))
94
+ if code == "server_unreachable":
95
+ return SettingsError(SERVER_UNREACHABLE, (
96
+ "esr: the esr agent cannot reach the env-plane server and has no values it may serve. Check the "
97
+ "network connection and start the app again."))
98
+ if status == 200:
99
+ detail, hint = "the answer is not a valid resolve response", "Update esr with `esr update` and try again."
100
+ else:
101
+ detail = message
102
+ if code == "invalid_link_token":
103
+ hint = ("Check ESR_AGENT_TOKEN: the link token dies with the agent's session; run `esr link` on the host "
104
+ "to get the current one.")
105
+ elif code == "bad_request":
106
+ hint = "The agent did not understand the request (internal error): update esr with `esr update`."
107
+ else:
108
+ hint = "Update esr with `esr update` and try again."
109
+ shown = f'"{_clip(code, 60)}"' if code else "none"
110
+ return SettingsError(AGENT_ERROR, (
111
+ f"esr: unexpected answer from the esr agent at {agent.address} (status {status}, code {shown})"
112
+ + (f": {detail}" if detail else "") + f". {hint}"))
113
+
114
+
115
+ def _environment(agent: _agent.Agent) -> str:
116
+ """The agent's current environment, for the `forbidden` message."""
117
+ try:
118
+ status, body = agent.request("GET", "/v1/status", response_timeout=_agent.REPORT_TIMEOUT)
119
+ except (_agent.ConnectError, _agent.ProtocolError):
120
+ return ""
121
+ if status == 200 and isinstance(body, dict):
122
+ return _clip(body.get("environment"), 100)
123
+ return ""
124
+
125
+
126
+ def _invalid_settings(decl: "Declaration", missing: list[str], invalid: dict[str, str],
127
+ user_values: typing.Collection[str]) -> SettingsError:
128
+ lines = [f'esr: the settings of project "{decl.project}", version "{decl.version}" cannot be loaded.']
129
+ own = [n for n in missing if n in user_values]
130
+ plain = [n for n in missing if n not in user_values]
131
+ if plain:
132
+ lines.append(" missing: " + ", ".join(plain))
133
+ if own:
134
+ lines.append(" missing, your own value is needed: " + ", ".join(own))
135
+ if invalid:
136
+ lines.append(" invalid: " + ", ".join(f"{n} (expected {invalid[n]})" for n in sorted(invalid)))
137
+ if plain:
138
+ lines.append("Missing values: set them in env-plane for this project, version and environment, "
139
+ "or locally in .env or the process environment.")
140
+ if own:
141
+ lines.append("User-specific secrets: every user must set their own value in env-plane (or locally in .env).")
142
+ if invalid:
143
+ lines.append("Invalid values: correct them where they are set (the process environment, .env or env-plane).")
144
+ return SettingsError(INVALID_SETTINGS, "\n".join(lines), missing, sorted(invalid))
145
+
146
+
147
+ # ---------------------------------------------------------------- declaration
148
+
149
+ _MISSING: Any = object()
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class FieldSpec:
154
+ name: str
155
+ type: str
156
+ variable: str
157
+ default: Any = _MISSING
158
+
159
+ @property
160
+ def has_default(self) -> bool:
161
+ return self.default is not _MISSING
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class Declaration:
166
+ project: str
167
+ version: str
168
+ fields: tuple[FieldSpec, ...]
169
+ env_file: str | None = None
170
+
171
+
172
+ # ---------------------------------------------------------------- loading (§8.2)
173
+
174
+ def _warn(stderr: TextIO, line: str) -> None:
175
+ try:
176
+ stderr.write(line + "\n")
177
+ stderr.flush()
178
+ except (OSError, ValueError):
179
+ pass
180
+
181
+
182
+ def _read_dotenv(decl: Declaration, environ: Mapping[str, str], cwd: str | None, stderr: TextIO) -> dict[str, str]:
183
+ path = environ.get("ESR_ENV_FILE")
184
+ if path is None:
185
+ path = decl.env_file if decl.env_file is not None else ".env"
186
+ if path == "":
187
+ return {}
188
+ if cwd is not None:
189
+ path = os.path.join(cwd, path)
190
+ try:
191
+ with open(path, "rb") as f:
192
+ text = f.read().decode("utf-8", errors="replace")
193
+ except (FileNotFoundError, NotADirectoryError):
194
+ return {}
195
+ except OSError:
196
+ _warn(stderr, f"esr: warning: .env file {path} could not be read and was ignored")
197
+ return {}
198
+ values, invalid = parse_dotenv(text)
199
+ for n in invalid:
200
+ _warn(stderr, f"esr: warning: .env line {n} is not valid and was ignored")
201
+ return values
202
+
203
+
204
+ def load(decl: Declaration, environ: Mapping[str, str] | None = None, *, stderr: TextIO | None = None,
205
+ cwd: str | None = None) -> dict[str, Any]:
206
+ """Load the declared fields; returns the values by field name or raises
207
+ SettingsError. `environ`, `stderr` and `cwd` default to the process's."""
208
+ if environ is None:
209
+ environ = os.environ
210
+ if stderr is None:
211
+ stderr = sys.stderr
212
+
213
+ # 1. The agent, unless ESR_OFFLINE is exactly "1". Any failure stops here.
214
+ agent: _agent.Agent | None = None
215
+ agent_values: dict[str, tuple[str, str]] = {} # name -> (value, kind)
216
+ user_values: frozenset[str] = frozenset()
217
+ if environ.get("ESR_OFFLINE") != "1":
218
+ try:
219
+ agent = _agent.find_agent(environ)
220
+ status, body = agent.request("POST", "/v1/resolve", {"project": decl.project, "version": decl.version})
221
+ except _agent.ConnectError as e:
222
+ raise _unavailable(agent, e.reason) from None
223
+ except _agent.ProtocolError as e:
224
+ raise SettingsError(AGENT_ERROR, (
225
+ f"esr: no usable answer from the esr agent at {agent.address if agent else '?'} (status none, code "
226
+ f"none): {e.reason}. Check `esr status`; update esr with `esr update` if this persists.")) from None
227
+ parsed = _parse_resolve(body) if status == 200 else None
228
+ if parsed is None:
229
+ raise _agent_failure(decl, agent, status, body)
230
+ agent_values, user_values = parsed
231
+
232
+ # 2. The .env file.
233
+ dotenv = _read_dotenv(decl, environ, cwd, stderr)
234
+
235
+ # 3.–5. First source that has the variable; coerce; collect every problem.
236
+ values: dict[str, Any] = {}
237
+ missing: set[str] = set()
238
+ invalid: dict[str, str] = {}
239
+ overrides: dict[str, str] = {} # variable -> "the environment" | ".env"
240
+ for f in decl.fields:
241
+ var = f.variable
242
+ if var in environ:
243
+ raw, source = environ[var], "the environment"
244
+ elif var in dotenv:
245
+ raw, source = dotenv[var], ".env"
246
+ elif var in agent_values:
247
+ raw, source = agent_values[var][0], ""
248
+ elif f.has_default:
249
+ values[f.name] = copy.deepcopy(f.default)
250
+ continue
251
+ else:
252
+ missing.add(var)
253
+ continue
254
+ if source and var in agent_values:
255
+ agent_value, kind = agent_values[var]
256
+ if kind in ("secret", "provider_token") and agent_value != raw:
257
+ overrides[var] = source
258
+ try:
259
+ values[f.name] = coerce(f.type, raw)
260
+ except Invalid:
261
+ invalid[var] = f.type
262
+ if missing or invalid:
263
+ raise _invalid_settings(decl, sorted(missing), invalid, user_values)
264
+
265
+ # 6. Secret overrides: warn and report names. Never a value.
266
+ if overrides:
267
+ names = sorted(overrides)
268
+ for name in names:
269
+ _warn(stderr, f"esr: warning: secret {name} is overridden by {overrides[name]}")
270
+ if agent is not None:
271
+ try:
272
+ agent.request("POST", "/v1/overrides", {"project": decl.project, "version": decl.version, "fields": names},
273
+ response_timeout=_agent.REPORT_TIMEOUT)
274
+ except (_agent.ConnectError, _agent.ProtocolError):
275
+ pass # best effort
276
+ return values
277
+
278
+
279
+ def _parse_resolve(body: Any) -> tuple[dict[str, tuple[str, str]], frozenset[str]] | None:
280
+ """The values of a LocalResolveResponse, or None if it is malformed."""
281
+ if not isinstance(body, dict) or not isinstance(body.get("values"), list):
282
+ return None
283
+ out: dict[str, tuple[str, str]] = {}
284
+ for v in body["values"]:
285
+ if not isinstance(v, dict):
286
+ return None
287
+ name, value, kind = v.get("name"), v.get("value"), v.get("kind")
288
+ if not (isinstance(name, str) and isinstance(value, str) and isinstance(kind, str)):
289
+ return None
290
+ out[name] = (value, kind)
291
+ user = body.get("missing_user_values")
292
+ if user is None:
293
+ user = []
294
+ if not isinstance(user, list) or not all(isinstance(x, str) for x in user):
295
+ return None
296
+ return out, frozenset(user)
297
+
298
+
299
+ # ---------------------------------------------------------------- the idiom
300
+
301
+ Json = Any
302
+ """Annotation for a field holding any JSON value: `flags: Json`."""
303
+
304
+
305
+ class _Field:
306
+ __slots__ = ("default", "variable")
307
+
308
+ def __init__(self, default: Any, variable: str | None) -> None:
309
+ self.default = default
310
+ self.variable = variable
311
+
312
+
313
+ def field(*, default: Any = _MISSING, variable: str | None = None) -> Any:
314
+ """Field options: an explicit variable name and/or a default.
315
+
316
+ token: str = field(variable="SERVICE_TOKEN")
317
+ retries: int = field(default=3, variable="HTTP_RETRIES")
318
+ """
319
+ if variable is not None and (not isinstance(variable, str) or variable == ""):
320
+ raise TypeError("esr: field(variable=...) must be a non-empty string")
321
+ return _Field(default, variable)
322
+
323
+
324
+ _SCALARS: dict[Any, str] = {str: "str", int: "int", float: "float", bool: "bool"}
325
+ _NONE = type(None)
326
+
327
+
328
+ def _type_name(annotation: Any) -> str | None:
329
+ origin = typing.get_origin(annotation)
330
+ if origin is typing.Union or origin is types.UnionType: # Optional[T] is T
331
+ args = [a for a in typing.get_args(annotation) if a is not _NONE]
332
+ if len(args) != 1:
333
+ return None
334
+ return _type_name(args[0])
335
+ if annotation in _SCALARS:
336
+ return _SCALARS[annotation]
337
+ if annotation is list:
338
+ return "list[str]"
339
+ if origin is list:
340
+ (arg,) = typing.get_args(annotation) or (str,)
341
+ return "list[" + _SCALARS[arg] + "]" if arg in _SCALARS else "json"
342
+ if annotation is Any or annotation is object or annotation is dict or origin is dict:
343
+ return "json"
344
+ return None
345
+
346
+
347
+ def _declare(cls: type, project: str, version: str, env_file: str | None) -> Declaration:
348
+ try:
349
+ hints = typing.get_type_hints(cls)
350
+ except Exception as e: # unresolvable forward reference
351
+ raise TypeError(f"esr: cannot read the annotations of {cls.__name__}: {e}") from None
352
+ fields: list[FieldSpec] = []
353
+ for name, annotation in hints.items():
354
+ if name.startswith("_") or typing.get_origin(annotation) is ClassVar or annotation is ClassVar:
355
+ continue
356
+ typ = _type_name(annotation)
357
+ if typ is None:
358
+ raise TypeError(
359
+ f"esr: field {cls.__name__}.{name} has an unsupported type; use str, int, float, bool, "
360
+ "list[str|int|float|bool] or esr.Json (dict, Any)")
361
+ assert typ in TYPES
362
+ attr = _MISSING
363
+ for klass in cls.__mro__:
364
+ if name in klass.__dict__:
365
+ attr = klass.__dict__[name]
366
+ break
367
+ default, variable = attr, None
368
+ if isinstance(attr, _Field):
369
+ default, variable = attr.default, attr.variable
370
+ fields.append(FieldSpec(name, typ, variable or variable_name(name), default))
371
+ return Declaration(project, version, tuple(fields), env_file)
372
+
373
+
374
+ class BaseSettings:
375
+ """Base class of a settings declaration.
376
+
377
+ class Settings(BaseSettings, project="shop", version="main"):
378
+ database_url: str
379
+ debug: bool = False
380
+ hosts: list[str] = []
381
+ token: str = field(variable="SERVICE_TOKEN")
382
+
383
+ settings = Settings() # loads once; raises SettingsError
384
+
385
+ Project and version are constants in the code; the environment never is.
386
+ `env_file="path"` names another .env file than `.env` in the working
387
+ directory (ESR_ENV_FILE still wins). Instances are read-only and their
388
+ repr shows field names only.
389
+ """
390
+
391
+ __esr_declaration__: ClassVar[Declaration | None] = None
392
+
393
+ def __init_subclass__(cls, *, project: str | None = None, version: str | None = None,
394
+ env_file: str | None = None, **kwargs: Any) -> None:
395
+ super().__init_subclass__(**kwargs)
396
+ parent = cls.__esr_declaration__
397
+ if project is None and parent is not None:
398
+ project = parent.project
399
+ if version is None and parent is not None:
400
+ version = parent.version
401
+ if env_file is None and parent is not None:
402
+ env_file = parent.env_file
403
+ if not isinstance(project, str) or not project or not isinstance(version, str) or not version:
404
+ raise TypeError(
405
+ f'esr: {cls.__name__} must name its project and version: '
406
+ f'class {cls.__name__}(BaseSettings, project="…", version="…")')
407
+ cls.__esr_declaration__ = _declare(cls, project, version, env_file)
408
+
409
+ def __init__(self) -> None:
410
+ decl = type(self).__esr_declaration__
411
+ if decl is None:
412
+ raise TypeError("esr: BaseSettings must be subclassed with project= and version=")
413
+ for name, value in load(decl).items():
414
+ object.__setattr__(self, name, value)
415
+
416
+ def __setattr__(self, name: str, value: Any) -> None:
417
+ raise AttributeError("esr: settings are read-only")
418
+
419
+ def __delattr__(self, name: str) -> None:
420
+ raise AttributeError("esr: settings are read-only")
421
+
422
+ def __repr__(self) -> str:
423
+ decl = type(self).__esr_declaration__
424
+ assert decl is not None
425
+ names = ", ".join(f.name for f in decl.fields)
426
+ return f"<{type(self).__name__} project={decl.project!r} version={decl.version!r} fields: {names}>"
esr/py.typed ADDED
File without changes
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: esr-client-sdk
3
+ Version: 1.0.0
4
+ Summary: env-plane settings: typed configuration and secrets from the local esr agent
5
+ License-Expression: MIT
6
+ Project-URL: Source, https://github.com/labsbit/esr-sdk
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Typing :: Typed
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # esr for Python
15
+
16
+ Typed settings from env-plane. The library asks the local `esr` agent for the
17
+ values of your project and version, lets `.env` and the process environment
18
+ override them, and fails fast with one error that names every problem.
19
+
20
+ Python 3.10+, standard library only, typed (`py.typed`).
21
+
22
+ ## Install
23
+
24
+ From PyPI (the package is `esr-client-sdk`, the module is `esr`):
25
+
26
+ ```
27
+ pip install esr-client-sdk
28
+ ```
29
+
30
+ ## Coding agents
31
+
32
+ `esr skill install` (in the project's repository) installs the env-plane
33
+ skill for Claude Code, Cursor and Codex. It teaches the agent how to onboard
34
+ the project: find the values it reads, upload them with `esr vars`, declare
35
+ them with this library and wire `esr run` into tools, Docker and
36
+ deployments, without writing secrets into files or transcripts.
37
+ `esr skill` prints it.
38
+
39
+ ## Use
40
+
41
+ ```python
42
+ from esr import BaseSettings, field
43
+
44
+ class Settings(BaseSettings, project="shop", version="main"):
45
+ database_url: str # DATABASE_URL, required
46
+ debug: bool = False # DEBUG, optional
47
+ hosts: list[str] = [] # HOSTS: "a,b" or a JSON array
48
+ token: str = field(variable="SERVICE_TOKEN") # explicit variable name
49
+
50
+ settings = Settings() # loads once; raises esr.SettingsError
51
+ print(settings.debug)
52
+ ```
53
+
54
+ Run `esr login` once a day, then start the app. In a deployment start it with
55
+ `esr run -- <command>`. Tests and CI without an agent set `ESR_OFFLINE=1` and
56
+ provide values through the environment or `.env`.
57
+
58
+ ## Behaviour
59
+
60
+ - **Project and version are in the code**, the environment never is: it is
61
+ the agent's (`development` after login, `esr env use <name>` to switch, or
62
+ the deployment token's).
63
+ - **Variable of a field:** its name in upper snake case (`database_url` →
64
+ `DATABASE_URL`), or `field(variable="…")`. Lookups are case-sensitive.
65
+ - **Sources, first hit wins:** process environment, `.env`, agent, default.
66
+ An empty string is a value. Defaults are used as declared.
67
+ - **`.env`:** `.env` in the working directory, or `env_file="…"` in the class
68
+ statement, or `ESR_ENV_FILE` (empty = no file). No interpolation; invalid
69
+ lines are skipped with a warning that names the line number only.
70
+ - **Types:** `str`, `int`, `float`, `bool` (`1 true t yes y on` / `0 false f
71
+ no n off`), `list[str|int|float|bool]` (`a,b` or a JSON array), and JSON
72
+ values (`esr.Json`, `dict`, `Any`). `T | None` is `T`; give it a default.
73
+ - **Errors:** one `SettingsError` with `code` (`agent_unavailable`,
74
+ `not_signed_in`, `forbidden`, `not_found`, `version_mismatch`,
75
+ `server_unreachable`, `agent_error`, `invalid_settings`) and, for
76
+ `invalid_settings`, the sorted variable names in `missing` and `invalid`.
77
+ The message says what to do (`esr login`, …).
78
+ - **Secret overrides:** when `.env` or the environment replaces a secret or a
79
+ proxy token with a different value, the library prints
80
+ `esr: warning: secret NAME is overridden by .env` and reports the name to
81
+ the agent. Overrides are always allowed.
82
+ - **Values are never printed**: not in messages, warnings, reports or the
83
+ `repr` of a settings object. Settings objects are read-only.
84
+ - **Finding the agent:** `ESR_AGENT_SOCK`, else `ESR_AGENT_URL` with
85
+ `ESR_AGENT_TOKEN` (Docker Compose, see `esr link`), else
86
+ `~/.esr/agent.sock`. 2 s to connect, 30 s for the answer.
87
+
88
+ The fixtures in `conformance/` hold all three libraries to the same rules.
89
+
90
+ ## Development
91
+
92
+ ```
93
+ python3 -m unittest discover -s tests # in python/
94
+ ./test.sh # all libraries, fixtures and examples
95
+ ```
@@ -0,0 +1,10 @@
1
+ esr/__init__.py,sha256=z4outWfGx83NDFF6AKX3vNPr2aXtABu0yVEDXWOc9XI,534
2
+ esr/_agent.py,sha256=v72MbyqYkof2fJ96cyZWcI4ZCZ_ytwIWebtmUGTX8P0,5961
3
+ esr/_core.py,sha256=scQOEbBRQinNBGCQezWz9VjjG9C8VbSSgc3hKj-UuSk,7551
4
+ esr/_settings.py,sha256=gNNj7teBZdF-pR59HRnBhOdZZmF8JvP7PaAdqZW3V-0,18155
5
+ esr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ esr_client_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=W6Qwd1oHUBARAoBAIulcKeZ1NZyarpdVzLhh7ZkvxKk,1064
7
+ esr_client_sdk-1.0.0.dist-info/METADATA,sha256=RD_aDgpp0CHKpfxmax-egzIJXGSfrbi4Mo1dJVhimoc,4018
8
+ esr_client_sdk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ esr_client_sdk-1.0.0.dist-info/top_level.txt,sha256=uv2Bw_jL7uDkhY_qeTvnxBFoGeDkzPfTdRxUwtAkmP8,4
10
+ esr_client_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 labsbit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ esr