Coverage for python/lsst/images/serialization/_io.py: 91%

88 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-07-16 15:24 -0700

1# This file is part of lsst-images. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11"""Generic ``read_archive`` / ``write_archive`` dispatchers and the 

12schema-name registry. 

13""" 

14 

15from __future__ import annotations 

16 

17__all__ = ( 

18 "class_for_schema", 

19 "parameterize_tree", 

20 "public_type_for_schema", 

21 "read_archive", 

22 "register_schema_class", 

23 "tree_class_for_info", 

24 "write_archive", 

25) 

26 

27import importlib 

28import importlib.metadata 

29from pathlib import Path 

30from typing import IO, TYPE_CHECKING, Any, overload 

31 

32from lsst.resources import ResourcePathExpression 

33 

34from ._backends import backend_for_path 

35from ._common import ArchiveReadError, ArchiveTree 

36 

37if TYPE_CHECKING: 

38 from ._input_archive import ArchiveInfo 

39 

40_REGISTRY: dict[str, type[ArchiveTree]] = {} 

41"""Map of ``SCHEMA_NAME`` to the registered ``ArchiveTree`` subclass. 

42 

43The registry is keyed by name only. Schema-version compatibility is 

44enforced when the selected tree's ``model_validate*`` runs, via 

45``min_read_version``. 

46""" 

47 

48_SCHEMA_ENTRY_POINT_GROUP = "lsst.images.schemas" 

49"""Entry point group for third-party serialization-model providers.""" 

50 

51_BUILTIN_SCHEMA_PROVIDERS: dict[str, str] = { 

52 "cell_aperture_correction_map": ( 

53 "lsst.images.cells._aperture_corrections:CellApertureCorrectionMapSerializationModel" 

54 ), 

55 "cell_coadd": "lsst.images.cells._coadd:CellCoaddSerializationModel", 

56 "cell_psf": "lsst.images.cells._psf:CellPointSpreadFunctionSerializationModel", 

57 "coadd_provenance": "lsst.images.cells._provenance:CoaddProvenanceSerializationModel", 

58} 

59"""Schema providers owned by this package but not imported by ``lsst.images``. 

60 

61These duplicate the package's own ``lsst.images.schemas`` entry points so 

62source-tree use via ``PYTHONPATH=python`` has the same lazy-import behavior as 

63an installed distribution with entry point metadata. 

64 

65Schemas whose model classes are imported unconditionally by ``lsst.images`` do 

66not need built-in providers or entry points: their ``ArchiveTree`` subclass 

67hooks register them before this lazy path is needed. 

68""" 

69 

70 

71def class_for_schema(schema_name: str) -> type[ArchiveTree] | None: 

72 """Return the registered ``ArchiveTree`` subclass for ``schema_name``. 

73 

74 If no class is already registered, this attempts schema-specific lazy 

75 imports from built-in providers and then from entry points in the 

76 ``lsst.images.schemas`` group before returning `None`. 

77 

78 Parameters 

79 ---------- 

80 schema_name 

81 Schema name (e.g. ``"visit_image"``). 

82 """ 

83 if (cls := _REGISTRY.get(schema_name)) is not None: 

84 return cls 

85 _load_builtin_schema_provider(schema_name) 

86 if (cls := _REGISTRY.get(schema_name)) is not None: 

87 return cls 

88 _load_schema_entry_points(schema_name) 

89 return _REGISTRY.get(schema_name) 

90 

91 

92def register_schema_class(cls: type[ArchiveTree]) -> None: 

93 """Register ``cls`` under ``cls.SCHEMA_NAME``. 

94 

95 No-op when the same class is registered again (re-import during 

96 tests). Raises `RuntimeError` when a *different* class is 

97 registered under an existing name. 

98 

99 Intended to be called from ``ArchiveTree.__pydantic_init_subclass__``; 

100 not part of the public API. 

