Coverage for python/lsst/daf/butler/remote_butler/_remote_butler.py: 31%

273 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-10-09 03:22 -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 software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

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

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

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

18# (at your option) any later version. 

19# 

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

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

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

23# GNU General Public License for more details. 

24# 

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

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

27 

28from __future__ import annotations 

29 

30__all__ = ("RemoteButler",) 

31 

32import logging 

33import uuid 

34from collections.abc import Collection, Iterable, Iterator, Sequence 

35from contextlib import AbstractContextManager, contextmanager 

36from types import EllipsisType 

37from typing import TYPE_CHECKING, Any, TextIO, cast 

38 

39from deprecated.sphinx import deprecated 

40 

41from lsst.daf.butler.datastores.file_datastore.retrieve_artifacts import ( 

42 ArtifactIndexInfo, 

43 ZipIndex, 

44 determine_destination_for_retrieved_artifact, 

45 retrieve_and_zip, 

46 unpack_zips, 

47) 

48from lsst.resources import ResourcePath, ResourcePathExpression 

49 

50from .._butler import Butler, _DeprecatedDefault 

51from .._butler_collections import ButlerCollections 

52from .._butler_metrics import ButlerMetrics 

53from .._dataset_existence import DatasetExistence 

54from .._dataset_ref import DatasetId, DatasetRef 

55from .._dataset_type import DatasetType 

56from .._deferredDatasetHandle import DeferredDatasetHandle 

57from .._exceptions import DatasetNotFoundError 

58from .._query_all_datasets import QueryAllDatasetsParameters 

59from .._storage_class import StorageClass, StorageClassFactory 

60from .._utilities.locked_object import LockedObject 

61from ..datastore import DatasetRefURIs, DatastoreConfig 

62from ..datastore.cache_manager import AbstractDatastoreCacheManager, DatastoreCacheManager 

63from ..dimensions import DataIdValue, DimensionConfig, DimensionUniverse, SerializedDataId 

64from ..queries import Query 

65from ..queries.tree import make_column_literal 

66from ..registry import CollectionArgType, NoDefaultCollectionError, Registry, RegistryDefaults 

67from ._collection_args import convert_collection_arg_to_glob_string_list 

68from ._defaults import DefaultsHolder 

69from ._get import convert_http_url_to_resource_path, get_dataset_as_python_object 

70from ._http_connection import RemoteButlerHttpConnection, parse_model, quote_path_variable 

71from ._query_driver import RemoteQueryDriver 

72from ._query_results import convert_dataset_ref_results, read_query_results 

73from ._ref_utils import apply_storage_class_override, normalize_dataset_type_name, simplify_dataId 

74from ._registry import RemoteButlerRegistry 

75from ._remote_butler_collections import RemoteButlerCollections 

76from ._remote_file_transfer_source import RemoteFileTransferSource 

77from .server_models import ( 

78 CollectionList, 

79 FileInfoPayload, 

80 FindDatasetRequestModel, 

81 FindDatasetResponseModel, 

82 GetDatasetTypeResponseModel, 

83 GetFileByDataIdRequestModel, 

84 GetFileResponseModel, 

85 GetUniverseResponseModel, 

86 QueryAllDatasetsRequestModel, 

87) 

88 

89if TYPE_CHECKING: 

90 from .._dataset_provenance import DatasetProvenance 

91 from .._file_dataset import FileDataset 

92 from .._limited_butler import LimitedButler 

93 from .._timespan import Timespan 

94 from ..dimensions import DataId 

95 from ..transfers import RepoExportContext 

96 

97 

98_LOG = logging.getLogger(__name__) 

99 

100 

101class RemoteButler(Butler): # numpydoc ignore=PR02 

102 """A `Butler` that can be used to connect through a remote server. 

103 

104 Parameters 

105 ---------- 

106 options : `ButlerInstanceOptions` 

107 Default values and other settings for the Butler instance. 

108 connection : `RemoteButlerHttpConnection` 

109 Connection to Butler server. 

110 cache : `RemoteButlerCache` 

111 Cache of data shared between multiple RemoteButler instances connected 

112 to the same server. 

113 use_disabled_datastore_cache : `bool`, optional 

114 If `True`, a datastore cache manager will be created with a default 

115 disabled state which can be enabled by the environment. If `False` 

116 a cache manager will be constructed from the default local 

117 configuration, likely caching by default but only specific storage 

118 classes. 

119 

120 Notes 

121 ----- 

122 Instead of using this constructor, most users should use either 

123 `Butler.from_config` or `RemoteButlerFactory`. 

124 """ 

