Coverage for core / src / sensorkit / api / bootstrap.py: 68%
76 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2import asyncio
3import os
4import pathlib
5import warnings
6from collections.abc import Iterable
7from typing import Literal, cast, overload
9from sensorkit.backend.base import BackendImpl
10from sensorkit.common.importutil import import_module_or_file, obj_from_spec
11from sensorkit.config.parser import SensorKitBaseConfig, SensorKitConfig, parse_config
13DEFAULT_BACKEND = "nats"
14DEFAULT_CONFIG_FILE = "sensorkit.yaml"
15DEFAULT_BASE_IMPORTS = (
16 "sensorkit.std",
17 "sensorkit.sensor",
18 "sensorkit.webapi",
19 "sensorkit.data.filesys",
20 "sensorkit.data.fits",
21 "sensorkit.data.local",
22)
23BACKEND_MODULES = {
24 "nats": "sensorkit.backend.nats",
25 "fake": "sensorkit.backend.fake",
26}
28_read_lock = asyncio.Lock()
29_base: SensorKitBaseConfig | None = None
30_resolved: SensorKitConfig | None = None
33@overload
34async def _read_config(*, required: Literal[False] = False) -> SensorKitBaseConfig | None: ...
37@overload
38async def _read_config(*, required: Literal[True]) -> SensorKitBaseConfig: ...
41async def _read_config(*, required: bool = False):
42 """Read and memoize the base config.
44 Callers must hold `_read_lock`.
45 """
46 global _base
48 def _read_config_sync(location: str | None):
49 import yaml
51 path = pathlib.Path(location or DEFAULT_CONFIG_FILE)
53 try:
54 base = parse_config(yaml.safe_load(path.read_text()))
55 except FileNotFoundError:
56 if required or location is not None:
57 raise
59 base = None
61 return base
63 if _base is None:
64 _base = await asyncio.to_thread(
65 _read_config_sync,
66 os.environ.get("SENSORKIT_CONFIG"),
67 )
69 return _base
72def _imports_from_env(var: str, default: Iterable[str] = ()) -> list[str]:
73 return [mod.strip() for mod in os.environ.get(var, "").split(",") if mod] or list(default)
76def _import_modules_sync(*, fail_policy: Literal["error", "warn", "ignore"]):
77 imports = _imports_from_env("SENSORKIT_BASE_IMPORTS", DEFAULT_BASE_IMPORTS)
78 imports.extend(_imports_from_env("SENSORKIT_IMPORTS"))
80 if _base is not None:
81 imports.extend(_base.configured_imports())
83 for module in imports:
84 try:
85 import_module_or_file(module)
86 except Exception:
87 match fail_policy:
88 case "error":
89 raise
90 case "warn":
91 warnings.warn(f"Failed to import: {module}", stacklevel=1)
92 case "ignore":
93 pass
96def set_config_location(location: str | None) -> None:
97 """Set the location of the SensorKit configuration file.
99 This must be called before `load_config`, `import_modules`, and `connect`
100 to have effect.
101 """
102 if location is not None:
103 current = os.environ.get("SENSORKIT_CONFIG", DEFAULT_CONFIG_FILE)
105 if _base is not None and location != current:
106 raise RuntimeError(f"config already loaded from {current}, cannot set to {location}")
108 os.environ["SENSORKIT_CONFIG"] = location
111async def load_config(
112 *,
113 fail_policy: Literal["error", "warn", "ignore"] = "warn",
114) -> SensorKitConfig:
115 """Loads and fully resolves configuration, importing modules as needed.
117 The fully resolved configuration is memoized; subsequent calls return the
118 cached result without re-resolving.
119 """
120 global _resolved
122 async with _read_lock:
123 if _resolved is None:
124 base = await _read_config(required=True)
125 await asyncio.to_thread(_import_modules_sync, fail_policy=fail_policy)
126 _resolved = base.resolve_dynamic_sections()
128 return cast(SensorKitConfig, _resolved)
131async def import_modules(*, fail_policy: Literal["error", "warn", "ignore"] = "error"):
132 """Imports modules based on environment and configuration."""
133 async with _read_lock:
134 await _read_config()
136 await asyncio.to_thread(_import_modules_sync, fail_policy=fail_policy)
139async def connect(*, backend: str | None = None):
140 """Creates a SensorKit client and connects to the backend.
142 The backend is either provided as a string, read from the environment, or
143 (if neither is present) read from the SensorKit configuration file.
145 User modules are not imported automatically. Callers that need to access
146 types provided by modules must opt in to these imports by calling
147 `import_modules()` or `load_config()` (to retrieve the fully resolved
148 configuration structure).
149 """
150 from sensorkit.core.client import SensorKit
152 backend = backend or os.environ.get("SENSORKIT_BACKEND")
154 if not backend:
155 async with _read_lock:
156 config = await _read_config()
158 backend = config.sensorkit.backend if config else None
160 backend_module = BACKEND_MODULES.get(backend) or BACKEND_MODULES[DEFAULT_BACKEND]
161 backend_cls = await asyncio.to_thread(
162 obj_from_spec,
163 spec=backend_module,
164 base=BackendImpl,
165 subclass=True,
166 )
167 backend_impl = await backend_cls.create()
168 return SensorKit(backend=backend_impl)