Coverage for python/lsst/daf/butler/core/datastore.py: 51%

209 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 02:10 -0700

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <http://www.gnu.org/licenses/>. 

21 

22"""Support for generic data stores.""" 

23 

24from __future__ import annotations 

25 

26__all__ = ("DatastoreConfig", "Datastore", "DatastoreValidationError", "DatasetRefURIs") 

27 

28import contextlib 

29import dataclasses 

30import logging 

31from abc import ABCMeta, abstractmethod 

32from collections import abc, defaultdict 

33from typing import ( 

34 TYPE_CHECKING, 

35 Any, 

36 Callable, 

37 ClassVar, 

38 Dict, 

39 Iterable, 

40 Iterator, 

41 List, 

42 Mapping, 

43 Optional, 

44 Set, 

45 Tuple, 

46 Type, 

47 Union, 

48) 

49 

50from lsst.utils import doImportType 

51 

52from .config import Config, ConfigSubset 

53from .constraints import Constraints 

54from .exceptions import DatasetTypeNotSupportedError, ValidationError 

55from .fileDataset import FileDataset 

56from .storageClass import StorageClassFactory 

57 

58if TYPE_CHECKING: 

59 from lsst.resources import ResourcePath, ResourcePathExpression 

60 

61 from ..registry.interfaces import DatasetIdRef, DatastoreRegistryBridgeManager 

62 from .configSupport import LookupKey 

63 from .datasets import DatasetRef, DatasetType 

64 from .datastoreRecordData import DatastoreRecordData 

65 from .storageClass import StorageClass 

66 

67 

68class DatastoreConfig(ConfigSubset): 

69 """Configuration for Datastores.""" 

70 

71 component = "datastore" 

72 requiredKeys = ("cls",) 

73 defaultConfigFile = "datastore.yaml" 

74 

75 

76class DatastoreValidationError(ValidationError): 

77 """There is a problem with the Datastore configuration.""" 

78 

79 pass 

80 

81 

82@dataclasses.dataclass(frozen=True) 

83class Event: 

84 __slots__ = {"name", "undoFunc", "args", "kwargs"} 

85 name: str 

86 undoFunc: Callable 

87 args: tuple 

88 kwargs: dict 

89 

90 

91class IngestPrepData: 

92 """A helper base class for `Datastore` ingest implementations. 

93 

94 Datastore implementations will generally need a custom implementation of 

95 this class. 

96 

97 Should be accessed as ``Datastore.IngestPrepData`` instead of via direct 

98 import. 

99 

100 Parameters 

101 ---------- 

102 refs : iterable of `DatasetRef` 

103 References for the datasets that can be ingested by this datastore. 

104 """ 

105 

106 def __init__(self, refs: Iterable[DatasetRef]): 

107 self.refs = {ref.id: ref for ref in refs} 

108 

109 

110class DatastoreTransaction: 

111 """Keeps a log of `Datastore` activity and allow rollback. 

112 

113 Parameters 

114 ---------- 

115 parent : `DatastoreTransaction`, optional 

116 The parent transaction (if any) 

117 """ 

118 

119 Event: ClassVar[Type] = Event 

120 

121 parent: Optional[DatastoreTransaction] 

122 """The parent transaction. (`DatastoreTransaction`, optional)""" 

123 

124 def __init__(self, parent: Optional[DatastoreTransaction] = None): 

125 self.parent = parent 

126 self._log: List[Event] = [] 

127 

128 def registerUndo(self, name: str, undoFunc: Callable, *args: Any, **kwargs: Any) -> None: 

129 """Register event with undo function. 

130 

131 Parameters 

132 ---------- 

133 name : `str` 

134 Name of the event. 

135 undoFunc : func 

136 Function to undo this event. 

137 args : `tuple` 

138 Positional arguments to `undoFunc`. 

139 **kwargs 

140 Keyword arguments to `undoFunc`. 

141 """ 

142 self._log.append(self.Event(name, undoFunc, args, kwargs)) 

143 

144 @contextlib.contextmanager 

145 def undoWith(self, name: str, undoFunc: Callable, *args: Any, **kwargs: Any) -> Iterator[None]: 

146 """Register undo function if nested operation succeeds. 

147 

148 Calls `registerUndo`. 

149 

150 This can be used to wrap individual undo-able statements within a 

151 DatastoreTransaction block. Multiple statements that can fail 

152 separately should not be part of the same `undoWith` block. 

153 

154 All arguments are forwarded directly to `registerUndo`. 

155 """ 

156 try: 

157 yield None 

158 except BaseException: 

159 raise 

160 else: 

161 self.registerUndo(name, undoFunc, *args, **kwargs) 

162 

163 def rollback(self) -> None: 

164 """Roll back all events in this transaction.""" 

165 log = logging.getLogger(__name__) 

166 while self._log: 

167 ev = self._log.pop() 

168 try: 

169 log.debug( 

170 "Rolling back transaction: %s: %s(%s,%s)", 

171 ev.name, 

172 ev.undoFunc, 

173 ",".join(str(a) for a in ev.args), 

174 ",".join(f"{k}={v}" for k, v in ev.kwargs.items()), 

175 ) 

176 except Exception: 

177 # In case we had a problem in stringification of arguments 

178 log.warning("Rolling back transaction: %s", ev.name) 

179 try: 

180 ev.undoFunc(*ev.args, **ev.kwargs) 

181 except BaseException as e: 

182 # Deliberately swallow error that may occur in unrolling 

183 log.warning("Exception: %s caught while unrolling: %s", e, ev.name) 

