Coverage for python/lsst/daf/butler/remote_butler/_remote_butler.py: 0%
301 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-16 14:47 -0700
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-16 14:47 -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/>.
28from __future__ import annotations
30__all__ = ("RemoteButler",)
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
39from deprecated.sphinx import deprecated
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
49from lsst.utils.iteration import chunk_iterable
51from .._butler import Butler, _DeprecatedDefault
52from .._butler_collections import ButlerCollections
53from .._butler_metrics import ButlerMetrics
54from .._dataset_existence import DatasetExistence
55from .._dataset_ref import DatasetId, DatasetRef
56from .._dataset_type import DatasetType
57from .._deferredDatasetHandle import DeferredDatasetHandle
58from .._exceptions import DatasetNotFoundError
59from .._query_all_datasets import QueryAllDatasetsParameters
60from .._storage_class import StorageClass, StorageClassFactory
61from .._utilities.locked_object import LockedObject
62from ..datastore import DatasetRefURIs, DatastoreConfig
63from ..datastore.cache_manager import AbstractDatastoreCacheManager, DatastoreCacheManager
64from ..dimensions import DataCoordinate, DataIdValue, DimensionConfig, DimensionUniverse, SerializedDataId
65from ..queries import Query
66from ..queries.tree import make_column_literal
67from ..registry import CollectionArgType, NoDefaultCollectionError, Registry, RegistryDefaults
68from ..registry.expand_data_ids import expand_data_ids
69from ._collection_args import convert_collection_arg_to_glob_string_list
70from ._defaults import DefaultsHolder
71from ._get import convert_http_url_to_resource_path, get_dataset_as_python_object
72from ._http_connection import RemoteButlerHttpConnection, parse_model, quote_path_variable
73from ._query_driver import RemoteQueryDriver
74from ._query_results import convert_dataset_ref_results, read_query_results
75from ._ref_utils import (
76 apply_storage_class_override,
77 get_component_override,
78 normalize_dataset_type_name,
79 simplify_dataId,
80 split_dataset_type_name,
81)
82from ._registry import RemoteButlerRegistry
83from ._remote_butler_collections import RemoteButlerCollections
84from ._remote_file_transfer_source import RemoteFileTransferSource
85from .server_models import (
86 CollectionList,
87 FileInfoPayload,
88 FindDatasetRequestModel,
89 FindDatasetResponseModel,
90 GetDatasetTypeResponseModel,
91 GetFileByDataIdRequestModel,
92 GetFileResponseModel,
93 GetManyDatasetsRequestModel,
94 GetManyDatasetsResponseModel,
95 GetUniverseResponseModel,
96 QueryAllDatasetsRequestModel,
97)
99if TYPE_CHECKING:
100 from .._dataset_provenance import DatasetProvenance
101 from .._file_dataset import FileDataset
102 from .._limited_butler import LimitedButler
103 from .._timespan import Timespan
104 from ..dimensions import DataId
105 from ..transfers import RepoExportContext
108_LOG = logging.getLogger(__name__)
111class RemoteButler(Butler): # numpydoc ignore=PR02
112 """A `Butler` that can be used to connect through a remote server.
114 Parameters
115 ----------
116 options : `ButlerInstanceOptions`
117 Default values and other settings for the Butler instance.
118 connection : `RemoteButlerHttpConnection`
119 Connection to Butler server.
120 cache : `RemoteButlerCache`
121 Cache of data shared between multiple RemoteButler instances connected
122 to the same server.
123 use_disabled_datastore_cache : `bool`, optional
124 If `True`, a datastore cache manager will be created with a default
125 disabled state which can be enabled by the environment. If `False`
126 a cache manager will be constructed from the default local
127 configuration, likely caching by default but only specific storage
128 classes.
130 Notes
131 -----
132 Instead of using this constructor, most users should use either
133 `Butler.from_config` or `RemoteButlerFactory`.
134 """
136 _registry_defaults: DefaultsHolder
137 _connection: RemoteButlerHttpConnection
138 _cache: RemoteButlerCache
139 _registry: RemoteButlerRegistry
140 _datastore_cache_manager: AbstractDatastoreCacheManager | None
141 _use_disabled_datastore_cache: bool
143 # This is __new__ instead of __init__ because we have to support
144 # instantiation via the legacy constructor Butler.__new__(), which
145 # reads the configuration and selects which subclass to instantiate. The
146 # interaction between __new__ and __init__ is kind of wacky in Python. If
147 # we were using __init__ here, __init__ would be called twice (once when
148 # the RemoteButler instance is constructed inside Butler.from_config(), and
149 # a second time with the original arguments to Butler() when the instance
150 # is returned from Butler.__new__()
151 def __new__(
152 cls,
153 *,
154 connection: RemoteButlerHttpConnection,
155 defaults: RegistryDefaults,
156 cache: RemoteButlerCache,
157 use_disabled_datastore_cache: bool = True,
158 metrics: ButlerMetrics | None = None,
159 ) -> RemoteButler:
160 self = cast(RemoteButler, super().__new__(cls))
161 self.storageClasses = StorageClassFactory()
163 self._connection = connection
164 self._cache = cache
165 self._datastore_cache_manager = None
166 self._use_disabled_datastore_cache = use_disabled_datastore_cache
167 self._metrics = metrics if metrics is not None else ButlerMetrics()
169 self._registry_defaults = DefaultsHolder(defaults)
170 self._registry = RemoteButlerRegistry(self, self._registry_defaults, self._connection)
171 defaults.finish(self._registry)
173 return self
175 def isWriteable(self) -> bool:
176 # Docstring inherited.
177 return False
179 @property
180 @deprecated(
181 "Please use 'collections' instead. collection_chains will be removed after v28.",
182 version="v28",
183 category=FutureWarning,
184 )
185 def collection_chains(self) -> ButlerCollections:
186 """Object with methods for modifying collection chains."""
187 return self.collections
189 @property
190 def collections(self) -> ButlerCollections:
191 """Object with methods for modifying and querying collections."""
192 return RemoteButlerCollections(self._registry_defaults, self._connection)
194 @property
195 def dimensions(self) -> DimensionUniverse:
196 # Docstring inherited.
197 with self._cache.access() as cache:
198 if cache.dimensions is not None:
199 return cache.dimensions
201 response = self._connection.get("universe")
202 model = parse_model(response, GetUniverseResponseModel)
204 config = DimensionConfig.from_simple(model.universe)
205 universe = DimensionUniverse(config)
206 with self._cache.access() as cache:
207 if cache.dimensions is None:
208 cache.dimensions = universe
209 return cache.dimensions
211 @property
212 def _cache_manager(self) -> AbstractDatastoreCacheManager:
213 """Cache manager to use when reading files from the butler."""
214 # RemoteButler does not get any cache configuration from the server.
215 # Either create a disabled cache manager which can be enabled via the
216 # environment, or create a cache manager from the default FileDatastore
217 # config. This will not work properly if the defaults for
218 # DatastoreConfig no longer include the cache.
219 if self._datastore_cache_manager is None:
220 datastore_config = DatastoreConfig()
221 if not self._use_disabled_datastore_cache and "cached" in datastore_config:
222 self._datastore_cache_manager = DatastoreCacheManager(
223 datastore_config["cached"], universe=self.dimensions
224 )
225 else:
226 self._datastore_cache_manager = DatastoreCacheManager.create_disabled(
227 universe=self.dimensions
228 )
229 return self._datastore_cache_manager
231 def _caching_context(self) -> AbstractContextManager[None]:
232 # Docstring inherited.
233 # Not implemented for now, will have to think whether this needs to
234 # do something on client side and/or remote side.
235 raise NotImplementedError()
237 def transaction(self) -> AbstractContextManager[None]:
238 """Will always raise NotImplementedError.
239 Transactions are not supported by RemoteButler.
240 """
241 raise NotImplementedError()
243 def put(
244 self,
245 obj: Any,
246 datasetRefOrType: DatasetRef | DatasetType | str,
247 /,
248 dataId: DataId | None = None,
249 *,
250 run: str | None = None,
251 provenance: DatasetProvenance | None = None,
252 **kwargs: Any,
253 ) -> DatasetRef:
254 # Docstring inherited.
255 raise NotImplementedError()
257 def getDeferred(
258 self,
259 datasetRefOrType: DatasetRef | DatasetType | str,
260 /,
261 dataId: DataId | None = None,
262 *,
263 parameters: dict | None = None,
264 collections: Any = None,
265 storageClass: str | StorageClass | None = None,
266 timespan: Timespan | None = None,
267 **kwargs: Any,
268 ) -> DeferredDatasetHandle:
269 response = self._get_file_info(datasetRefOrType, dataId, collections, timespan, kwargs)
270 # Check that artifact information is available.
271 _to_file_payload(response)
272 if isinstance(datasetRefOrType, DatasetRef):
273 # Use the ref provided by the caller, which may include component
274 # or storage class overrides that are not known to the server.
275 ref = datasetRefOrType
276 else:
277 ref = DatasetRef.from_simple(response.dataset_ref, universe=self.dimensions)
278 # The server returns the parent dataset type -- component dataset
279 # types are never sent to the server, because it may not have the
280 # storage class definitions needed to construct them. Re-apply
281 # any component here.
282 component = get_component_override(datasetRefOrType)
283 if component is not None:
284 ref = ref.makeComponentRef(component)
285 return DeferredDatasetHandle(butler=self, ref=ref, parameters=parameters, storageClass=storageClass)
287 def get(
288 self,
289 datasetRefOrType: DatasetRef | DatasetType | str,
290 /,
291 dataId: DataId | None = None,
292 *,
293 parameters: dict[str, Any] | None = None,
294 collections: Any = None,
295 storageClass: StorageClass | str | None = None,
296 timespan: Timespan | None = None,
297 **kwargs: Any,
298 ) -> Any:
299 # Docstring inherited.
300 with self._metrics.instrument_get(log=_LOG, msg="Retrieved remote dataset"):
301 model = self._get_file_info(datasetRefOrType, dataId, collections, timespan, kwargs)
303 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions)
304 # The server returns the parent dataset type -- component dataset
305 # types are never sent to the server, because it may not have the
306 # storage class definitions needed to construct them. Re-apply
307 # any component here.
308 componentOverride = get_component_override(datasetRefOrType)
309 if componentOverride is not None:
310 ref = ref.makeComponentRef(componentOverride)
311 ref = apply_storage_class_override(ref, datasetRefOrType, storageClass)
313 return self._get_dataset_as_python_object(ref, model, parameters)
315 def _get_dataset_as_python_object(
316 self,
317 ref: DatasetRef,
318 model: GetFileResponseModel,
319 parameters: dict[str, Any] | None,
320 ) -> Any:
321 # This thin wrapper method is here to provide a place to hook in a mock
322 # mimicking DatastoreMock functionality for use in unit tests.
323 return get_dataset_as_python_object(
324 ref,
325 _to_file_payload(model),
326 auth=self._connection.auth,
327 parameters=parameters,
328 cache_manager=self._cache_manager,
329 )
331 def _get_file_info(
332 self,
333 datasetRefOrType: DatasetRef | DatasetType | str,
334 dataId: DataId | None,
335 collections: CollectionArgType,
336 timespan: Timespan | None,
337 kwargs: dict[str, DataIdValue],
338 ) -> GetFileResponseModel:
339 """Send a request to the server for the file URLs and metadata
340 associated with a dataset.
341 """
342 if isinstance(datasetRefOrType, DatasetRef):
343 if dataId is not None:
344 raise ValueError("DatasetRef given, cannot use dataId as well")
345 return self._get_file_info_for_ref(datasetRefOrType)
346 else:
347 # Only the parent dataset type is sent to the server -- it may
348 # not have the storage class definitions needed to construct a
349 # component DatasetType. Callers are responsible for re-applying
350 # any component to the returned ref.
351 dataset_type_name, _ = split_dataset_type_name(datasetRefOrType)
352 request = GetFileByDataIdRequestModel(
353 dataset_type=dataset_type_name,
354 collections=self._normalize_collections(collections),
355 data_id=simplify_dataId(dataId, kwargs),
356 default_data_id=self._serialize_default_data_id(),
357 timespan=timespan,
358 )
359 response = self._connection.post("get_file_by_data_id", request)
360 return parse_model(response, GetFileResponseModel)
362 def _get_file_info_for_ref(self, ref: DatasetRef) -> GetFileResponseModel:
363 response = self._connection.get(f"get_file/{_to_uuid_string(ref.id)}")
364 return parse_model(response, GetFileResponseModel)
366 def getURIs(
367 self,
368 datasetRefOrType: DatasetRef | DatasetType | str,
369 /,
370 dataId: DataId | None = None,
371 *,
372 predict: bool = False,
373 collections: Any = None,
374 run: str | None = None,
375 **kwargs: Any,
376 ) -> DatasetRefURIs:
377 # Docstring inherited.
378 if predict or run:
379 raise NotImplementedError("Predict mode is not supported by RemoteButler")
381 response = self._get_file_info(datasetRefOrType, dataId, collections, None, kwargs)
382 file_info = _to_file_payload(response).file_info
383 if len(file_info) == 1:
384 return DatasetRefURIs(
385 primaryURI=convert_http_url_to_resource_path(
386 file_info[0].url, self._connection.auth, file_info[0].auth
387 )
388 )
389 else:
390 components = {}
391 for f in file_info:
392 component = f.datastoreRecords.component
393 if component is None:
394 raise ValueError(
395 f"DatasetId {response.dataset_ref.id} has a component file"
396 " with no component name defined"
397 )
398 components[component] = convert_http_url_to_resource_path(
399 f.url, self._connection.auth, f.auth
400 )
401 return DatasetRefURIs(componentURIs=components)
403 def get_dataset_type(self, name: str) -> DatasetType:
404 with self._cache.access() as cache:
405 if (cached_value := cache.dataset_types.get(name)) is not None:
406 return cached_value
408 # Only the parent dataset type name is sent to the server -- it may
409 # not have the storage class definitions needed to construct a
410 # component DatasetType, so the component dataset type is constructed
411 # here from the parent definition.
412 parent_name, component = split_dataset_type_name(name)
413 response = self._connection.get(f"dataset_type/{quote_path_variable(parent_name)}")
414 model = parse_model(response, GetDatasetTypeResponseModel)
415 value = DatasetType.from_simple(model.dataset_type, universe=self.dimensions)
416 if component is not None:
417 value = value.makeComponentDatasetType(component)
418 with self._cache.access() as cache:
419 return cache.dataset_types.setdefault(name, value)
421 def get_dataset(
422 self,
423 id: DatasetId | str,
424 *,
425 storage_class: str | StorageClass | None = None,
426 dimension_records: bool = False,
427 datastore_records: bool = False,
428 ) -> DatasetRef | None:
429 # datastore_records is intentionally ignored. It is an optimization
430 # flag that only applies to DirectButler.
431 path = f"dataset/{_to_uuid_string(id)}"
432 response = self._connection.get(path, params={"dimension_records": bool(dimension_records)})
433 model = parse_model(response, FindDatasetResponseModel)
434 if model.dataset_ref is None:
435 return None
436 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions)
437 if storage_class is not None:
438 ref = ref.overrideStorageClass(storage_class)
439 return ref
441 def get_many_datasets(self, ids: Iterable[DatasetId | str]) -> list[DatasetRef]:
442 result = []
443 for batch in chunk_iterable(ids, GetManyDatasetsRequestModel.MAX_ITEMS_PER_REQUEST):
444 request = GetManyDatasetsRequestModel(dataset_ids=batch)
445 response = self._connection.post("datasets", request)
446 model = parse_model(response, GetManyDatasetsResponseModel)
447 refs = convert_dataset_ref_results(model, self.dimensions)
448 result.extend(refs)
449 return result
451 def find_dataset(
452 self,
453 dataset_type: DatasetType | str,
454 data_id: DataId | None = None,
455 *,
456 collections: str | Sequence[str] | None = None,
457 timespan: Timespan | None = None,
458 storage_class: str | StorageClass | None = None,
459 dimension_records: bool = False,
460 datastore_records: bool = False,
461 **kwargs: Any,
462 ) -> DatasetRef | None:
463 # datastore_records is intentionally ignored. It is an optimization
464 # flag that only applies to DirectButler.
466 # Only the parent dataset type is sent to the server -- it may not
467 # have the storage class definitions needed to construct a component
468 # DatasetType. The component is re-applied to the returned ref below.
469 dataset_type_name, component = split_dataset_type_name(dataset_type)
470 query = FindDatasetRequestModel(
471 dataset_type=dataset_type_name,
472 data_id=simplify_dataId(data_id, kwargs),
473 default_data_id=self._serialize_default_data_id(),
474 collections=self._normalize_collections(collections),
475 timespan=timespan,
476 dimension_records=dimension_records,
477 )
479 response = self._connection.post("find_dataset", query)
481 model = parse_model(response, FindDatasetResponseModel)
482 if model.dataset_ref is None:
483 return None
485 ref = DatasetRef.from_simple(model.dataset_ref, universe=self.dimensions)
486 if isinstance(data_id, DataCoordinate) and data_id.hasRecords():
487 ref = ref.expanded(data_id)
488 if component is not None:
489 ref = ref.makeComponentRef(component)
490 return apply_storage_class_override(ref, dataset_type, storage_class)
492 def _retrieve_artifacts(
493 self,
494 refs: Iterable[DatasetRef],
495 destination: ResourcePathExpression,
496 transfer: str = "auto",
497 preserve_path: bool = True,
498 overwrite: bool = False,
499 write_index: bool = True,
500 add_prefix: bool = False,
501 ) -> dict[ResourcePath, ArtifactIndexInfo]:
502 destination = ResourcePath(destination).abspath()
503 if not destination.isdir():
504 raise ValueError(f"Destination location must refer to a directory. Given {destination}.")
506 if transfer not in ("auto", "copy"):
507 raise ValueError("Only 'copy' and 'auto' transfer modes are supported.")
509 requested_ids = {ref.id for ref in refs}
510 have_copied: dict[ResourcePath, ResourcePath] = {}
511 artifact_map: dict[ResourcePath, ArtifactIndexInfo] = {}
512 # Sort to ensure that in many refs to one file situation the same
513 # ref is used for any prefix that might be added.
514 for ref in sorted(refs):
515 prefix = str(ref.id)[:8] + "-" if add_prefix else ""
516 file_info = _to_file_payload(self._get_file_info_for_ref(ref)).file_info
517 for file in file_info:
518 source_uri = ResourcePath(str(file.url))
519 # For DECam/zip we only want to copy once.
520 # For zip files we need to unpack so that they can be
521 # zipped up again if needed.
522 is_zip = source_uri.getExtension() == ".zip" and "zip-path" in source_uri.fragment
523 cleaned_source_uri = source_uri.replace(fragment="", query="", params="")
524 if is_zip:
525 if cleaned_source_uri not in have_copied:
526 zipped_artifacts = unpack_zips(
527 [cleaned_source_uri], requested_ids, destination, preserve_path, overwrite
528 )
529 artifact_map.update(zipped_artifacts)
530 have_copied[cleaned_source_uri] = cleaned_source_uri
531 elif cleaned_source_uri not in have_copied:
532 relative_path = ResourcePath(file.datastoreRecords.path, forceAbsolute=False)
533 target_uri = determine_destination_for_retrieved_artifact(
534 destination, relative_path, preserve_path, prefix
535 )
536 # Because signed URLs expire, we want to do the transfer
537 # soon after retrieving the URL.
538 target_uri.transfer_from(source_uri, transfer="copy", overwrite=overwrite)
539 have_copied[cleaned_source_uri] = target_uri
540 artifact_map[target_uri] = ArtifactIndexInfo.from_single(file.datastoreRecords, ref.id)
541 else:
542 target_uri = have_copied[cleaned_source_uri]
543 artifact_map[target_uri].append(ref.id)
545 if write_index:
546 index = ZipIndex.from_artifact_map(refs, artifact_map, destination)
547 index.write_index(destination)
549 return artifact_map
551 def retrieve_artifacts_zip(
552 self,
553 refs: Iterable[DatasetRef],
554 destination: ResourcePathExpression,
555 overwrite: bool = True,
556 ) -> ResourcePath:
557 return retrieve_and_zip(refs, destination, self._retrieve_artifacts, overwrite)
559 def retrieveArtifacts(
560 self,
561 refs: Iterable[DatasetRef],
562 destination: ResourcePathExpression,
563 transfer: str = "auto",
564 preserve_path: bool = True,
565 overwrite: bool = False,
566 ) -> list[ResourcePath]:
567 artifact_map = self._retrieve_artifacts(
568 refs,
569 destination,
570 transfer,
571 preserve_path,
572 overwrite,
573 )
574 return list(artifact_map)
576 def exists(
577 self,
578 dataset_ref_or_type: DatasetRef | DatasetType | str,
579 /,
580 data_id: DataId | None = None,
581 *,
582 full_check: bool = True,
583 collections: Any = None,
584 **kwargs: Any,
585 ) -> DatasetExistence:
586 try:
587 response = self._get_file_info(
588 dataset_ref_or_type, dataId=data_id, collections=collections, timespan=None, kwargs=kwargs
589 )
590 except DatasetNotFoundError:
591 return DatasetExistence.UNRECOGNIZED
593 if response.artifact is None:
594 if full_check:
595 return DatasetExistence.RECORDED
596 else:
597 return DatasetExistence.RECORDED | DatasetExistence._ASSUMED
599 if full_check:
600 for file in response.artifact.file_info:
601 if not ResourcePath(str(file.url)).exists():
602 return DatasetExistence.RECORDED | DatasetExistence.DATASTORE
603 return DatasetExistence.VERIFIED
604 else:
605 return DatasetExistence.KNOWN
607 def _exists_many(
608 self,
609 refs: Iterable[DatasetRef],
610 /,
611 *,
612 full_check: bool = True,
613 ) -> dict[DatasetRef, DatasetExistence]:
614 return {ref: self.exists(ref, full_check=full_check) for ref in refs}
616 def removeRuns(
617 self,
618 names: Iterable[str],
619 unstore: bool | type[_DeprecatedDefault] = _DeprecatedDefault,
620 *,
621 unlink_from_chains: bool = False,
622 ) -> None:
623 # Docstring inherited.
624 raise NotImplementedError()
626 def ingest(
627 self,
628 *datasets: FileDataset,
629 transfer: str | None = "auto",
630 record_validation_info: bool = True,
631 skip_existing: bool = False,
632 ) -> None:
633 # Docstring inherited.
634 raise NotImplementedError()
636 def ingest_zip(
637 self,
638 zip_file: ResourcePathExpression,
639 transfer: str = "auto",
640 *,
641 transfer_dimensions: bool = False,
642 dry_run: bool = False,
643 skip_existing: bool = False,
644 ) -> None:
645 # Docstring inherited.
646 raise NotImplementedError()
648 def export(
649 self,
650 *,
651 directory: str | None = None,
652 filename: str | None = None,
653 format: str | None = None,
654 transfer: str | None = None,
655 ) -> AbstractContextManager[RepoExportContext]:
656 # Docstring inherited.
657 raise NotImplementedError()
659 def import_(
660 self,
661 *,
662 directory: ResourcePathExpression | None = None,
663 filename: ResourcePathExpression | TextIO | None = None,
664 format: str | None = None,
665 transfer: str | None = None,
666 skip_dimensions: set | None = None,
667 record_validation_info: bool = True,
668 without_datastore: bool = False,
669 ) -> None:
670 # Docstring inherited.
671 raise NotImplementedError()
673 def transfer_dimension_records_from(
674 self, source_butler: LimitedButler | Butler, source_refs: Iterable[DatasetRef | DataCoordinate]
675 ) -> None:
676 # Docstring inherited.
677 raise NotImplementedError()
679 def transfer_from(
680 self,
681 source_butler: LimitedButler,
682 source_refs: Iterable[DatasetRef],
683 transfer: str = "auto",
684 skip_missing: bool = True,
685 register_dataset_types: bool = False,
686 transfer_dimensions: bool = False,
687 dry_run: bool = False,
688 ) -> Collection[DatasetRef]:
689 # Docstring inherited.
690 raise NotImplementedError()
692 def validateConfiguration(
693 self,
694 logFailures: bool = False,
695 datasetTypeNames: Iterable[str] | None = None,
696 ignore: Iterable[str] | None = None,
697 ) -> None:
698 # Docstring inherited.
699 raise NotImplementedError()
701 @property
702 def run(self) -> str | None:
703 # Docstring inherited.
704 return self._registry_defaults.get().run
706 @property
707 def registry(self) -> Registry:
708 return self._registry
710 @contextmanager
711 def query(self) -> Iterator[Query]:
712 driver = RemoteQueryDriver(self, self._connection)
713 with driver:
714 query = Query(driver)
715 yield query
717 @contextmanager
718 def _query_all_datasets_by_page(
719 self, args: QueryAllDatasetsParameters
720 ) -> Iterator[Iterator[list[DatasetRef]]]:
721 universe = self.dimensions
723 request = QueryAllDatasetsRequestModel(
724 collections=self._normalize_collections(args.collections),
725 name=[normalize_dataset_type_name(name) for name in args.name],
726 find_first=args.find_first,
727 data_id=simplify_dataId(args.data_id, args.kwargs),
728 default_data_id=self._serialize_default_data_id(),
729 where=args.where,
730 bind={k: make_column_literal(v) for k, v in args.bind.items()},
731 limit=args.limit,
732 with_dimension_records=args.with_dimension_records,
733 )
734 with self._connection.post_with_stream_response("query/all_datasets", request) as response:
735 pages = read_query_results(response)
736 yield (convert_dataset_ref_results(page, universe) for page in pages)
738 def pruneDatasets(
739 self,
740 refs: Iterable[DatasetRef],
741 *,
742 disassociate: bool = True,
743 unstore: bool = False,
744 tags: Iterable[str] = (),
745 purge: bool = False,
746 ) -> None:
747 # Docstring inherited.
748 raise NotImplementedError()
750 def _normalize_collections(self, collections: CollectionArgType | None) -> CollectionList:
751 """Convert the ``collections`` parameter in the format used by Butler
752 methods to a standardized format for the REST API.
753 """
754 if collections is None:
755 if not self.collections.defaults:
756 raise NoDefaultCollectionError(
757 "No collections provided, and no defaults from butler construction."
758 )
759 collections = self.collections.defaults
760 return convert_collection_arg_to_glob_string_list(collections)
762 def clone(
763 self,
764 *,
765 collections: CollectionArgType | None | EllipsisType = ...,
766 run: str | None | EllipsisType = ...,
767 inferDefaults: bool | EllipsisType = ...,
768 dataId: dict[str, str] | EllipsisType = ...,
769 metrics: ButlerMetrics | None = None,
770 ) -> RemoteButler:
771 defaults = self._registry_defaults.get().clone(collections, run, inferDefaults, dataId)
772 return RemoteButler(
773 connection=self._connection, cache=self._cache, defaults=defaults, metrics=metrics
774 )
776 def close(self) -> None:
777 pass
779 def _expand_data_ids(self, data_ids: Iterable[DataCoordinate]) -> list[DataCoordinate]:
780 return expand_data_ids(data_ids, self.dimensions, self.query, None)
782 @property
783 def _file_transfer_source(self) -> RemoteFileTransferSource:
784 return RemoteFileTransferSource(self._connection)
786 def __str__(self) -> str:
787 return f"RemoteButler({self._connection.server_url})"
789 def _serialize_default_data_id(self) -> SerializedDataId:
790 """Convert the default data ID to a serializable format."""
791 # In an ideal world, the default data ID would just get combined with
792 # the rest of the data ID on the client side instead of being sent
793 # separately to the server. Unfortunately, that requires knowledge of
794 # the DatasetType's dimensions which we don't always have available on
795 # the client. Data ID values can be specified indirectly by "implied"
796 # dimensions, but knowing what things are implied depends on what the
797 # required dimensions are.
799 return self._registry_defaults.get().dataId.to_simple(minimal=True).dataId
802def _to_file_payload(get_file_response: GetFileResponseModel) -> FileInfoPayload:
803 if get_file_response.artifact is None:
804 ref = get_file_response.dataset_ref
805 raise DatasetNotFoundError(f"Dataset is known, but artifact is not available. (datasetId='{ref.id}')")
807 return get_file_response.artifact
810def _to_uuid_string(id: uuid.UUID | str) -> str:
811 """Convert a UUID, or string parseable as a UUID, into a string formatted
812 like '1481269e-4c8d-4696-bcca-d1b4c9005d06'
813 """
814 return str(uuid.UUID(str(id)))
817class _RemoteButlerCacheData:
818 def __init__(self) -> None:
819 self.dimensions: DimensionUniverse | None = None
820 self.dataset_types: dict[str, DatasetType] = {}
823class RemoteButlerCache(LockedObject[_RemoteButlerCacheData]):
824 def __init__(self) -> None:
825 super().__init__(_RemoteButlerCacheData())