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

87 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-06-25 08:25 +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 if not getattr(tree_cls, "__parameters__", ()): 

198 return tree_cls 

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

200 

201 

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

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

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

205 

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

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

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

209 

210 Parameters 

211 ---------- 

212 schema_name 

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

214 """ 

215 tree_cls = class_for_schema(schema_name) 

216 if tree_cls is None: 

217 return None 

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

219 

220 

221@overload 

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

223@overload 

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

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

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

227 

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

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

230 returns the fully deserialized object. 

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

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

233 

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

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

236 object, use `open` instead. 

237 

238 Parameters 

239 ---------- 

240 path 

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

242 cls 

243 Optional expected in-memory type. 

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

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

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

247 **kwargs 

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

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

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

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

252 here; use `open` for those. 

253 

254 Returns 

255 ------- 

256 object 

257 The deserialized object. 

258 

259 Raises 

260 ------ 

261 ValueError 

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

263 ArchiveReadError 

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

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

266 ``model_validate*``. 

267 TypeError 

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

269 deserialized object is not compatible with it. 

270 """ 

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

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

273 from ._reader import open as open_archive 

274 

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

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

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

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

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

280 return reader.read(**kwargs) 

281 

282 

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

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

285 

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

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

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

289 ``serialize`` method. 

290 

291 Parameters 

292 ---------- 

293 obj 

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

295 write functions expect. 

296 path 

297 Destination path. The extension selects the backend. 

298 **kwargs 

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

300 

301 Returns 

302 ------- 

303 Any 

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

305 archive tree). 

306 """ 

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