184 pass 

185 

186 def commit(self) -> None: 

187 """Commit this transaction.""" 

188 if self.parent is None: 

189 # Just forget about the events, they have already happened. 

190 return 

191 else: 

192 # We may still want to events from this transaction as part of 

193 # the parent. 

194 self.parent._log.extend(self._log) 

195 

196 

197@dataclasses.dataclass 

198class DatasetRefURIs(abc.Sequence): 

199 """Represents the primary and component ResourcePath(s) associated with a 

200 DatasetRef. 

201 

202 This is used in places where its members used to be represented as a tuple 

203 `(primaryURI, componentURIs)`. To maintain backward compatibility this 

204 inherits from Sequence and so instances can be treated as a two-item 

205 tuple. 

206 """ 

207 

208 def __init__( 

209 self, 

210 primaryURI: Optional[ResourcePath] = None, 

211 componentURIs: Optional[Dict[str, ResourcePath]] = None, 

212 ): 

213 self.primaryURI = primaryURI 

214 """The URI to the primary artifact associated with this dataset. If the 

215 dataset was disassembled within the datastore this may be `None`. 

216 """ 

217 

218 self.componentURIs = componentURIs or {} 

219 """The URIs to any components associated with the dataset artifact 

220 indexed by component name. This can be empty if there are no 

221 components. 

222 """ 

223 

224 def __getitem__(self, index: Any) -> Any: 

225 """Get primaryURI and componentURIs by index. 

226 

227 Provides support for tuple-like access. 

228 """ 

229 if index == 0: 

230 return self.primaryURI 

231 elif index == 1: 

232 return self.componentURIs 

233 raise IndexError("list index out of range") 

234 

235 def __len__(self) -> int: 

236 """Get the number of data members. 

237 

238 Provides support for tuple-like access. 

239 """ 

240 return 2 

241 

242 def __repr__(self) -> str: 

243 return f"DatasetRefURIs({repr(self.primaryURI)}, {repr(self.componentURIs)})" 

244 

245 

246class Datastore(metaclass=ABCMeta): 

247 """Datastore interface. 

248 

249 Parameters 

250 ---------- 

251 config : `DatastoreConfig` or `str` 

252 Load configuration either from an existing config instance or by 

253 referring to a configuration file. 

254 bridgeManager : `DatastoreRegistryBridgeManager` 

255 Object that manages the interface between `Registry` and datastores. 

256 butlerRoot : `str`, optional 

257 New datastore root to use to override the configuration value. 

258 """ 

259 

260 defaultConfigFile: ClassVar[Optional[str]] = None 

261 """Path to configuration defaults. Accessed within the ``config`` resource 

262 or relative to a search path. Can be None if no defaults specified. 

263 """ 

264 

265 containerKey: ClassVar[Optional[str]] = None 

266 """Name of the key containing a list of subconfigurations that also 

267 need to be merged with defaults and will likely use different Python 

268 datastore classes (but all using DatastoreConfig). Assumed to be a 

269 list of configurations that can be represented in a DatastoreConfig 

270 and containing a "cls" definition. None indicates that no containers 

271 are expected in this Datastore.""" 

272 

273 isEphemeral: bool = False 

274 """Indicate whether this Datastore is ephemeral or not. An ephemeral 

275 datastore is one where the contents of the datastore will not exist 

276 across process restarts. This value can change per-instance.""" 

277 

278 config: DatastoreConfig 

279 """Configuration used to create Datastore.""" 

280 

281 name: str 

282 """Label associated with this Datastore.""" 

283 

284 storageClassFactory: StorageClassFactory 

285 """Factory for creating storage class instances from name.""" 

286 

287 constraints: Constraints 

288 """Constraints to apply when putting datasets into the datastore.""" 

289 

290 # MyPy does not like for this to be annotated as any kind of type, because 

291 # it can't do static checking on type variables that can change at runtime. 

292 IngestPrepData: ClassVar[Any] = IngestPrepData 

293 """Helper base class for ingest implementations. 

294 """ 

295 

296 @classmethod 

297 @abstractmethod 

298 def setConfigRoot(cls, root: str, config: Config, full: Config, overwrite: bool = True) -> None: 

299 """Set filesystem-dependent config options for this datastore. 

300 

301 The options will be appropriate for a new empty repository with the 

302 given root. 

303 

304 Parameters 

305 ---------- 

306 root : `str` 

307 Filesystem path to the root of the data repository. 

308 config : `Config` 

309 A `Config` to update. Only the subset understood by 

310 this component will be updated. Will not expand 

311 defaults. 

312 full : `Config` 

313 A complete config with all defaults expanded that can be 

314 converted to a `DatastoreConfig`. Read-only and will not be 

315 modified by this method. 

316 Repository-specific options that should not be obtained 

317 from defaults when Butler instances are constructed 

318 should be copied from ``full`` to ``config``. 

319 overwrite : `bool`, optional 

320 If `False`, do not modify a value in ``config`` if the value 

321 already exists. Default is always to overwrite with the provided 

322 ``root``. 

323 

324 Notes 

325 ----- 

326 If a keyword is explicitly defined in the supplied ``config`` it 

327 will not be overridden by this method if ``overwrite`` is `False`. 

328 This allows explicit values set in external configs to be retained. 

329 """ 

330 raise NotImplementedError() 

331 

332 @staticmethod 

333 def fromConfig( 

334 config: Config, 

335 bridgeManager: DatastoreRegistryBridgeManager, 

336 butlerRoot: Optional[ResourcePathExpression] = None, 

337 ) -> "Datastore": 