101 """ 

102 key = cls.SCHEMA_NAME 

103 existing = _REGISTRY.get(key) 

104 if existing is cls: 

105 return 

106 if existing is not None: 

107 raise RuntimeError( 

108 f"Schema {cls.SCHEMA_NAME!r} is already registered to " 

109 f"{existing.__qualname__}; refusing to replace it with " 

110 f"{cls.__qualname__}." 

111 ) 

112 _REGISTRY[key] = cls 

113 

114 

115def _load_builtin_schema_provider(schema_name: str) -> None: 

116 """Import a package-local provider for ``schema_name``, if one exists.""" 

117 provider = _BUILTIN_SCHEMA_PROVIDERS.get(schema_name) 

118 if provider is None: 

119 return 

120 try: 

121 obj = _load_provider_object(provider) 

122 except Exception as err: 

123 raise ArchiveReadError( 

124 f"Could not load built-in schema provider {provider!r} for schema {schema_name!r}: {err}" 

125 ) from err 

126 _register_provider_object(obj) 

127 if schema_name not in _REGISTRY: 127 ↛ 128line 127 didn't jump to line 128 because the condition on line 127 was never true

128 raise ArchiveReadError( 

129 f"Built-in schema provider {provider!r} did not register schema {schema_name!r}." 

130 ) 

131 

132 

133def _load_schema_entry_points(schema_name: str) -> None: 

134 """Load entry points named ``schema_name`` from ``lsst.images.schemas``.""" 

135 loaded: list[str] = [] 

136 for entry_point in importlib.metadata.entry_points( 

137 group=_SCHEMA_ENTRY_POINT_GROUP, 

138 name=schema_name, 

139 ): 

140 loaded.append(entry_point.value) 

141 try: 

142 obj = entry_point.load() 

143 except Exception as err: 

144 raise ArchiveReadError( 

145 f"Could not load schema provider entry point {entry_point.value!r} " 

146 f"for schema {schema_name!r}: {err}" 

147 ) from err 

148 _register_provider_object(obj) 

149 if loaded and schema_name not in _REGISTRY: 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true

150 raise ArchiveReadError( 

151 f"Schema provider entry point(s) for {schema_name!r} did not register that schema: {loaded}." 

152 ) 

153 

154 

155def _load_provider_object(provider: str) -> object: 

156 """Load ``module[:attribute[.nested]]`` provider specifications.""" 

157 module_name, _, attr_path = provider.partition(":") 

158 obj: object = importlib.import_module(module_name) 

159 if attr_path: 159 ↛ 162line 159 didn't jump to line 162 because the condition on line 159 was always true

160 for attr in attr_path.split("."): 

161 obj = getattr(obj, attr) 

162 return obj 

163 

164 

165def _register_provider_object(obj: object) -> None: 

166 """Register ``obj`` if a provider returned an ``ArchiveTree`` subclass.""" 

167 if isinstance(obj, type) and issubclass(obj, ArchiveTree): 167 ↛ exitline 167 didn't return from function '_register_provider_object' because the condition on line 167 was always true

168 register_schema_class(obj) 

169 

170 

171def tree_class_for_info(info: ArchiveInfo, path: ResourcePathExpression | IO[bytes]) -> type[ArchiveTree]: 

172 """Return the registered `ArchiveTree` subclass for ``info``'s schema. 

173 

174 Parameters 

175 ---------- 

176 info 

177 Basic archive info whose ``schema_name`` selects the tree class. 

178 path 

179 Path or stream being opened, used only for the error message. 

180 

181 Raises 

182 ------ 

183 ArchiveReadError 

184 If no class is registered for the schema. 

185 """ 

186 tree_cls = class_for_schema(info.schema_name) 

187 if tree_cls is None: 

188 raise ArchiveReadError(f"No registered schema {info.schema_name!r}; cannot open {path!r}.") 

189 return tree_cls 

190 

191 

192def parameterize_tree( 

193 tree_cls: type[ArchiveTree], 

194 pointer_type: type[Any], 

195) -> type[ArchiveTree]: 

196 """Parameterise ``tree_cls`` over ``pointer_type`` if it is generic. 

197 

198 Some `ArchiveTree` subclasses (e.g. ``SumFieldSerializationModel``) 

199 take no type parameters; their ``_get_archive_tree_type`` returns 

200 the class itself. Match that behaviour here so per-backend 

201 ``open_tree`` implementations can call this uniformly. 

202 

203 Parameters 

204 ---------- 

205 tree_cls 

206 Archive tree class to parameterise. 

207 pointer_type 

208 Pointer type to parameterise ``tree_cls`` over when it is generic. 

209 """ 

210 if not getattr(tree_cls, "__parameters__", ()): 

211 return tree_cls 

212 return tree_cls[pointer_type] # type: ignore[index] 

213 

214 

215def public_type_for_schema(schema_name: str) -> type | None: 

216 """Return the in-memory Python class produced when reading an archive 

217 whose top-level tree has schema name ``schema_name``. 

218 

219 Looks the schema name up in the registry and returns the registered 

220 tree's ``PUBLIC_TYPE`` ClassVar (the type its ``deserialize`` produces). 

221 Returns `None` when nothing is registered for ``schema_name``. 

222 

223 Parameters 

224 ---------- 

225 schema_name 

226 Schema name (e.g. ``"visit_image"``). 