125 

126 _registry_defaults: DefaultsHolder 

127 _connection: RemoteButlerHttpConnection 

128 _cache: RemoteButlerCache 

129 _registry: RemoteButlerRegistry 

130 _datastore_cache_manager: AbstractDatastoreCacheManager | None 

131 _use_disabled_datastore_cache: bool 

132 

133 # This is __new__ instead of __init__ because we have to support 

134 # instantiation via the legacy constructor Butler.__new__(), which 

135 # reads the configuration and selects which subclass to instantiate. The 

136 # interaction between __new__ and __init__ is kind of wacky in Python. If 

137 # we were using __init__ here, __init__ would be called twice (once when 

138 # the RemoteButler instance is constructed inside Butler.from_config(), and 

139 # a second time with the original arguments to Butler() when the instance 

140 # is returned from Butler.__new__() 

141 def __new__( 

142 cls, 

143 *, 

144 connection: RemoteButlerHttpConnection, 

145 defaults: RegistryDefaults, 

146 cache: RemoteButlerCache, 

147 use_disabled_datastore_cache: bool = True, 

148 metrics: ButlerMetrics | None = None, 

149 ) -> RemoteButler: 

150 self = cast(RemoteButler, super().__new__(cls)) 

151 self.storageClasses = StorageClassFactory() 

152 

153 self._connection = connection 

154 self._cache = cache 

155 self._datastore_cache_manager = None 

156 self._use_disabled_datastore_cache = use_disabled_datastore_cache 

157 self._metrics = metrics if metrics is not None else ButlerMetrics() 

158 

159 self._registry_defaults = DefaultsHolder(defaults) 

160 self._registry = RemoteButlerRegistry(self, self._registry_defaults, self._connection) 

161 defaults.finish(self._registry) 

162 

163 return self 

164 

165 def isWriteable(self) -> bool: 

166 # Docstring inherited. 

167 return False 

168 

169 @property 

170 @deprecated( 

171 "Please use 'collections' instead. collection_chains will be removed after v28.", 

172 version="v28", 

173 category=FutureWarning, 

174 ) 

175 def collection_chains(self) -> ButlerCollections: 

176 """Object with methods for modifying collection chains.""" 

177 return self.collections 

178 

179 @property 

180 def collections(self) -> ButlerCollections: 

181 """Object with methods for modifying and querying collections.""" 

182 return RemoteButlerCollections(self._registry_defaults, self._connection) 

183 

184 @property 

185 def dimensions(self) -> DimensionUniverse: 

186 # Docstring inherited. 

187 with self._cache.access() as cache: 

188 if cache.dimensions is not None: 

189 return cache.dimensions 

190 

191 response = self._connection.get("universe") 

192 model = parse_model(response, GetUniverseResponseModel) 

193 

194 config = DimensionConfig.from_simple(model.universe) 

195 universe = DimensionUniverse(config) 

196 with self._cache.access() as cache: 

197 if cache.dimensions is None: 

198 cache.dimensions = universe 

199 return cache.dimensions 

200 

201 @property 

202 def _cache_manager(self) -> AbstractDatastoreCacheManager: 

203 """Cache manager to use when reading files from the butler.""" 

204 # RemoteButler does not get any cache configuration from the server. 

205 # Either create a disabled cache manager which can be enabled via the 

206 # environment, or create a cache manager from the default FileDatastore 

207 # config. This will not work properly if the defaults for 

208 # DatastoreConfig no longer include the cache. 

209 if self._datastore_cache_manager is None: 

210 datastore_config = DatastoreConfig() 

211 if not self._use_disabled_datastore_cache and "cached" in datastore_config: 

212 self._datastore_cache_manager = DatastoreCacheManager( 

213 datastore_config["cached"], universe=self.dimensions 

214 ) 

215 else: 

216 self._datastore_cache_manager = DatastoreCacheManager.create_disabled( 

217 universe=self.dimensions 

218 ) 

219 return self._datastore_cache_manager 

220 

221 def _caching_context(self) -> AbstractContextManager[None]: 

222 # Docstring inherited. 