338 """Create datastore from type specified in config file. 

339 

340 Parameters 

341 ---------- 

342 config : `Config` 

343 Configuration instance. 

344 bridgeManager : `DatastoreRegistryBridgeManager` 

345 Object that manages the interface between `Registry` and 

346 datastores. 

347 butlerRoot : `str`, optional 

348 Butler root directory. 

349 """ 

350 cls = doImportType(config["datastore", "cls"]) 

351 if not issubclass(cls, Datastore): 

352 raise TypeError(f"Imported child class {config['datastore', 'cls']} is not a Datastore") 

353 return cls(config=config, bridgeManager=bridgeManager, butlerRoot=butlerRoot) 

354 

355 def __init__( 

356 self, 

357 config: Union[Config, str], 

358 bridgeManager: DatastoreRegistryBridgeManager, 

359 butlerRoot: Optional[ResourcePathExpression] = None, 

360 ): 

361 self.config = DatastoreConfig(config) 

362 self.name = "ABCDataStore" 

363 self._transaction: Optional[DatastoreTransaction] = None 

364 

365 # All Datastores need storage classes and constraints 

366 self.storageClassFactory = StorageClassFactory() 

367 

368 # And read the constraints list 

369 constraintsConfig = self.config.get("constraints") 

370 self.constraints = Constraints(constraintsConfig, universe=bridgeManager.universe) 

371 

372 def __str__(self) -> str: 

373 return self.name 

374 

375 def __repr__(self) -> str: 

376 return self.name 

377 

378 @property 

379 def names(self) -> Tuple[str, ...]: 

380 """Names associated with this datastore returned as a list. 

381 

382 Can be different to ``name`` for a chaining datastore. 

383 """ 

384 # Default implementation returns solely the name itself 

385 return (self.name,) 

386 

387 @contextlib.contextmanager 

388 def transaction(self) -> Iterator[DatastoreTransaction]: 

389 """Context manager supporting `Datastore` transactions. 

390 

391 Transactions can be nested, and are to be used in combination with 

392 `Registry.transaction`. 

393 """ 

394 self._transaction = DatastoreTransaction(self._transaction) 

395 try: 

396 yield self._transaction 

397 except BaseException: 

398 self._transaction.rollback() 

399 raise 

400 else: 

401 self._transaction.commit() 

402 self._transaction = self._transaction.parent 

403 

404 @abstractmethod 

405 def knows(self, ref: DatasetRef) -> bool: 

406 """Check if the dataset is known to the datastore. 

407 

408 Does not check for existence of any artifact. 

409 

410 Parameters 

411 ---------- 

412 ref : `DatasetRef` 

413 Reference to the required dataset. 

414 

415 Returns 

416 ------- 

417 exists : `bool` 

418 `True` if the dataset is known to the datastore. 

419 """ 

420 raise NotImplementedError() 

421 

422 def knows_these(self, refs: Iterable[DatasetRef]) -> dict[DatasetRef, bool]: 

423 """Check which of the given datasets are known to this datastore. 

424 

425 This is like ``mexist()`` but does not check that the file exists. 

426 

427 Parameters 

428 ---------- 

429 refs : iterable `DatasetRef` 

430 The datasets to check. 

431 

432 Returns 

433 ------- 

434 exists : `dict`[`DatasetRef`, `bool`] 

435 Mapping of dataset to boolean indicating whether the dataset 

436 is known to the datastore. 

437 """ 

438 # Non-optimized default calls knows() repeatedly. 

439 return {ref: self.knows(ref) for ref in refs} 

440 

441 def mexists( 

442 self, refs: Iterable[DatasetRef], artifact_existence: Optional[Dict[ResourcePath, bool]] = None 

443 ) -> Dict[DatasetRef, bool]: 

444 """Check the existence of multiple datasets at once. 

445 

446 Parameters 

447 ---------- 

448 refs : iterable of `DatasetRef` 

449 The datasets to be checked. 

450 artifact_existence : `dict` [`lsst.resources.ResourcePath`, `bool`] 

451 Optional mapping of datastore artifact to existence. Updated by 

452 this method with details of all artifacts tested. Can be `None` 

453 if the caller is not interested. 

454 

455 Returns 

456 ------- 

457 existence : `dict` of [`DatasetRef`, `bool`] 

458 Mapping from dataset to boolean indicating existence. 

459 """ 

460 existence: Dict[DatasetRef, bool] = {} 

461 # Non-optimized default. 

462 for ref in refs: 

463 existence[ref] = self.exists(ref) 

464 return existence 

465 

466 @abstractmethod 

467 def exists(self, datasetRef: DatasetRef) -> bool: 

468 """Check if the dataset exists in the datastore. 

469 

470 Parameters 

471 ---------- 

472 datasetRef : `DatasetRef` 

473 Reference to the required dataset. 

474 

475 Returns 

476 ------- 

477 exists : `bool` 

478 `True` if the entity exists in the `Datastore`. 

479 """ 

480 raise NotImplementedError("Must be implemented by subclass") 

481 

482 @abstractmethod 

483 def get( 

484 self, 

485 datasetRef: DatasetRef, 

486 parameters: Mapping[str, Any] | None = None, 

487 storageClass: Optional[Union[StorageClass, str]] = None, 

488 ) -> Any: 

