involve-benchling 0.1.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.
@@ -0,0 +1,49 @@
1
+ """involve-benchling: an extension of Benchling's V3 Python SDK.
2
+
3
+ Helpers that work alongside ``benchling_v3_sdk`` and accept and return its
4
+ models:
5
+
6
+ - :mod:`involve_benchling.cache` -- tiered, pickle-free response caching.
7
+ - :mod:`involve_benchling.resolve` -- generic name->object resolution with
8
+ typed errors, over any V3 resource.
9
+ - :mod:`involve_benchling.dataframes` -- pandas adapters (optional extra).
10
+ - :mod:`involve_benchling.testing` -- pytest fixtures and resource cleanup.
11
+ - :mod:`involve_benchling.tools` -- cross-resource workflows (roadmap).
12
+
13
+ Quick start::
14
+
15
+ from involve_benchling import BenchlingConfig, connect, resolve
16
+
17
+ config = BenchlingConfig.from_env()
18
+ benchling = connect(config)
19
+ plasmid = resolve.get_by_name(benchling.custom_entity, "pEX-001")
20
+ """
21
+
22
+ from . import resolve
23
+ from .cache import BenchlingCache, CachePolicy
24
+ from .core import BenchlingConfig, connect, connect_async
25
+ from .errors import (
26
+ AmbiguousError,
27
+ CacheError,
28
+ ConfigError,
29
+ InvolveBenchlingError,
30
+ NotFoundError,
31
+ ReadOnlyViolationError,
32
+ )
33
+ from .version import __version__
34
+
35
+ __all__ = [
36
+ "AmbiguousError",
37
+ "BenchlingCache",
38
+ "BenchlingConfig",
39
+ "CacheError",
40
+ "CachePolicy",
41
+ "ConfigError",
42
+ "InvolveBenchlingError",
43
+ "NotFoundError",
44
+ "ReadOnlyViolationError",
45
+ "__version__",
46
+ "connect",
47
+ "connect_async",
48
+ "resolve",
49
+ ]
@@ -0,0 +1,159 @@
1
+ """Caching for Benchling API responses.
2
+
3
+ Reference data (schemas, dropdowns, registries, users) changes rarely but
4
+ is often read many times. A :class:`BenchlingCache` keeps those responses
5
+ locally, so repeat lookups take under a millisecond.
6
+
7
+ Values round-trip through JSON (never pickle). Benchling SDK models are
8
+ Pydantic models and are serialised losslessly. A cached model is rebuilt
9
+ only from a ``benchling_v3_sdk`` class or the ``model`` passed to
10
+ :meth:`BenchlingCache.get_or_fetch`, so a tampered cache file cannot make
11
+ the cache import arbitrary modules::
12
+
13
+ from involve_benchling.cache import BenchlingCache
14
+ from benchling_v3_sdk.types.custom_entity import CustomEntity
15
+
16
+ cache = BenchlingCache.from_policy(policy, namespace=config.base_url)
17
+
18
+ entities = cache.get_or_fetch(
19
+ "entities:by-schema:ts_abc123",
20
+ category="entity",
21
+ model=CustomEntity,
22
+ fetch=lambda: list(benchling.custom_entity.list(schema_eq="ts_abc123")),
23
+ )
24
+
25
+ # after a write:
26
+ cache.invalidate("entities:")
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import hashlib
32
+ import importlib
33
+ from collections.abc import Callable, Sequence
34
+ from typing import Any, TypeVar
35
+
36
+ from pydantic import BaseModel
37
+
38
+ from .backends import MISSING, CacheBackend, DiskBackend, MemoryBackend, TieredBackend
39
+ from .policy import DEFAULT_TTLS, CachePolicy
40
+
41
+ __all__ = [
42
+ "DEFAULT_TTLS",
43
+ "MISSING",
44
+ "BenchlingCache",
45
+ "CacheBackend",
46
+ "CachePolicy",
47
+ "DiskBackend",
48
+ "MemoryBackend",
49
+ "TieredBackend",
50
+ ]
51
+
52
+ M = TypeVar("M", bound=BaseModel)
53
+
54
+
55
+ def _encode(value: Any) -> Any:
56
+ """Encode a value (possibly a Pydantic model or list of them) to JSON-safe form."""
57
+ if isinstance(value, BaseModel):
58
+ return {"__model__": _model_ref(type(value)), "data": value.model_dump_json()}
59
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
60
+ return {"__list__": [_encode(item) for item in value]}
61
+ return {"__json__": value}
62
+
63
+
64
+ def _decode(doc: Any, model: type[BaseModel] | None = None) -> Any:
65
+ if not isinstance(doc, dict):
66
+ return doc
67
+ if "__model__" in doc:
68
+ ref = doc["__model__"]
69
+ model_cls = model if model and ref == _model_ref(model) else _import_model(ref)
70
+ return model_cls.model_validate_json(doc["data"])
71
+ if "__list__" in doc:
72
+ return [_decode(item, model) for item in doc["__list__"]]
73
+ return doc.get("__json__")
74
+
75
+
76
+ def _model_ref(cls: type[BaseModel]) -> str:
77
+ return f"{cls.__module__}:{cls.__qualname__}"
78
+
79
+
80
+ #: Packages whose models the cache imports by name when rehydrating.
81
+ _TRUSTED_MODEL_PACKAGES = ("benchling_v3_sdk",)
82
+
83
+
84
+ def _import_model(ref: str) -> type[BaseModel]:
85
+ module_name, _, qualname = ref.partition(":")
86
+ if module_name.partition(".")[0] not in _TRUSTED_MODEL_PACKAGES:
87
+ raise TypeError(f"{ref} is not a Benchling SDK model; pass it as model=")
88
+ obj: Any = importlib.import_module(module_name)
89
+ for part in qualname.split("."):
90
+ obj = getattr(obj, part)
91
+ if not (isinstance(obj, type) and issubclass(obj, BaseModel)):
92
+ raise TypeError(f"{ref} is not a Pydantic model")
93
+ return obj
94
+
95
+
96
+ class BenchlingCache:
97
+ """High-level cache facade with stats and model-aware serialisation."""
98
+
99
+ def __init__(self, backend: CacheBackend, policy: CachePolicy | None = None) -> None:
100
+ self._backend = backend
101
+ self._policy = policy or CachePolicy()
102
+ self.hits = 0
103
+ self.misses = 0
104
+
105
+ @classmethod
106
+ def from_policy(cls, policy: CachePolicy, *, namespace: str = "") -> BenchlingCache:
107
+ """Build the standard tiered cache described by ``policy``.
108
+
109
+ ``namespace`` (typically the tenant base URL) isolates cache
110
+ directories between tenants.
111
+ """
112
+ memory = MemoryBackend(policy.max_memory_entries)
113
+ if policy.directory is None:
114
+ return cls(memory, policy)
115
+ subdir = hashlib.sha256(namespace.encode()).hexdigest()[:12] if namespace else "default"
116
+ disk = DiskBackend(policy.directory / subdir)
117
+ return cls(TieredBackend(memory, disk), policy)
118
+
119
+ @property
120
+ def hit_rate(self) -> float:
121
+ total = self.hits + self.misses
122
+ return self.hits / total if total else 0.0
123
+
124
+ def get_or_fetch(
125
+ self,
126
+ key: str,
127
+ *,
128
+ fetch: Callable[[], Any],
129
+ category: str = "",
130
+ ttl: float | None = None,
131
+ model: type[BaseModel] | None = None,
132
+ ) -> Any:
133
+ """Return the cached value for ``key``, calling ``fetch`` on a miss.
134
+
135
+ ``ttl`` overrides the policy TTL for ``category``. ``model`` names a
136
+ Pydantic class outside ``benchling_v3_sdk`` that the cached value may
137
+ hold; SDK models need no ``model``. An entry that cannot be decoded
138
+ counts as a miss.
139
+ """
140
+ if not self._policy.enabled:
141
+ return fetch()
142
+ doc = self._backend.get(key)
143
+ if doc is not MISSING:
144
+ try:
145
+ value = _decode(doc, model)
146
+ except (ImportError, AttributeError, TypeError, ValueError):
147
+ pass
148
+ else:
149
+ self.hits += 1
150
+ return value
151
+ self.misses += 1
152
+ value = fetch()
153
+ resolved_ttl = ttl if ttl is not None else self._policy.ttl_for(category)
154
+ self._backend.set(key, _encode(value), resolved_ttl)
155
+ return value
156
+
157
+ def invalidate(self, prefix: str = "") -> int:
158
+ """Drop every entry whose key starts with ``prefix``. Returns the count."""
159
+ return self._backend.invalidate(prefix)
@@ -0,0 +1,164 @@
1
+ """Cache backends.
2
+
3
+ Values are stored as JSON documents, never pickle. Pydantic models from
4
+ the Benchling SDK are serialised with ``model_dump_json`` and rehydrated
5
+ with ``model_validate_json``.
6
+
7
+ The disk tier creates its directory and files readable only by the current
8
+ user, because cached responses can hold sensitive tenant data.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import tempfile
18
+ import time
19
+ from collections import OrderedDict
20
+ from pathlib import Path
21
+ from typing import Any, Protocol, runtime_checkable
22
+
23
+
24
+ class _Missing:
25
+ def __repr__(self) -> str: # pragma: no cover
26
+ return "<MISSING>"
27
+
28
+
29
+ #: Sentinel returned by :meth:`CacheBackend.get` on a miss.
30
+ MISSING: Any = _Missing()
31
+
32
+
33
+ @runtime_checkable
34
+ class CacheBackend(Protocol):
35
+ """Minimal interface a cache backend must implement.
36
+
37
+ Values are JSON-serialisable documents (dict/list/str/num/bool/None).
38
+ """
39
+
40
+ def get(self, key: str) -> Any: ...
41
+
42
+ def set(self, key: str, value: Any, ttl: float) -> None: ...
43
+
44
+ def invalidate(self, prefix: str = "") -> int: ...
45
+
46
+
47
+ class MemoryBackend:
48
+ """In-process LRU cache with per-entry TTL."""
49
+
50
+ def __init__(self, max_entries: int = 1024) -> None:
51
+ self._max = max_entries
52
+ self._data: OrderedDict[str, tuple[float, Any]] = OrderedDict()
53
+
54
+ def get(self, key: str) -> Any:
55
+ entry = self._data.get(key)
56
+ if entry is None:
57
+ return MISSING
58
+ expires_at, value = entry
59
+ if time.monotonic() >= expires_at:
60
+ del self._data[key]
61
+ return MISSING
62
+ self._data.move_to_end(key)
63
+ return value
64
+
65
+ def set(self, key: str, value: Any, ttl: float) -> None:
66
+ self._data[key] = (time.monotonic() + ttl, value)
67
+ self._data.move_to_end(key)
68
+ while len(self._data) > self._max:
69
+ self._data.popitem(last=False)
70
+
71
+ def invalidate(self, prefix: str = "") -> int:
72
+ keys = [k for k in self._data if k.startswith(prefix)]
73
+ for k in keys:
74
+ del self._data[k]
75
+ return len(keys)
76
+
77
+
78
+ class DiskBackend:
79
+ """Persistent cache: one JSON file per key, shared across processes.
80
+
81
+ Writes are atomic (write to a unique temp file, then rename). Corrupt or
82
+ unreadable entries are treated as misses, never as errors. The directory
83
+ holds a ``.gitignore`` so a cache inside a repository is never committed.
84
+ """
85
+
86
+ def __init__(self, directory: Path) -> None:
87
+ self._dir = directory
88
+ self._index_dir = directory / "entries"
89
+ self._index_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
90
+ gitignore = directory / ".gitignore"
91
+ if not gitignore.exists():
92
+ with contextlib.suppress(OSError):
93
+ gitignore.write_text("*\n")
94
+
95
+ def _path(self, key: str) -> Path:
96
+ digest = hashlib.sha256(key.encode()).hexdigest()[:40]
97
+ return self._index_dir / f"{digest}.json"
98
+
99
+ def get(self, key: str) -> Any:
100
+ path = self._path(key)
101
+ try:
102
+ doc = json.loads(path.read_text())
103
+ except (OSError, ValueError):
104
+ return MISSING
105
+ if doc.get("key") != key or time.time() >= doc.get("expires_at", 0):
106
+ return MISSING
107
+ return doc.get("value")
108
+
109
+ def set(self, key: str, value: Any, ttl: float) -> None:
110
+ path = self._path(key)
111
+ doc = {"key": key, "expires_at": time.time() + ttl, "value": value}
112
+ try:
113
+ # mkstemp creates the file with mode 0600.
114
+ fd, tmp_name = tempfile.mkstemp(dir=self._index_dir, suffix=".tmp")
115
+ except OSError:
116
+ return
117
+ tmp = Path(tmp_name)
118
+ try:
119
+ with os.fdopen(fd, "w") as f:
120
+ f.write(json.dumps(doc))
121
+ tmp.replace(path)
122
+ except OSError:
123
+ # Cache failures must never break the caller.
124
+ tmp.unlink(missing_ok=True)
125
+
126
+ def invalidate(self, prefix: str = "") -> int:
127
+ count = 0
128
+ for path in self._index_dir.glob("*.json"):
129
+ try:
130
+ doc = json.loads(path.read_text())
131
+ except (OSError, ValueError):
132
+ path.unlink(missing_ok=True)
133
+ continue
134
+ if doc.get("key", "").startswith(prefix):
135
+ path.unlink(missing_ok=True)
136
+ count += 1
137
+ return count
138
+
139
+
140
+ class TieredBackend:
141
+ """Memory tier in front of a persistent tier."""
142
+
143
+ def __init__(self, memory: MemoryBackend, disk: DiskBackend) -> None:
144
+ self._memory = memory
145
+ self._disk = disk
146
+
147
+ def get(self, key: str) -> Any:
148
+ value = self._memory.get(key)
149
+ if value is not MISSING:
150
+ return value
151
+ value = self._disk.get(key)
152
+ if value is not MISSING:
153
+ # Re-warm the memory tier; TTL is enforced by the disk doc,
154
+ # so a short memory TTL keeps the tiers close.
155
+ self._memory.set(key, value, ttl=60)
156
+ return value
157
+
158
+ def set(self, key: str, value: Any, ttl: float) -> None:
159
+ self._memory.set(key, value, ttl)
160
+ self._disk.set(key, value, ttl)
161
+
162
+ def invalidate(self, prefix: str = "") -> int:
163
+ self._memory.invalidate(prefix)
164
+ return self._disk.invalidate(prefix)
@@ -0,0 +1,39 @@
1
+ """Cache policy: what to cache, where, and for how long."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ #: Default TTLs (seconds) per category. Categories are free-form strings;
9
+ #: these defaults reflect how often each kind of Benchling data changes.
10
+ DEFAULT_TTLS: dict[str, float] = {
11
+ "schema": 24 * 3600,
12
+ "registry": 12 * 3600,
13
+ "dropdown": 12 * 3600,
14
+ "folder": 12 * 3600,
15
+ "project": 12 * 3600,
16
+ "user": 12 * 3600,
17
+ "entity": 3600,
18
+ }
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class CachePolicy:
23
+ """Configuration for :class:`~involve_benchling.cache.BenchlingCache`."""
24
+
25
+ enabled: bool = True
26
+ #: Directory for the persistent tier. ``None`` disables the disk tier.
27
+ directory: Path | None = Path(".benchling-cache")
28
+ #: Maximum entries held in the in-memory LRU tier.
29
+ max_memory_entries: int = 1024
30
+ #: TTL (seconds) used when a category has no specific TTL.
31
+ default_ttl: float = 3600
32
+ #: Per-category TTL overrides, merged over :data:`DEFAULT_TTLS`.
33
+ ttls: dict[str, float] = field(default_factory=dict)
34
+
35
+ def ttl_for(self, category: str) -> float:
36
+ """Resolve the TTL for a category."""
37
+ if category in self.ttls:
38
+ return self.ttls[category]
39
+ return DEFAULT_TTLS.get(category, self.default_ttl)
@@ -0,0 +1,7 @@
1
+ """Core: configuration and SDK client construction."""
2
+
3
+ from .client import connect, connect_async
4
+ from .config import BenchlingConfig
5
+ from .pacing import Pacer, pacer_for
6
+
7
+ __all__ = ["BenchlingConfig", "Pacer", "connect", "connect_async", "pacer_for"]
@@ -0,0 +1,125 @@
1
+ """Construction helpers for ``benchling_v3_sdk`` clients.
2
+
3
+ :func:`connect` returns a plain ``benchling_v3_sdk.Benchling`` client, and
4
+ every helper in this library accepts SDK clients and resources directly.
5
+
6
+ The client is built on this library's own ``httpx`` client when either
7
+ option below is set:
8
+
9
+ - ``config.read_only`` blocks every request that could change tenant data
10
+ (see :mod:`~involve_benchling.core.readonly`).
11
+ - ``config.pacing`` caps concurrent requests and pauses them together after
12
+ a ``429`` (see :mod:`~involve_benchling.core.pacing`).
13
+
14
+ The read-only check runs first, so a blocked write never waits.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ import httpx
22
+
23
+ from ..errors import ConfigError
24
+ from .config import BenchlingConfig
25
+ from .pacing import AsyncPacedTransport, PacedTransport, Pacer, _register
26
+ from .readonly import AsyncReadOnlyTransport, ReadOnlyTransport
27
+
28
+ if TYPE_CHECKING:
29
+ from benchling_v3_sdk import AsyncBenchling, Benchling
30
+
31
+ #: Request timeout (seconds) for clients built here, matching the SDK default.
32
+ _DEFAULT_TIMEOUT = 60.0
33
+
34
+
35
+ def _client_kwargs(config: BenchlingConfig) -> dict[str, Any]:
36
+ kwargs: dict[str, Any] = {"base_url": config.base_url}
37
+ if config.early_access:
38
+ kwargs["early_access"] = "true"
39
+ if config.api_key:
40
+ kwargs["api_key"] = config.api_key
41
+ else:
42
+ kwargs["client_id"] = config.oauth_client_id
43
+ kwargs["client_secret"] = config.oauth_client_secret
44
+ return kwargs
45
+
46
+
47
+ def _owns_http_client(config: BenchlingConfig) -> bool:
48
+ return config.read_only or config.pacing
49
+
50
+
51
+ def _http_kwargs(extra: dict[str, Any]) -> dict[str, Any]:
52
+ if "httpx_client" in extra:
53
+ raise ConfigError(
54
+ "This config builds its own httpx client for read-only access or pacing; "
55
+ "do not pass httpx_client (set pacing=False to supply your own)."
56
+ )
57
+ return {
58
+ "timeout": extra.get("timeout") or _DEFAULT_TIMEOUT,
59
+ "follow_redirects": extra.get("follow_redirects", True),
60
+ }
61
+
62
+
63
+ def _sync_transport(config: BenchlingConfig) -> tuple[httpx.BaseTransport, Pacer | None]:
64
+ transport: httpx.BaseTransport = httpx.HTTPTransport()
65
+ pacer = Pacer(config.max_concurrency) if config.pacing else None
66
+ if pacer:
67
+ transport = PacedTransport(pacer, transport)
68
+ if config.read_only:
69
+ transport = ReadOnlyTransport(config.base_url, transport)
70
+ return transport, pacer
71
+
72
+
73
+ def _async_transport(
74
+ config: BenchlingConfig,
75
+ ) -> tuple[httpx.AsyncBaseTransport, Pacer | None]:
76
+ transport: httpx.AsyncBaseTransport = httpx.AsyncHTTPTransport()
77
+ pacer = Pacer(config.max_concurrency) if config.pacing else None
78
+ if pacer:
79
+ transport = AsyncPacedTransport(pacer, transport)
80
+ if config.read_only:
81
+ transport = AsyncReadOnlyTransport(config.base_url, transport)
82
+ return transport, pacer
83
+
84
+
85
+ def connect(config: BenchlingConfig, **extra: Any) -> Benchling:
86
+ """Create a synchronous ``benchling_v3_sdk.Benchling`` client.
87
+
88
+ Extra keyword arguments (``timeout``, ``max_retries``, ``httpx_client``,
89
+ ...) are forwarded to the SDK constructor.
90
+
91
+ Raises:
92
+ ConfigError: ``httpx_client`` was passed while ``config.read_only`` or
93
+ ``config.pacing`` is set.
94
+ """
95
+ from benchling_v3_sdk import Benchling
96
+
97
+ pacer = None
98
+ if _owns_http_client(config):
99
+ http = _http_kwargs(extra)
100
+ transport, pacer = _sync_transport(config)
101
+ extra["httpx_client"] = httpx.Client(transport=transport, **http)
102
+ client = Benchling(**_client_kwargs(config), **extra)
103
+ if pacer:
104
+ _register(client, pacer)
105
+ return client
106
+
107
+
108
+ def connect_async(config: BenchlingConfig, **extra: Any) -> AsyncBenchling:
109
+ """Create an asynchronous ``benchling_v3_sdk.AsyncBenchling`` client.
110
+
111
+ Raises:
112
+ ConfigError: ``httpx_client`` was passed while ``config.read_only`` or
113
+ ``config.pacing`` is set.
114
+ """
115
+ from benchling_v3_sdk import AsyncBenchling
116
+
117
+ pacer = None
118
+ if _owns_http_client(config):
119
+ http = _http_kwargs(extra)
120
+ transport, pacer = _async_transport(config)
121
+ extra["httpx_client"] = httpx.AsyncClient(transport=transport, **http)
122
+ client = AsyncBenchling(**_client_kwargs(config), **extra)
123
+ if pacer:
124
+ _register(client, pacer)
125
+ return client
@@ -0,0 +1,102 @@
1
+ """Immutable configuration for connecting to Benchling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field, replace
7
+ from typing import Any
8
+
9
+ from ..cache.policy import CachePolicy
10
+ from ..errors import ConfigError
11
+
12
+ _ENV_PREFIX = "BENCHLING_"
13
+
14
+
15
+ def _env_flag(name: str, default: bool = False) -> bool:
16
+ value = os.getenv(f"{_ENV_PREFIX}{name}", "").strip().lower()
17
+ if not value:
18
+ return default
19
+ return value in ("1", "true", "yes")
20
+
21
+
22
+ def _env_int(name: str, default: int) -> int:
23
+ value = os.getenv(f"{_ENV_PREFIX}{name}", "").strip()
24
+ if not value:
25
+ return default
26
+ try:
27
+ return int(value)
28
+ except ValueError:
29
+ raise ConfigError(f"{_ENV_PREFIX}{name} must be an integer, got {value!r}") from None
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class BenchlingConfig:
34
+ """Connection settings for a Benchling tenant.
35
+
36
+ Authenticate with either an API key or OAuth client credentials.
37
+ All fields are immutable; use :meth:`with_options` to derive variants.
38
+ """
39
+
40
+ base_url: str
41
+ api_key: str | None = None
42
+ oauth_client_id: str | None = None
43
+ oauth_client_secret: str | None = None
44
+ early_access: bool = False
45
+ registry_name: str | None = None
46
+ #: Clients built from this config send only reads (see :mod:`~involve_benchling.core.readonly`).
47
+ read_only: bool = False
48
+ #: Clients pause together after a ``429`` (see :mod:`~involve_benchling.core.pacing`).
49
+ pacing: bool = True
50
+ #: Most requests a paced client sends at once.
51
+ max_concurrency: int = 4
52
+ cache: CachePolicy = field(default_factory=CachePolicy)
53
+
54
+ def __post_init__(self) -> None:
55
+ if not self.base_url:
56
+ raise ConfigError("base_url is required (e.g. https://yourtenant.benchling.com)")
57
+ has_key = bool(self.api_key)
58
+ has_oauth = bool(self.oauth_client_id and self.oauth_client_secret)
59
+ if not has_key and not has_oauth:
60
+ raise ConfigError(
61
+ "Provide api_key or oauth_client_id + oauth_client_secret "
62
+ f"(or set {_ENV_PREFIX}API_KEY / {_ENV_PREFIX}OAUTH_CLIENT_ID "
63
+ f"and {_ENV_PREFIX}OAUTH_CLIENT_SECRET)."
64
+ )
65
+ if has_key and has_oauth:
66
+ raise ConfigError("Provide api_key or OAuth credentials, not both.")
67
+ if self.max_concurrency < 1:
68
+ raise ConfigError(f"max_concurrency must be at least 1, got {self.max_concurrency}")
69
+
70
+ @property
71
+ def auth_method(self) -> str:
72
+ """``"api_key"`` or ``"oauth"``."""
73
+ return "api_key" if self.api_key else "oauth"
74
+
75
+ @classmethod
76
+ def from_env(cls, **overrides: Any) -> BenchlingConfig:
77
+ """Build a config from ``BENCHLING_*`` environment variables.
78
+
79
+ Recognised variables: ``BENCHLING_BASE_URL``, ``BENCHLING_API_KEY``,
80
+ ``BENCHLING_OAUTH_CLIENT_ID``, ``BENCHLING_OAUTH_CLIENT_SECRET``,
81
+ ``BENCHLING_EARLY_ACCESS``, ``BENCHLING_REGISTRY_NAME``,
82
+ ``BENCHLING_READ_ONLY``, ``BENCHLING_PACING`` (on unless set to a false
83
+ value), ``BENCHLING_MAX_CONCURRENCY``.
84
+ Keyword arguments override environment values.
85
+ """
86
+ env: dict[str, Any] = {
87
+ "base_url": os.getenv(f"{_ENV_PREFIX}BASE_URL", ""),
88
+ "api_key": os.getenv(f"{_ENV_PREFIX}API_KEY") or None,
89
+ "oauth_client_id": os.getenv(f"{_ENV_PREFIX}OAUTH_CLIENT_ID") or None,
90
+ "oauth_client_secret": os.getenv(f"{_ENV_PREFIX}OAUTH_CLIENT_SECRET") or None,
91
+ "early_access": _env_flag("EARLY_ACCESS"),
92
+ "registry_name": os.getenv(f"{_ENV_PREFIX}REGISTRY_NAME") or None,
93
+ "read_only": _env_flag("READ_ONLY"),
94
+ "pacing": _env_flag("PACING", default=True),
95
+ "max_concurrency": _env_int("MAX_CONCURRENCY", 4),
96
+ }
97
+ env.update(overrides)
98
+ return cls(**env)
99
+
100
+ def with_options(self, **changes: Any) -> BenchlingConfig:
101
+ """Return a copy of this config with the given fields replaced."""
102
+ return replace(self, **changes)