227 """ 

228 tree_cls = class_for_schema(schema_name) 

229 if tree_cls is None: 

230 return None 

231 return getattr(tree_cls, "PUBLIC_TYPE", None) 

232 

233 

234@overload 

235def read_archive[T]( 

236 path: ResourcePathExpression | IO[bytes], cls: type[T], *, format: str | None = ..., **kwargs: Any 

237) -> T: ... 

238@overload 

239def read_archive( 239 ↛ exitline 239 didn't return from function 'read_archive' because

240 path: ResourcePathExpression | IO[bytes], cls: None = ..., *, format: str | None = ..., **kwargs: Any 

241) -> Any: ... 

242def read_archive( 

243 path: ResourcePathExpression | IO[bytes], 

244 cls: type[Any] | None = None, 

245 *, 

246 format: str | None = None, 

247 **kwargs: Any, 

248) -> Any: 

249 """Read an archive whose in-memory type is inferred from its schema. 

250 

251 Dispatches to the appropriate backend based on ``path``'s extension (or, 

252 for stream input, its leading bytes), resolves the registered in-memory 

253 type from the file's schema, and returns the fully deserialized object. 

254 Schema-version compatibility is enforced when the model validates the 

255 on-disk tree, via ``min_read_version``. 

256 A path with a ``.gz``/``.zst`` compression suffix is decompressed 

257 transparently; stream input must already be decompressed. 

258 

259 This is the convenient way to read a whole object. To read individual 

260 components, or to reach the metadata and butler info stored alongside the 

261 object, use `open_archive` instead. 

262 

263 Parameters 

264 ---------- 

265 path 

266 File to read; convertible to `lsst.resources.ResourcePath`, or a 

267 seekable binary stream containing the file's content (e.g. 

268 ``io.BytesIO(data)`` for in-memory bytes). 

269 cls 

270 Optional expected in-memory type. 

271 When given, the file's schema is checked against ``cls`` and the 

272 deserialized object is validated with ``isinstance`` (raising 

273 `TypeError` otherwise), and the static return type is ``T``. 

274 format 

275 Optional backend name (``"fits"``, ``"ndf"``, or ``"json"``) 

276 forcing the backend, instead of dispatching on the path's extension 

277 or the stream's leading bytes. 

278 **kwargs 

279 Type-specific keyword arguments forwarded to the object's 

280 ``deserialize`` (e.g. ``bbox`` for an image subset read). 

281 Mis-targeted arguments surface as ``TypeError``. 

282 Backend-specific open options (e.g. ``page_size``) are not accepted 

283 here; use `open_archive` for those. 

284 

285 Returns 

286 ------- 

287 object 

288 The deserialized object. 

289 

290 Raises 

291 ------ 

292 ValueError 

293 Raised by `backend_for_path` if the file extension is not 

294 recognized, by `backend_for_stream` if a stream's leading bytes are 

295 not recognized, or by `backend_for_name` if ``format`` is not a 

296 known backend name. 

297 ArchiveReadError 

298 Raised when the file's ``schema_name`` is not registered, or 

299 propagated from the model's ``min_read_version`` check on 

300 ``model_validate*``. 

301 TypeError 

302 Raised when ``cls`` is given and the file's schema or the 

303 deserialized object is not compatible with it. 

304 """ 

305 # Imported here to break the _io <-> _reader import cycle: _reader imports 

306 # class_for_schema / public_type_for_schema from this module at load time. 

307 from ._reader import open_archive 

308 

309 # A subset read (any deserialize kwarg with a value) reads incrementally; 

310 # a plain whole-object read may slurp the file up front. This mirrors the 

311 # ``partial`` default the per-backend readers used. 

312 partial = any(value is not None for value in kwargs.values()) 

313 with open_archive(path, cls, format=format, partial=partial) as reader: 

314 return reader.read(**kwargs) 

315 

316 

317def write_archive(obj: Any, path: Path | str, **kwargs: Any) -> Any: 

318 """Write ``obj`` to ``path``, dispatching by file extension. 

319 

320 Forwards ``**kwargs`` to the per-backend ``write`` (e.g. 

321 ``compression_options`` for FITS). No registry lookup is performed: 

322 the per-backend ``write`` already accepts any object with a 

323 ``serialize`` method. 

324 

325 Parameters 

326 ---------- 

327 obj 

328 Object to write; must implement ``serialize`` like the per-backend 

329 write functions expect. 

330 path 

331 Destination path. The extension selects the backend. 

332 **kwargs 

333 Forwarded verbatim to the backend's ``write``. 

334 

335 Returns 

336 ------- 

337 Any 

338 Whatever the per-backend ``write`` returns (the serialised 

339 archive tree). 

340 """ 

341 return backend_for_path(path).write(obj, path, **kwargs)