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

87 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-06-29 22:40 +0000

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`` / ``write`` dispatchers and the schema-name registry.""" 

12 

13from __future__ import annotations 

14 

15__all__ = ( 

16 "class_for_schema", 

17 "parameterize_tree", 

18 "public_type_for_schema", 

19 "read", 

20 "register_schema_class", 

21 "tree_class_for_info", 

22 "write", 

23) 

24 

25import importlib 

26import importlib.metadata 

27from typing import TYPE_CHECKING, Any, overload 

28 

29from lsst.resources import ResourcePathExpression 

30 

31from ._backends import backend_for_path 

32from ._common import ArchiveReadError, ArchiveTree 

33 

34if TYPE_CHECKING: 

35 from ._input_archive import ArchiveInfo 

36 

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

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

39 

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

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

42``min_read_version``. 

43""" 

44 

45_SCHEMA_ENTRY_POINT_GROUP = "lsst.images.schemas" 

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

47 

48_BUILTIN_SCHEMA_PROVIDERS: dict[str, str] = { 

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

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

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

52} 

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

54 

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

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

57an installed distribution with entry point metadata. 

58 

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

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

61hooks register them before this lazy path is needed. 

62""" 

63 

64 

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

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

67 

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

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

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

71 

72 Parameters 

73 ---------- 

74 schema_name 

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

76 """ 

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

78 return cls 

79 _load_builtin_schema_provider(schema_name) 

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

81 return cls 

82 _load_schema_entry_points(schema_name) 

83 return _REGISTRY.get(schema_name) 

84 

85 

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

87 """Register ``cls`` under ``cls.SCHEMA_NAME``. 

88 

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

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

91 registered under an existing name. 

92 

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

94 not part of the public API. 

95 """ 

96 key = cls.SCHEMA_NAME 

97 existing = _REGISTRY.get(key) 

98 if existing is cls: 

99 return 

100 if existing is not None: 

101 raise RuntimeError( 

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

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

104 f"{cls.__qualname__}." 

105 ) 

106 _REGISTRY[key] = cls 

107 

108 

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

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

111 provider = _BUILTIN_SCHEMA_PROVIDERS.get(schema_name) 

112 if provider is None: 

113 return 

114 try: 

115 obj = _load_provider_object(provider) 

116 except Exception as err: 

117 raise ArchiveReadError( 

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

119 ) from err 

120 _register_provider_object(obj) 

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

122 raise ArchiveReadError( 

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

124 ) 

125 

126 

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

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

129 loaded: list[str] = [] 

130 for entry_point in importlib.metadata.entry_points( 

131 group=_SCHEMA_ENTRY_POINT_GROUP, 

132 name=schema_name, 

133 ): 

134 loaded.append(entry_point.value) 

135 try: 

136 obj = entry_point.load() 

137 except Exception as err: 

138 raise ArchiveReadError( 

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

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

141 ) from err 

142 _register_provider_object(obj) 

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

144 raise ArchiveReadError( 

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

146 ) 

147 

148 

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

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

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

152 obj: object = importlib.import_module(module_name) 

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

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

155 obj = getattr(obj, attr) 

156 return obj 

157 

158 

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

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

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

162 register_schema_class(obj) 

163 

164 

165def tree_class_for_info(info: ArchiveInfo, path: ResourcePathExpression) -> type[ArchiveTree]: 

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

167 

168 Parameters 

169 ---------- 

170 info 

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

172 path 

173 Path being opened, used only for the error message. 

174 

175 Raises 

176 ------ 

177 ArchiveReadError 

178 If no class is registered for the schema. 

179 """ 

180 tree_cls = class_for_schema(info.schema_name) 

181 if tree_cls is None: 

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

183 return tree_cls 

184 

185 

186def parameterize_tree( 

187 tree_cls: type[ArchiveTree], 

188 pointer_type: type[Any], 

189) -> type[ArchiveTree]: 

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

191 

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

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

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

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

196 

197 Parameters 

198 ---------- 

199 tree_cls 

200 Archive tree class to parameterise. 

201 pointer_type 

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

203 """ 

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

205 return tree_cls 

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

207 

208 

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

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

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

212 

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

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

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

216 

217 Parameters 

218 ---------- 

219 schema_name 

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

221 """ 

222 tree_cls = class_for_schema(schema_name) 

223 if tree_cls is None: 

224 return None 

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

226 

227 

228@overload 

229def read[T](path: ResourcePathExpression, cls: type[T], **kwargs: Any) -> T: ... 

230@overload 

231def read(path: ResourcePathExpression, cls: None = ..., **kwargs: Any) -> Any: ... 231 ↛ exitline 231 didn't return from function 'read' because

232def read(path: ResourcePathExpression, cls: type[Any] | None = None, **kwargs: Any) -> Any: 

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

234 

235 Dispatches to the appropriate backend based on ``path``'s extension, 

236 resolves the registered in-memory type from the file's schema, and 

237 returns the fully deserialized object. 

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

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

240 

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

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

243 object, use `open` instead. 

244 

245 Parameters 

246 ---------- 

247 path 

248 File to read; convertible to `lsst.resources.ResourcePath`. 

249 cls 

250 Optional expected in-memory type. 

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

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

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

254 **kwargs 

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

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

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

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

259 here; use `open` for those. 

260 

261 Returns 

262 ------- 

263 object 

264 The deserialized object. 

265 

266 Raises 

267 ------ 

268 ValueError 

269 Raised by `backend_for_path` if the file extension is not recognized. 

270 ArchiveReadError 

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

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

273 ``model_validate*``. 

274 TypeError 

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

276 deserialized object is not compatible with it. 

277 """ 

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

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

280 from ._reader import open as open_archive 

281 

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

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

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

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

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

287 return reader.read(**kwargs) 

288 

289 

290def write(obj: Any, path: str, **kwargs: Any) -> Any: 

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

292 

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

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

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

296 ``serialize`` method. 

297 

298 Parameters 

299 ---------- 

300 obj 

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

302 write functions expect. 

303 path 

304 Destination path. The extension selects the backend. 

305 **kwargs 

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

307 

308 Returns 

309 ------- 

310 Any 

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

312 archive tree). 

313 """ 

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