223 # Not implemented for now, will have to think whether this needs to 

224 # do something on client side and/or remote side. 

225 raise NotImplementedError() 

226 

227 def transaction(self) -> AbstractContextManager[None]: 

228 """Will always raise NotImplementedError. 

229 Transactions are not supported by RemoteButler. 

230 """ 

231 raise NotImplementedError() 

232 

233 def put( 

234 self, 

235 obj: Any, 

236 datasetRefOrType: DatasetRef | DatasetType | str, 

237 /, 

238 dataId: DataId | None = None, 

239 *, 

240 run: str | None = None, 

241 provenance: DatasetProvenance | None = None, 

242 **kwargs: Any, 

243 ) -> DatasetRef: 

244 # Docstring inherited. 

245 raise NotImplementedError() 

246 

247 def getDeferred( 

248 self, 

249 datasetRefOrType: DatasetRef | DatasetType | str, 

250 /, 

251 dataId: DataId | None = None, 

252 *, 

253 parameters: dict | None = None, 

254 collections: Any = None, 

255 storageClass: str | StorageClass | None = None, 

256 timespan: Timespan | None = None, 

257 **kwargs: Any, 

258 ) -> DeferredDatasetHandle: 

259 response = self._get_file_info(datasetRefOrType, dataId, collections, timespan, kwargs) 

260 # Check that artifact information is available. 

261 _to_file_payload(response) 

262 ref = DatasetRef.from_simple(response.dataset_ref, universe=self.dimensions) 

263 return DeferredDatasetHandle(butler=self, ref=ref, parameters=parameters, storageClass=storageClass) 

264 

265 def get( 

266 self, 

267 datasetRefOrType: DatasetRef | DatasetType | str, 

268 /, 

269 dataId: DataId | None = None, 

270 *, 

271 parameters: dict[str, Any] | None = None, 

272 collections: Any = None, 

273 storageClass: StorageClass | str | None = None, 

274 timespan: Timespan | None = None, 

275 **kwargs: Any, 

276 ) -> Any: 

277 # Docstring inherited. 

278 with self._metrics.instrument_get(log=_LOG, msg="Retrieved remote dataset"): 

279 model = self._get_file_info(datasetRefOrType, dataId, collections, timespan, kwargs) 

280 

281 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions) 

282 # If the caller provided a DatasetRef, they may have overridden the 

283 # component on it. We need to explicitly handle this because we 

284 # did not send the DatasetType to the server in this case. 

285 if isinstance(datasetRefOrType, DatasetRef): 

286 componentOverride = datasetRefOrType.datasetType.component() 

287 if componentOverride: 

288 ref = ref.makeComponentRef(componentOverride) 

289 ref = apply_storage_class_override(ref, datasetRefOrType, storageClass) 

290 

291 return self._get_dataset_as_python_object(ref, model, parameters) 

292 

293 def _get_dataset_as_python_object( 

294 self, 

295 ref: DatasetRef, 

296 model: GetFileResponseModel, 

297 parameters: dict[str, Any] | None, 

298 ) -> Any: 

299 # This thin wrapper method is here to provide a place to hook in a mock 

300 # mimicking DatastoreMock functionality for use in unit tests. 

301 return get_dataset_as_python_object( 

302 ref, 

303 _to_file_payload(model), 

304 auth=self._connection.auth, 

305 parameters=parameters, 

306 cache_manager=self._cache_manager, 

307 ) 

308 

309 def _get_file_info( 

310 self, 

311 datasetRefOrType: DatasetRef | DatasetType | str, 

312 dataId: DataId | None, 

313 collections: CollectionArgType, 

314 timespan: Timespan | None, 

315 kwargs: dict[str, DataIdValue], 

316 ) -> GetFileResponseModel: 

317 """Send a request to the server for the file URLs and metadata 

318 associated with a dataset. 

319 """ 

320 if isinstance(datasetRefOrType, DatasetRef): 

321 if dataId is not None: 

322 raise ValueError("DatasetRef given, cannot use dataId as well") 

323 return self._get_file_info_for_ref(datasetRefOrType) 

324 else: 

325 request = GetFileByDataIdRequestModel( 

326 dataset_type=normalize_dataset_type_name(datasetRefOrType), 

327 collections=self._normalize_collections(collections), 

328 data_id=simplify_dataId(dataId, kwargs), 

329 default_data_id=self._serialize_default_data_id(), 

330 timespan=timespan, 

331 ) 