489 """Load an `InMemoryDataset` from the store. 

490 

491 Parameters 

492 ---------- 

493 datasetRef : `DatasetRef` 

494 Reference to the required Dataset. 

495 parameters : `dict` 

496 `StorageClass`-specific parameters that specify a slice of the 

497 Dataset to be loaded. 

498 storageClass : `StorageClass` or `str`, optional 

499 The storage class to be used to override the Python type 

500 returned by this method. By default the returned type matches 

501 the dataset type definition for this dataset. Specifying a 

502 read `StorageClass` can force a different type to be returned. 

503 This type must be compatible with the original type. 

504 

505 Returns 

506 ------- 

507 inMemoryDataset : `object` 

508 Requested Dataset or slice thereof as an InMemoryDataset. 

509 """ 

510 raise NotImplementedError("Must be implemented by subclass") 

511 

512 @abstractmethod 

513 def put(self, inMemoryDataset: Any, datasetRef: DatasetRef) -> None: 

514 """Write a `InMemoryDataset` with a given `DatasetRef` to the store. 

515 

516 Parameters 

517 ---------- 

518 inMemoryDataset : `object` 

519 The Dataset to store. 

520 datasetRef : `DatasetRef` 

521 Reference to the associated Dataset. 

522 """ 

523 raise NotImplementedError("Must be implemented by subclass") 

524 

525 def _overrideTransferMode(self, *datasets: FileDataset, transfer: Optional[str] = None) -> Optional[str]: 

526 """Allow ingest transfer mode to be defaulted based on datasets. 

527 

528 Parameters 

529 ---------- 

530 datasets : `FileDataset` 

531 Each positional argument is a struct containing information about 

532 a file to be ingested, including its path (either absolute or 

533 relative to the datastore root, if applicable), a complete 

534 `DatasetRef` (with ``dataset_id not None``), and optionally a 

535 formatter class or its fully-qualified string name. If a formatter 

536 is not provided, this method should populate that attribute with 

537 the formatter the datastore would use for `put`. Subclasses are 

538 also permitted to modify the path attribute (typically to put it 

539 in what the datastore considers its standard form). 

540 transfer : `str`, optional 

541 How (and whether) the dataset should be added to the datastore. 

542 See `ingest` for details of transfer modes. 

543 

544 Returns 

545 ------- 

546 newTransfer : `str` 

547 Transfer mode to use. Will be identical to the supplied transfer 

548 mode unless "auto" is used. 

549 """ 

550 if transfer != "auto": 

551 return transfer 

552 raise RuntimeError(f"{transfer} is not allowed without specialization.") 

553 

554 def _prepIngest(self, *datasets: FileDataset, transfer: Optional[str] = None) -> IngestPrepData: 

555 """Process datasets to identify which ones can be ingested. 

556 

557 Parameters 

558 ---------- 

559 datasets : `FileDataset` 

560 Each positional argument is a struct containing information about 

561 a file to be ingested, including its path (either absolute or 

562 relative to the datastore root, if applicable), a complete 

563 `DatasetRef` (with ``dataset_id not None``), and optionally a 

564 formatter class or its fully-qualified string name. If a formatter 

565 is not provided, this method should populate that attribute with 

566 the formatter the datastore would use for `put`. Subclasses are 

567 also permitted to modify the path attribute (typically to put it 

568 in what the datastore considers its standard form). 

569 transfer : `str`, optional 

570 How (and whether) the dataset should be added to the datastore. 

571 See `ingest` for details of transfer modes. 

572 

573 Returns 

574 ------- 

575 data : `IngestPrepData` 

576 An instance of a subclass of `IngestPrepData`, used to pass 

577 arbitrary data from `_prepIngest` to `_finishIngest`. This should 

578 include only the datasets this datastore can actually ingest; 

579 others should be silently ignored (`Datastore.ingest` will inspect 

580 `IngestPrepData.refs` and raise `DatasetTypeNotSupportedError` if 

581 necessary). 

582 

583 Raises 

584 ------ 

585 NotImplementedError 

586 Raised if the datastore does not support the given transfer mode 

587 (including the case where ingest is not supported at all). 

588 FileNotFoundError 

589 Raised if one of the given files does not exist. 

590 FileExistsError 

591 Raised if transfer is not `None` but the (internal) location the 

592 file would be moved to is already occupied. 

593 

594 Notes 

595 ----- 

596 This method (along with `_finishIngest`) should be implemented by 

597 subclasses to provide ingest support instead of implementing `ingest` 

598 directly. 

599 

600 `_prepIngest` should not modify the data repository or given files in 

601 any way; all changes should be deferred to `_finishIngest`. 

602 

603 When possible, exceptions should be raised in `_prepIngest` instead of 

604 `_finishIngest`. `NotImplementedError` exceptions that indicate that 

605 the transfer mode is not supported must be raised by `_prepIngest` 

606 instead of `_finishIngest`. 

607 """ 

608 raise NotImplementedError(f"Datastore {self} does not support direct file-based ingest.") 

609 

610 def _finishIngest( 

611 self, prepData: IngestPrepData, *, transfer: Optional[str] = None, record_validation_info: bool = True 

612 ) -> None: 

613 """Complete an ingest operation. 

614 

615 Parameters 

616 ---------- 

617 data : `IngestPrepData` 

618 An instance of a subclass of `IngestPrepData`. Guaranteed to be 

619 the direct result of a call to `_prepIngest` on this datastore. 

620 transfer : `str`, optional 

621 How (and whether) the dataset should be added to the datastore. 

622 See `ingest` for details of transfer modes. 

623 record_validation_info : `bool`, optional 

624 If `True`, the default, the datastore can record validation 

625 information associated with the file. If `False` the datastore 

626 will not attempt to track any information such as checksums 

627 or file sizes. This can be useful if such information is tracked 

628 in an external system or if the file is to be compressed in place. 

629 It is up to the datastore whether this parameter is relevant. 

630 

631 Raises 

632 ------ 

633 FileNotFoundError 

634 Raised if one of the given files does not exist. 

635 FileExistsError 

636 Raised if transfer is not `None` but the (internal) location the 

637 file would be moved to is already occupied. 

638 

639 Notes 

640 ----- 

641 This method (along with `_prepIngest`) should be implemented by 

642 subclasses to provide ingest support instead of implementing `ingest` 

643 directly. 

644 """ 

