esr-client-sdk 1.0.0__tar.gz
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_client_sdk-1.0.0/LICENSE +21 -0
- esr_client_sdk-1.0.0/PKG-INFO +95 -0
- esr_client_sdk-1.0.0/README.md +82 -0
- esr_client_sdk-1.0.0/pyproject.toml +26 -0
- esr_client_sdk-1.0.0/setup.cfg +4 -0
- esr_client_sdk-1.0.0/src/esr/__init__.py +17 -0
- esr_client_sdk-1.0.0/src/esr/_agent.py +150 -0
- esr_client_sdk-1.0.0/src/esr/_core.py +250 -0
- esr_client_sdk-1.0.0/src/esr/_settings.py +426 -0
- esr_client_sdk-1.0.0/src/esr/py.typed +0 -0
- esr_client_sdk-1.0.0/src/esr_client_sdk.egg-info/PKG-INFO +95 -0
- esr_client_sdk-1.0.0/src/esr_client_sdk.egg-info/SOURCES.txt +14 -0
- esr_client_sdk-1.0.0/src/esr_client_sdk.egg-info/dependency_links.txt +1 -0
- esr_client_sdk-1.0.0/src/esr_client_sdk.egg-info/top_level.txt +1 -0
- esr_client_sdk-1.0.0/tests/test_conformance.py +181 -0
- esr_client_sdk-1.0.0/tests/test_integration.py +393 -0
|
@@ -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,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,82 @@
|
|
|
1
|
+
# esr for Python
|
|
2
|
+
|
|
3
|
+
Typed settings from env-plane. The library asks the local `esr` agent for the
|
|
4
|
+
values of your project and version, lets `.env` and the process environment
|
|
5
|
+
override them, and fails fast with one error that names every problem.
|
|
6
|
+
|
|
7
|
+
Python 3.10+, standard library only, typed (`py.typed`).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
From PyPI (the package is `esr-client-sdk`, the module is `esr`):
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
pip install esr-client-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Coding agents
|
|
18
|
+
|
|
19
|
+
`esr skill install` (in the project's repository) installs the env-plane
|
|
20
|
+
skill for Claude Code, Cursor and Codex. It teaches the agent how to onboard
|
|
21
|
+
the project: find the values it reads, upload them with `esr vars`, declare
|
|
22
|
+
them with this library and wire `esr run` into tools, Docker and
|
|
23
|
+
deployments, without writing secrets into files or transcripts.
|
|
24
|
+
`esr skill` prints it.
|
|
25
|
+
|
|
26
|
+
## Use
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from esr import BaseSettings, field
|
|
30
|
+
|
|
31
|
+
class Settings(BaseSettings, project="shop", version="main"):
|
|
32
|
+
database_url: str # DATABASE_URL, required
|
|
33
|
+
debug: bool = False # DEBUG, optional
|
|
34
|
+
hosts: list[str] = [] # HOSTS: "a,b" or a JSON array
|
|
35
|
+
token: str = field(variable="SERVICE_TOKEN") # explicit variable name
|
|
36
|
+
|
|
37
|
+
settings = Settings() # loads once; raises esr.SettingsError
|
|
38
|
+
print(settings.debug)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Run `esr login` once a day, then start the app. In a deployment start it with
|
|
42
|
+
`esr run -- <command>`. Tests and CI without an agent set `ESR_OFFLINE=1` and
|
|
43
|
+
provide values through the environment or `.env`.
|
|
44
|
+
|
|
45
|
+
## Behaviour
|
|
46
|
+
|
|
47
|
+
- **Project and version are in the code**, the environment never is: it is
|
|
48
|
+
the agent's (`development` after login, `esr env use <name>` to switch, or
|
|
49
|
+
the deployment token's).
|
|
50
|
+
- **Variable of a field:** its name in upper snake case (`database_url` →
|
|
51
|
+
`DATABASE_URL`), or `field(variable="…")`. Lookups are case-sensitive.
|
|
52
|
+
- **Sources, first hit wins:** process environment, `.env`, agent, default.
|
|
53
|
+
An empty string is a value. Defaults are used as declared.
|
|
54
|
+
- **`.env`:** `.env` in the working directory, or `env_file="…"` in the class
|
|
55
|
+
statement, or `ESR_ENV_FILE` (empty = no file). No interpolation; invalid
|
|
56
|
+
lines are skipped with a warning that names the line number only.
|
|
57
|
+
- **Types:** `str`, `int`, `float`, `bool` (`1 true t yes y on` / `0 false f
|
|
58
|
+
no n off`), `list[str|int|float|bool]` (`a,b` or a JSON array), and JSON
|
|
59
|
+
values (`esr.Json`, `dict`, `Any`). `T | None` is `T`; give it a default.
|
|
60
|
+
- **Errors:** one `SettingsError` with `code` (`agent_unavailable`,
|
|
61
|
+
`not_signed_in`, `forbidden`, `not_found`, `version_mismatch`,
|
|
62
|
+
`server_unreachable`, `agent_error`, `invalid_settings`) and, for
|
|
63
|
+
`invalid_settings`, the sorted variable names in `missing` and `invalid`.
|
|
64
|
+
The message says what to do (`esr login`, …).
|
|
65
|
+
- **Secret overrides:** when `.env` or the environment replaces a secret or a
|
|
66
|
+
proxy token with a different value, the library prints
|
|
67
|
+
`esr: warning: secret NAME is overridden by .env` and reports the name to
|
|
68
|
+
the agent. Overrides are always allowed.
|
|
69
|
+
- **Values are never printed**: not in messages, warnings, reports or the
|
|
70
|
+
`repr` of a settings object. Settings objects are read-only.
|
|
71
|
+
- **Finding the agent:** `ESR_AGENT_SOCK`, else `ESR_AGENT_URL` with
|
|
72
|
+
`ESR_AGENT_TOKEN` (Docker Compose, see `esr link`), else
|
|
73
|
+
`~/.esr/agent.sock`. 2 s to connect, 30 s for the answer.
|
|
74
|
+
|
|
75
|
+
The fixtures in `conformance/` hold all three libraries to the same rules.
|
|
76
|
+
|
|
77
|
+
## Development
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
python3 -m unittest discover -s tests # in python/
|
|
81
|
+
./test.sh # all libraries, fixtures and examples
|
|
82
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "esr-client-sdk"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "env-plane settings: typed configuration and secrets from the local esr agent"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
license = "MIT"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Typing :: Typed",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Source = "https://github.com/labsbit/esr-sdk"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools]
|
|
22
|
+
package-dir = { "" = "src" }
|
|
23
|
+
packages = ["esr"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.package-data]
|
|
26
|
+
esr = ["py.typed"]
|
|
@@ -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"
|
|
@@ -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"))
|
|
@@ -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()
|