332 response = self._connection.post("get_file_by_data_id", request) 

333 return parse_model(response, GetFileResponseModel) 

334 

335 def _get_file_info_for_ref(self, ref: DatasetRef) -> GetFileResponseModel: 

336 response = self._connection.get(f"get_file/{_to_uuid_string(ref.id)}") 

337 return parse_model(response, GetFileResponseModel) 

338 

339 def getURIs( 

340 self, 

341 datasetRefOrType: DatasetRef | DatasetType | str, 

342 /, 

343 dataId: DataId | None = None, 

344 *, 

345 predict: bool = False, 

346 collections: Any = None, 

347 run: str | None = None, 

348 **kwargs: Any, 

349 ) -> DatasetRefURIs: 

350 # Docstring inherited. 

351 if predict or run: 

352 raise NotImplementedError("Predict mode is not supported by RemoteButler") 

353 

354 response = self._get_file_info(datasetRefOrType, dataId, collections, None, kwargs) 

355 file_info = _to_file_payload(response).file_info 

356 if len(file_info) == 1: 

357 return DatasetRefURIs( 

358 primaryURI=convert_http_url_to_resource_path( 

359 file_info[0].url, self._connection.auth, file_info[0].auth 

360 ) 

361 ) 

362 else: 

363 components = {} 

364 for f in file_info: 

365 component = f.datastoreRecords.component 

366 if component is None: 

367 raise ValueError( 

368 f"DatasetId {response.dataset_ref.id} has a component file" 

369 " with no component name defined" 

370 ) 

371 components[component] = convert_http_url_to_resource_path( 

372 f.url, self._connection.auth, f.auth 

373 ) 

374 return DatasetRefURIs(componentURIs=components) 

375 

376 def get_dataset_type(self, name: str) -> DatasetType: 

377 with self._cache.access() as cache: 

378 if (cached_value := cache.dataset_types.get(name)) is not None: 

379 return cached_value 

380 

381 response = self._connection.get(f"dataset_type/{quote_path_variable(name)}") 

382 model = parse_model(response, GetDatasetTypeResponseModel) 

383 value = DatasetType.from_simple(model.dataset_type, universe=self.dimensions) 

384 with self._cache.access() as cache: 

385 return cache.dataset_types.setdefault(name, value) 

386 

387 def get_dataset( 

388 self, 

389 id: DatasetId, 

390 *, 

391 storage_class: str | StorageClass | None = None, 

392 dimension_records: bool = False, 

393 datastore_records: bool = False, 

394 ) -> DatasetRef | None: 

395 # datastore_records is intentionally ignored. It is an optimization 

396 # flag that only applies to DirectButler. 

397 path = f"dataset/{_to_uuid_string(id)}" 

398 response = self._connection.get(path, params={"dimension_records": bool(dimension_records)}) 

399 model = parse_model(response, FindDatasetResponseModel) 

400 if model.dataset_ref is None: 

401 return None 

402 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions) 

403 if storage_class is not None: 

404 ref = ref.overrideStorageClass(storage_class) 

405 return ref 

406 

407 def find_dataset( 

408 self, 

409 dataset_type: DatasetType | str, 

410 data_id: DataId | None = None, 

411 *, 

412 collections: str | Sequence[str] | None = None, 

413 timespan: Timespan | None = None, 

414 storage_class: str | StorageClass | None = None, 

415 dimension_records: bool = False, 

416 datastore_records: bool = False, 

417 **kwargs: Any, 

418 ) -> DatasetRef | None: 

419 # datastore_records is intentionally ignored. It is an optimization 

420 # flag that only applies to DirectButler. 

421 

422 query = FindDatasetRequestModel( 

423 dataset_type=normalize_dataset_type_name(dataset_type), 

424 data_id=simplify_dataId(data_id, kwargs), 

425 default_data_id=self._serialize_default_data_id(), 

426 collections=self._normalize_collections(collections), 

427 timespan=timespan, 

428 dimension_records=dimension_records, 

429 ) 

430 

431 response = self._connection.post("find_dataset", query) 

432 

433 model = parse_model(response, FindDatasetResponseModel) 

434 if model.dataset_ref is None: 

435 return None 

436 

437 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions) 