645 raise NotImplementedError(f"Datastore {self} does not support direct file-based ingest.") 

646 

647 def ingest( 

648 self, *datasets: FileDataset, transfer: Optional[str] = None, record_validation_info: bool = True 

649 ) -> None: 

650 """Ingest one or more files into the datastore. 

651 

652 Parameters 

653 ---------- 

654 datasets : `FileDataset` 

655 Each positional argument is a struct containing information about 

656 a file to be ingested, including its path (either absolute or 

657 relative to the datastore root, if applicable), a complete 

658 `DatasetRef` (with ``dataset_id not None``), and optionally a 

659 formatter class or its fully-qualified string name. If a formatter 

660 is not provided, the one the datastore would use for ``put`` on 

661 that dataset is assumed. 

662 transfer : `str`, optional 

663 How (and whether) the dataset should be added to the datastore. 

664 If `None` (default), the file must already be in a location 

665 appropriate for the datastore (e.g. within its root directory), 

666 and will not be modified. Other choices include "move", "copy", 

667 "link", "symlink", "relsymlink", and "hardlink". "link" is a 

668 special transfer mode that will first try to make a hardlink and 

669 if that fails a symlink will be used instead. "relsymlink" creates 

670 a relative symlink rather than use an absolute path. 

671 Most datastores do not support all transfer modes. 

672 "auto" is a special option that will let the 

673 data store choose the most natural option for itself. 

674 record_validation_info : `bool`, optional 

675 If `True`, the default, the datastore can record validation 

676 information associated with the file. If `False` the datastore 

677 will not attempt to track any information such as checksums 

678 or file sizes. This can be useful if such information is tracked 

679 in an external system or if the file is to be compressed in place. 

680 It is up to the datastore whether this parameter is relevant. 

681 

682 Raises 

683 ------ 

684 NotImplementedError 

685 Raised if the datastore does not support the given transfer mode 

686 (including the case where ingest is not supported at all). 

687 DatasetTypeNotSupportedError 

688 Raised if one or more files to be ingested have a dataset type that 

689 is not supported by the datastore. 

690 FileNotFoundError 

691 Raised if one of the given files does not exist. 

692 FileExistsError 

693 Raised if transfer is not `None` but the (internal) location the 

694 file would be moved to is already occupied. 

695 

696 Notes 

697 ----- 

698 Subclasses should implement `_prepIngest` and `_finishIngest` instead 

699 of implementing `ingest` directly. Datastores that hold and 

700 delegate to child datastores may want to call those methods as well. 

701 

702 Subclasses are encouraged to document their supported transfer modes 

703 in their class documentation. 

704 """ 

705 # Allow a datastore to select a default transfer mode 

706 transfer = self._overrideTransferMode(*datasets, transfer=transfer) 

707 prepData = self._prepIngest(*datasets, transfer=transfer) 

708 refs = {ref.id: ref for dataset in datasets for ref in dataset.refs} 

709 if refs.keys() != prepData.refs.keys(): 

710 unsupported = refs.keys() - prepData.refs.keys() 

711 # Group unsupported refs by DatasetType for an informative 

712 # but still concise error message. 

713 byDatasetType = defaultdict(list) 

714 for datasetId in unsupported: 

715 ref = refs[datasetId] 

716 byDatasetType[ref.datasetType].append(ref) 

717 raise DatasetTypeNotSupportedError( 

718 "DatasetType(s) not supported in ingest: " 

719 + ", ".join(f"{k.name} ({len(v)} dataset(s))" for k, v in byDatasetType.items()) 

720 ) 

721 self._finishIngest(prepData, transfer=transfer, record_validation_info=record_validation_info) 

722 

723 def transfer_from( 

724 self, 

725 source_datastore: Datastore, 

726 refs: Iterable[DatasetRef], 

727 transfer: str = "auto", 

728 artifact_existence: Optional[Dict[ResourcePath, bool]] = None, 

729 ) -> tuple[set[DatasetRef], set[DatasetRef]]: 

730 """Transfer dataset artifacts from another datastore to this one. 

731 

732 Parameters 

733 ---------- 

734 source_datastore : `Datastore` 

735 The datastore from which to transfer artifacts. That datastore 

736 must be compatible with this datastore receiving the artifacts. 

737 refs : iterable of `DatasetRef` 

738 The datasets to transfer from the source datastore. 

739 transfer : `str`, optional 

740 How (and whether) the dataset should be added to the datastore. 

741 Choices include "move", "copy", 

742 "link", "symlink", "relsymlink", and "hardlink". "link" is a 

743 special transfer mode that will first try to make a hardlink and 

744 if that fails a symlink will be used instead. "relsymlink" creates 

745 a relative symlink rather than use an absolute path. 

746 Most datastores do not support all transfer modes. 

747 "auto" (the default) is a special option that will let the 

748 data store choose the most natural option for itself. 

749 If the source location and transfer location are identical the 

750 transfer mode will be ignored. 

751 artifact_existence : `dict` [`lsst.resources.ResourcePath`, `bool`] 

752 Optional mapping of datastore artifact to existence. Updated by 

753 this method with details of all artifacts tested. Can be `None` 

754 if the caller is not interested. 

755 

756 Returns 

757 ------- 

758 accepted : `set` [`DatasetRef`] 

759 The datasets that were transferred. 

760 rejected : `set` [`DatasetRef`] 

761 The datasets that were rejected due to a constraints violation. 

762 

763 Raises 

764 ------ 

765 TypeError 

766 Raised if the two datastores are not compatible. 

767 """ 