438 return apply_storage_class_override(ref, dataset_type, storage_class) 

439 

440 def _retrieve_artifacts( 

441 self, 

442 refs: Iterable[DatasetRef], 

443 destination: ResourcePathExpression, 

444 transfer: str = "auto", 

445 preserve_path: bool = True, 

446 overwrite: bool = False, 

447 write_index: bool = True, 

448 add_prefix: bool = False, 

449 ) -> dict[ResourcePath, ArtifactIndexInfo]: 

450 destination = ResourcePath(destination).abspath() 

451 if not destination.isdir(): 

452 raise ValueError(f"Destination location must refer to a directory. Given {destination}.") 

453 

454 if transfer not in ("auto", "copy"): 

455 raise ValueError("Only 'copy' and 'auto' transfer modes are supported.") 

456 

457 requested_ids = {ref.id for ref in refs} 

458 have_copied: dict[ResourcePath, ResourcePath] = {} 

459 artifact_map: dict[ResourcePath, ArtifactIndexInfo] = {} 

460 # Sort to ensure that in many refs to one file situation the same 

461 # ref is used for any prefix that might be added. 

462 for ref in sorted(refs): 

463 prefix = str(ref.id)[:8] + "-" if add_prefix else "" 

464 file_info = _to_file_payload(self._get_file_info_for_ref(ref)).file_info 

465 for file in file_info: 

466 source_uri = ResourcePath(str(file.url)) 

467 # For DECam/zip we only want to copy once. 

468 # For zip files we need to unpack so that they can be 

469 # zipped up again if needed. 

470 is_zip = source_uri.getExtension() == ".zip" and "zip-path" in source_uri.fragment 

471 cleaned_source_uri = source_uri.replace(fragment="", query="", params="") 

472 if is_zip: 

473 if cleaned_source_uri not in have_copied: 

474 zipped_artifacts = unpack_zips( 

475 [cleaned_source_uri], requested_ids, destination, preserve_path, overwrite 

476 ) 

477 artifact_map.update(zipped_artifacts) 

478 have_copied[cleaned_source_uri] = cleaned_source_uri 

479 elif cleaned_source_uri not in have_copied: 

480 relative_path = ResourcePath(file.datastoreRecords.path, forceAbsolute=False) 

481 target_uri = determine_destination_for_retrieved_artifact( 

482 destination, relative_path, preserve_path, prefix 

483 ) 

484 # Because signed URLs expire, we want to do the transfer 

485 # soon after retrieving the URL. 

486 target_uri.transfer_from(source_uri, transfer="copy", overwrite=overwrite) 

487 have_copied[cleaned_source_uri] = target_uri 

488 artifact_map[target_uri] = ArtifactIndexInfo.from_single(file.datastoreRecords, ref.id) 

489 else: 

490 target_uri = have_copied[cleaned_source_uri] 

491 artifact_map[target_uri].append(ref.id) 

492 

493 if write_index: 

494 index = ZipIndex.from_artifact_map(refs, artifact_map, destination) 

495 index.write_index(destination) 

496 

497 return artifact_map 

498 

499 def retrieve_artifacts_zip( 

500 self, 

501 refs: Iterable[DatasetRef], 

502 destination: ResourcePathExpression, 

503 overwrite: bool = True, 

504 ) -> ResourcePath: 

505 return retrieve_and_zip(refs, destination, self._retrieve_artifacts, overwrite) 

506 

507 def retrieveArtifacts( 

508 self, 

509 refs: Iterable[DatasetRef], 

510 destination: ResourcePathExpression, 

511 transfer: str = "auto", 

512 preserve_path: bool = True, 

513 overwrite: bool = False, 

514 ) -> list[ResourcePath]: 

515 artifact_map = self._retrieve_artifacts( 

516 refs, 

517 destination, 

518 transfer, 

519 preserve_path, 

520 overwrite, 

521 ) 

522 return list(artifact_map) 

523 

524 def exists( 

525 self, 

526 dataset_ref_or_type: DatasetRef | DatasetType | str, 

527 /, 

528 data_id: DataId | None = None, 

529 *, 

530 full_check: bool = True, 

531 collections: Any = None, 

532 **kwargs: Any, 

533 ) -> DatasetExistence: 

534 try: 

535 response = self._get_file_info( 

536 dataset_ref_or_type, dataId=data_id, collections=collections, timespan=None, kwargs=kwargs 

537 ) 

538 except DatasetNotFoundError: 

539 return DatasetExistence.UNRECOGNIZED 

540 

541 if response.artifact is None: 

542 if full_check: 

543 return DatasetExistence.RECORDED 

544 else: 

545 return DatasetExistence.RECORDED | DatasetExistence._ASSUMED 

546 

547 if full_check: 

548 for file in response.artifact.file_info: 

549 if not ResourcePath(str(file.url)).exists(): 

550 return DatasetExistence.RECORDED | DatasetExistence.DATASTORE 

551 return DatasetExistence.VERIFIED 

552 else: 

553 return DatasetExistence.KNOWN 

554 

555 def _exists_many( 

556 self, 

557 refs: Iterable[DatasetRef], 

558 /, 

559 *, 

560 full_check: bool = True, 

561 ) -> dict[DatasetRef, DatasetExistence]: 

562 return {ref: self.exists(ref, full_check=full_check) for ref in refs} 

563 

564 def removeRuns( 

565 self, 

566 names: Iterable[str], 

567 unstore: bool | type[_DeprecatedDefault] = _DeprecatedDefault, 

568 *, 

569 unlink_from_chains: bool = False, 

570 ) -> None: 

571 # Docstring inherited. 

572 raise NotImplementedError() 

573 

574 def ingest( 

575 self, 

576 *datasets: FileDataset, 

577 transfer: str | None = "auto", 

578 record_validation_info: bool = True, 

579 skip_existing: bool = False, 

580 ) -> None: 

581 # Docstring inherited. 

582 raise NotImplementedError() 

583 

584 def ingest_zip( 

585 self, 

586 zip_file: ResourcePathExpression, 

587 transfer: str = "auto", 

588 *, 

589 transfer_dimensions: bool = False, 

590 dry_run: bool = False, 

591 ) -> None: 

592 # Docstring inherited. 

593 raise NotImplementedError() 

594 

595 def export( 

596 self, 

597 *, 

598 directory: str | None = None, 

599 filename: str | None = None, 

600 format: str | None = None, 

601 transfer: str | None = None, 

602 ) -> AbstractContextManager[RepoExportContext]: 

603 # Docstring inherited. 

604 raise NotImplementedError() 

605 

606 def import_( 

607 self, 

608 *, 

609 directory: ResourcePathExpression | None = None, 

610 filename: ResourcePathExpression | TextIO | None = None, 

611 format: str | None = None, 

612 transfer: str | None = None, 

613 skip_dimensions: set | None = None, 

614 record_validation_info: bool = True, 

615 without_datastore: bool = False, 

616 ) -> None: 

617 # Docstring inherited. 

618 raise NotImplementedError() 

619 

620 def transfer_dimension_records_from( 

621 self, source_butler: LimitedButler | Butler, source_refs: Iterable[DatasetRef] 

622 ) -> None: 

623 # Docstring inherited. 

624 raise NotImplementedError() 

625 

626 def transfer_from( 

627 self, 

628 source_butler: LimitedButler, 

629 source_refs: Iterable[DatasetRef], 

630 transfer: str = "auto", 

631 skip_missing: bool = True, 

632 register_dataset_types: bool = False, 

633 transfer_dimensions: bool = False, 

634 dry_run: bool = False, 

635 ) -> Collection[DatasetRef]: 

636 # Docstring inherited. 

637 raise NotImplementedError() 

638 

639 def validateConfiguration( 

640 self, 

641 logFailures: bool = False, 

642 datasetTypeNames: Iterable[str] | None = None, 

643 ignore: Iterable[str] | None = None, 

644 ) -> None: 

645 # Docstring inherited. 

646 raise NotImplementedError() 

647 

648 @property 

649 def run(self) -> str | None: 

650 # Docstring inherited. 

651 return self._registry_defaults.get().run 

652 

653 @property 

654 def registry(self) -> Registry: 

655 return self._registry 

656 

657 @contextmanager 

658 def query(self) -> Iterator[Query]: 

659 driver = RemoteQueryDriver(self, self._connection) 

660 with driver: 

661 query = Query(driver) 

662 yield query 

663 

664 @contextmanager 

665 def _query_all_datasets_by_page( 

666 self, args: QueryAllDatasetsParameters 

667 ) -> Iterator[Iterator[list[DatasetRef]]]: 