768 if type(self) is not type(source_datastore): 

769 raise TypeError( 

770 f"Datastore mismatch between this datastore ({type(self)}) and the " 

771 f"source datastore ({type(source_datastore)})." 

772 ) 

773 

774 raise NotImplementedError(f"Datastore {type(self)} must implement a transfer_from method.") 

775 

776 def getManyURIs( 

777 self, 

778 refs: Iterable[DatasetRef], 

779 predict: bool = False, 

780 allow_missing: bool = False, 

781 ) -> Dict[DatasetRef, DatasetRefURIs]: 

782 """Return URIs associated with many datasets. 

783 

784 Parameters 

785 ---------- 

786 refs : iterable of `DatasetIdRef` 

787 References to the required datasets. 

788 predict : `bool`, optional 

789 If the datastore does not know about a dataset, should it 

790 return a predicted URI or not? 

791 allow_missing : `bool` 

792 If `False`, and `predict` is `False`, will raise if a `DatasetRef` 

793 does not exist. 

794 

795 Returns 

796 ------- 

797 URIs : `dict` of [`DatasetRef`, `DatasetRefUris`] 

798 A dict of primary and component URIs, indexed by the passed-in 

799 refs. 

800 

801 Raises 

802 ------ 

803 FileNotFoundError 

804 A URI has been requested for a dataset that does not exist and 

805 guessing is not allowed. 

806 

807 Notes 

808 ----- 

809 In file-based datastores, getManuURIs does not check that the file is 

810 really there, it's assuming it is if datastore is aware of the file 

811 then it actually exists. 

812 """ 

813 uris: Dict[DatasetRef, DatasetRefURIs] = {} 

814 missing_refs = [] 

815 for ref in refs: 

816 try: 

817 uris[ref] = self.getURIs(ref, predict=predict) 

818 except FileNotFoundError: 

819 missing_refs.append(ref) 

820 if missing_refs and not allow_missing: 

821 raise FileNotFoundError( 

822 "Missing {} refs from datastore out of {} and predict=False.".format( 

823 num_missing := len(missing_refs), num_missing + len(uris) 

824 ) 

825 ) 

826 return uris 

827 

828 @abstractmethod 

829 def getURIs(self, datasetRef: DatasetRef, predict: bool = False) -> DatasetRefURIs: 

830 """Return URIs associated with dataset. 

831 

832 Parameters 

833 ---------- 

834 ref : `DatasetRef` 

835 Reference to the required dataset. 

836 predict : `bool`, optional 

837 If the datastore does not know about the dataset, should it 

838 return a predicted URI or not? 

839 

840 Returns 

841 ------- 

842 uris : `DatasetRefURIs` 

843 The URI to the primary artifact associated with this dataset (if 

844 the dataset was disassembled within the datastore this may be 

845 `None`), and the URIs to any components associated with the dataset 

846 artifact. (can be empty if there are no components). 

847 """ 

848 raise NotImplementedError() 

849 

850 @abstractmethod 

851 def getURI(self, datasetRef: DatasetRef, predict: bool = False) -> ResourcePath: 

852 """URI to the Dataset. 

853 

854 Parameters 

855 ---------- 

856 datasetRef : `DatasetRef` 

857 Reference to the required Dataset. 

858 predict : `bool` 

859 If `True` attempt to predict the URI for a dataset if it does 

860 not exist in datastore. 

861 

862 Returns 

863 ------- 

864 uri : `str` 

865 URI string pointing to the Dataset within the datastore. If the 

866 Dataset does not exist in the datastore, the URI may be a guess. 

867 If the datastore does not have entities that relate well 

868 to the concept of a URI the returned URI string will be 

869 descriptive. The returned URI is not guaranteed to be obtainable. 

870 

871 Raises 

872 ------ 

873 FileNotFoundError 

874 A URI has been requested for a dataset that does not exist and 

875 guessing is not allowed. 

876 """ 

877 raise NotImplementedError("Must be implemented by subclass") 

878 

879 @abstractmethod 

880 def retrieveArtifacts( 

881 self, 

882 refs: Iterable[DatasetRef], 

883 destination: ResourcePath, 

884 transfer: str = "auto", 

885 preserve_path: bool = True, 

886 overwrite: bool = False, 

887 ) -> List[ResourcePath]: 

888 """Retrieve the artifacts associated with the supplied refs. 

889 

890 Parameters 

891 ---------- 

892 refs : iterable of `DatasetRef` 

893 The datasets for which artifacts are to be retrieved. 

894 A single ref can result in multiple artifacts. The refs must 

895 be resolved. 

896 destination : `lsst.resources.ResourcePath` 

897 Location to write the artifacts. 

898 transfer : `str`, optional 

899 Method to use to transfer the artifacts. Must be one of the options 

900 supported by `lsst.resources.ResourcePath.transfer_from()`. 

901 "move" is not allowed. 

902 preserve_path : `bool`, optional 

903 If `True` the full path of the artifact within the datastore 

904 is preserved. If `False` the final file component of the path 

905 is used. 

906 overwrite : `bool`, optional 

907 If `True` allow transfers to overwrite existing files at the 

908 destination. 

909 

910 Returns 

911 ------- 

912 targets : `list` of `lsst.resources.ResourcePath` 

913 URIs of file artifacts in destination location. Order is not 

914 preserved. 

915 

916 Notes 

917 ----- 

918 For non-file datastores the artifacts written to the destination 

919 may not match the representation inside the datastore. For example 

920 a hierarchichal data structure in a NoSQL database may well be stored 

921 as a JSON file. 

922 """ 