668 universe = self.dimensions 

669 

670 request = QueryAllDatasetsRequestModel( 

671 collections=self._normalize_collections(args.collections), 

672 name=[normalize_dataset_type_name(name) for name in args.name], 

673 find_first=args.find_first, 

674 data_id=simplify_dataId(args.data_id, args.kwargs), 

675 default_data_id=self._serialize_default_data_id(), 

676 where=args.where, 

677 bind={k: make_column_literal(v) for k, v in args.bind.items()}, 

678 limit=args.limit, 

679 with_dimension_records=args.with_dimension_records, 

680 ) 

681 with self._connection.post_with_stream_response("query/all_datasets", request) as response: 

682 pages = read_query_results(response) 

683 yield (convert_dataset_ref_results(page, universe) for page in pages) 

684 

685 def pruneDatasets( 

686 self, 

687 refs: Iterable[DatasetRef], 

688 *, 

689 disassociate: bool = True, 

690 unstore: bool = False, 

691 tags: Iterable[str] = (), 

692 purge: bool = False, 

693 ) -> None: 

694 # Docstring inherited. 

695 raise NotImplementedError() 

696 

697 def _normalize_collections(self, collections: CollectionArgType | None) -> CollectionList: 

698 """Convert the ``collections`` parameter in the format used by Butler 

699 methods to a standardized format for the REST API. 

700 """ 

701 if collections is None: 

702 if not self.collections.defaults: 

703 raise NoDefaultCollectionError( 

704 "No collections provided, and no defaults from butler construction." 

705 ) 

706 collections = self.collections.defaults 

707 return convert_collection_arg_to_glob_string_list(collections) 

708 

709 def clone( 

710 self, 

711 *, 

712 collections: CollectionArgType | None | EllipsisType = ..., 

713 run: str | None | EllipsisType = ..., 

714 inferDefaults: bool | EllipsisType = ..., 

715 dataId: dict[str, str] | EllipsisType = ..., 

716 metrics: ButlerMetrics | None = None, 

717 ) -> RemoteButler: 

718 defaults = self._registry_defaults.get().clone(collections, run, inferDefaults, dataId) 

719 return RemoteButler( 

720 connection=self._connection, cache=self._cache, defaults=defaults, metrics=metrics 

721 ) 

722 

723 @property 

724 def _file_transfer_source(self) -> RemoteFileTransferSource: 

725 return RemoteFileTransferSource(self._connection) 

726 

727 def __str__(self) -> str: 

728 return f"RemoteButler({self._connection.server_url})" 

729 

730 def _serialize_default_data_id(self) -> SerializedDataId: 

731 """Convert the default data ID to a serializable format.""" 

732 # In an ideal world, the default data ID would just get combined with 

733 # the rest of the data ID on the client side instead of being sent 

734 # separately to the server. Unfortunately, that requires knowledge of 

735 # the DatasetType's dimensions which we don't always have available on 

736 # the client. Data ID values can be specified indirectly by "implied" 

737 # dimensions, but knowing what things are implied depends on what the 

738 # required dimensions are. 

739 

740 return self._registry_defaults.get().dataId.to_simple(minimal=True).dataId 

741 

742 

743def _to_file_payload(get_file_response: GetFileResponseModel) -> FileInfoPayload: 

744 if get_file_response.artifact is None: 

745 ref = get_file_response.dataset_ref 

746 raise DatasetNotFoundError(f"Dataset is known, but artifact is not available. (datasetId='{ref.id}')") 

747 

748 return get_file_response.artifact 

749 

750 

751def _to_uuid_string(id: uuid.UUID | str) -> str: 

752 """Convert a UUID, or string parseable as a UUID, into a string formatted 

753 like '1481269e-4c8d-4696-bcca-d1b4c9005d06' 

754 """ 

755 return str(uuid.UUID(str(id))) 

756 

757 

758class _RemoteButlerCacheData: 

759 def __init__(self) -> None: 

760 self.dimensions: DimensionUniverse | None = None 

761 self.dataset_types: dict[str, DatasetType] = {} 

762 

763 

764class RemoteButlerCache(LockedObject[_RemoteButlerCacheData]): 

765 def __init__(self) -> None: 

766 super().__init__(_RemoteButlerCacheData())