923 raise NotImplementedError() 

924 

925 @abstractmethod 

926 def remove(self, datasetRef: DatasetRef) -> None: 

927 """Indicate to the Datastore that a Dataset can be removed. 

928 

929 Parameters 

930 ---------- 

931 datasetRef : `DatasetRef` 

932 Reference to the required Dataset. 

933 

934 Raises 

935 ------ 

936 FileNotFoundError 

937 When Dataset does not exist. 

938 

939 Notes 

940 ----- 

941 Some Datastores may implement this method as a silent no-op to 

942 disable Dataset deletion through standard interfaces. 

943 """ 

944 raise NotImplementedError("Must be implemented by subclass") 

945 

946 @abstractmethod 

947 def forget(self, refs: Iterable[DatasetRef]) -> None: 

948 """Indicate to the Datastore that it should remove all records of the 

949 given datasets, without actually deleting them. 

950 

951 Parameters 

952 ---------- 

953 refs : `Iterable` [ `DatasetRef` ] 

954 References to the datasets being forgotten. 

955 

956 Notes 

957 ----- 

958 Asking a datastore to forget a `DatasetRef` it does not hold should be 

959 a silent no-op, not an error. 

960 """ 

961 raise NotImplementedError("Must be implemented by subclass") 

962 

963 @abstractmethod 

964 def trash(self, ref: Union[DatasetRef, Iterable[DatasetRef]], ignore_errors: bool = True) -> None: 

965 """Indicate to the Datastore that a Dataset can be moved to the trash. 

966 

967 Parameters 

968 ---------- 

969 ref : `DatasetRef` or iterable thereof 

970 Reference(s) to the required Dataset. 

971 ignore_errors : `bool`, optional 

972 Determine whether errors should be ignored. When multiple 

973 refs are being trashed there will be no per-ref check. 

974 

975 Raises 

976 ------ 

977 FileNotFoundError 

978 When Dataset does not exist and errors are not ignored. Only 

979 checked if a single ref is supplied (and not in a list). 

980 

981 Notes 

982 ----- 

983 Some Datastores may implement this method as a silent no-op to 

984 disable Dataset deletion through standard interfaces. 

985 """ 

986 raise NotImplementedError("Must be implemented by subclass") 

987 

988 @abstractmethod 

989 def emptyTrash(self, ignore_errors: bool = True) -> None: 

990 """Remove all datasets from the trash. 

991 

992 Parameters 

993 ---------- 

994 ignore_errors : `bool`, optional 

995 Determine whether errors should be ignored. 

996 

997 Notes 

998 ----- 

999 Some Datastores may implement this method as a silent no-op to 

1000 disable Dataset deletion through standard interfaces. 

1001 """ 

1002 raise NotImplementedError("Must be implemented by subclass") 

1003 

1004 @abstractmethod 

1005 def transfer(self, inputDatastore: Datastore, datasetRef: DatasetRef) -> None: 

1006 """Transfer a dataset from another datastore to this datastore. 

1007 

1008 Parameters 

1009 ---------- 

1010 inputDatastore : `Datastore` 

1011 The external `Datastore` from which to retrieve the Dataset. 

1012 datasetRef : `DatasetRef` 

1013 Reference to the required Dataset. 

1014 """ 

1015 raise NotImplementedError("Must be implemented by subclass") 

1016 

1017 def export( 

1018 self, 

1019 refs: Iterable[DatasetRef], 

1020 *, 

1021 directory: Optional[ResourcePathExpression] = None, 

1022 transfer: Optional[str] = "auto", 

1023 ) -> Iterable[FileDataset]: 

1024 """Export datasets for transfer to another data repository. 

1025 

1026 Parameters 

1027 ---------- 

1028 refs : iterable of `DatasetRef` 

1029 Dataset references to be exported. 

1030 directory : `str`, optional 

1031 Path to a directory that should contain files corresponding to 

1032 output datasets. Ignored if ``transfer`` is explicitly `None`. 

1033 transfer : `str`, optional 

1034 Mode that should be used to move datasets out of the repository. 

1035 Valid options are the same as those of the ``transfer`` argument 

1036 to ``ingest``, and datastores may similarly signal that a transfer 

1037 mode is not supported by raising `NotImplementedError`. If "auto" 

1038 is given and no ``directory`` is specified, `None` will be 

1039 implied. 

1040 

1041 Returns 

1042 ------- 

1043 dataset : iterable of `DatasetTransfer` 

1044 Structs containing information about the exported datasets, in the 

1045 same order as ``refs``. 

1046 

1047 Raises 

1048 ------ 

1049 NotImplementedError 

1050 Raised if the given transfer mode is not supported. 

1051 """ 

1052 raise NotImplementedError(f"Transfer mode {transfer} not supported.") 

1053 

1054 @abstractmethod 

1055 def validateConfiguration( 

1056 self, entities: Iterable[Union[DatasetRef, DatasetType, StorageClass]], logFailures: bool = False 

1057 ) -> None: 

1058 """Validate some of the configuration for this datastore. 

1059 

1060 Parameters 

1061 ---------- 

1062 entities : iterable of `DatasetRef`, `DatasetType`, or `StorageClass` 

1063 Entities to test against this configuration. Can be differing 

1064 types. 

1065 logFailures : `bool`, optional 

1066 If `True`, output a log message for every validation error 

1067 detected. 

1068 

1069 Raises 

1070 ------ 

1071 DatastoreValidationError 

1072 Raised if there is a validation problem with a configuration. 

1073 

1074 Notes 

1075 ----- 

1076 Which parts of the configuration are validated is at the discretion 

1077 of each Datastore implementation. 

1078 """ 

1079 raise NotImplementedError("Must be implemented by subclass") 

1080 

1081 @abstractmethod 

1082 def validateKey(self, lookupKey: LookupKey, entity: Union[DatasetRef, DatasetType, StorageClass]) -> None: 

1083 """Validate a specific look up key with supplied entity. 

1084 

1085 Parameters 

1086 ---------- 

1087 lookupKey : `LookupKey` 

1088 Key to use to retrieve information from the datastore 

1089 configuration. 

1090 entity : `DatasetRef`, `DatasetType`, or `StorageClass` 

1091 Entity to compare with configuration retrieved using the 

1092 specified lookup key. 

1093 

1094 Raises 

1095 ------ 

1096 DatastoreValidationError 

1097 Raised if there is a problem with the combination of entity 

1098 and lookup key. 

1099 

1100 Notes 

1101 ----- 

1102 Bypasses the normal selection priorities by allowing a key that 

1103 would normally not be selected to be validated. 

1104 """ 

1105 raise NotImplementedError("Must be implemented by subclass") 

1106 

1107 @abstractmethod 

1108 def getLookupKeys(self) -> Set[LookupKey]: 

1109 """Return all the lookup keys relevant to this datastore. 

1110 

1111 Returns 

1112 ------- 

1113 keys : `set` of `LookupKey` 

1114 The keys stored internally for looking up information based 

1115 on `DatasetType` name or `StorageClass`. 

1116 """ 

1117 raise NotImplementedError("Must be implemented by subclass") 

1118 

1119 def needs_expanded_data_ids( 

1120 self, 

1121 transfer: Optional[str], 

1122 entity: Optional[Union[DatasetRef, DatasetType, StorageClass]] = None, 

1123 ) -> bool: 

1124 """Test whether this datastore needs expanded data IDs to ingest. 

1125 

1126 Parameters 

1127 ---------- 

1128 transfer : `str` or `None` 

1129 Transfer mode for ingest. 

1130 entity, optional 

1131 Object representing what will be ingested. If not provided (or not 

1132 specific enough), `True` may be returned even if expanded data 

1133 IDs aren't necessary. 

1134 

1135 Returns 

1136 ------- 

1137 needed : `bool` 

1138 If `True`, expanded data IDs may be needed. `False` only if 

1139 expansion definitely isn't necessary. 

1140 """ 

1141 return True 

1142 

1143 @abstractmethod 

1144 def import_records( 

1145 self, 

1146 data: Mapping[str, DatastoreRecordData], 

1147 ) -> None: 

1148 """Import datastore location and record data from an in-memory data 

1149 structure. 

1150 

1151 Parameters 

1152 ---------- 

1153 data : `Mapping` [ `str`, `DatastoreRecordData` ] 

1154 Datastore records indexed by datastore name. May contain data for 

1155 other `Datastore` instances (generally because they are chained to 

1156 this one), which should be ignored. 

1157 

1158 Notes 

1159 ----- 

1160 Implementations should generally not check that any external resources 

1161 (e.g. files) referred to by these records actually exist, for 

1162 performance reasons; we expect higher-level code to guarantee that they 

1163 do. 

1164 

1165 Implementations are responsible for calling 

1166 `DatastoreRegistryBridge.insert` on all datasets in ``data.locations`` 

1167 where the key is in `names`, as well as loading any opaque table data. 

1168 """ 

1169 raise NotImplementedError() 

1170 

1171 @abstractmethod 

1172 def export_records( 

1173 self, 

1174 refs: Iterable[DatasetIdRef], 

1175 ) -> Mapping[str, DatastoreRecordData]: 

1176 """Export datastore records and locations to an in-memory data 

1177 structure. 

1178 

1179 Parameters 

1180 ---------- 

1181 refs : `Iterable` [ `DatasetIdRef` ] 

1182 Datasets to save. This may include datasets not known to this 

1183 datastore, which should be ignored. 

1184 

1185 Returns 

1186 ------- 

1187 data : `Mapping` [ `str`, `DatastoreRecordData` ] 

1188 Exported datastore records indexed by datastore name. 

1189 """ 

1190 raise NotImplementedError() 

1191 

1192 def set_retrieve_dataset_type_method(self, method: Callable[[str], DatasetType | None] | None) -> None: 

1193 """Specify a method that can be used by datastore to retrieve 

1194 registry-defined dataset type. 

1195 

1196 Parameters 

1197 ---------- 

1198 method : `~collections.abc.Callable` | `None` 

1199 Method that takes a name of the dataset type and returns a 

1200 corresponding `DatasetType` instance as defined in Registry. If 

1201 dataset type name is not known to registry `None` is returned. 

1202 

1203 Notes 

1204 ----- 

1205 This method is only needed for a Datastore supporting a "trusted" mode 

1206 when it does not have an access to datastore records and needs to 

1207 guess dataset location based on its stored dataset type. 

1208 """ 

1209 pass