|
5 | 5 | from collections import defaultdict
|
6 | 6 |
|
7 | 7 | import polars as pl
|
| 8 | +import zarr |
| 9 | + |
| 10 | +__all__ = [ |
| 11 | + 'OPTIONS', |
| 12 | + 'set_options', |
| 13 | + '_set_async_flag', |
| 14 | +] |
8 | 15 |
|
9 | 16 |
|
10 | 17 | def show_versions(file=sys.stdout): # pragma: no cover
|
@@ -57,6 +64,59 @@ def show_versions(file=sys.stdout): # pragma: no cover
|
57 | 64 | print(f'{k}: {stat}', file=file)
|
58 | 65 |
|
59 | 66 |
|
| 67 | +def _zarr_async() -> bool: |
| 68 | + """ |
| 69 | + Zarr went all async in version 3.0.0. This sets the async flag based on |
| 70 | + the zarr version in storage options |
| 71 | + """ |
| 72 | + |
| 73 | + return int(zarr.__version__.split('.')[0]) > 2 |
| 74 | + |
| 75 | + |
| 76 | +def _set_async_flag(data_format: str, xarray_open_kwargs: dict) -> dict: |
| 77 | + """ |
| 78 | + If we have the data format set to either zarr2 or zarr3, the async flag in |
| 79 | + `xarray_open_kwargs['storage_options']['remote_opetions']` is constrained to |
| 80 | + be either False or True, respectively. |
| 81 | +
|
| 82 | + Parameters |
| 83 | + ---------- |
| 84 | + data_format : str |
| 85 | +
|
| 86 | + xarray_open_kwargs : dict |
| 87 | + The xarray open kwargs dictionary that may contain storage options. |
| 88 | + Returns |
| 89 | + ------- |
| 90 | + dict |
| 91 | + The updated xarray open kwargs with the async flag set appropriately. |
| 92 | + """ |
| 93 | + if data_format not in {'zarr2', 'zarr3'}: |
| 94 | + return xarray_open_kwargs |
| 95 | + |
| 96 | + storage_opts_template = { |
| 97 | + 'backend_kwargs': {'storage_options': {'remote_options': {'asynchronous': _zarr_async()}}} |
| 98 | + } |
| 99 | + if ( |
| 100 | + xarray_open_kwargs.get('backend_kwargs', {}) |
| 101 | + .get('storage_options', {}) |
| 102 | + .get('remote_options', None) |
| 103 | + is not None |
| 104 | + ): |
| 105 | + xarray_open_kwargs['backend_kwargs']['storage_options']['remote_options'][ |
| 106 | + 'asynchronous' |
| 107 | + ] = _zarr_async() |
| 108 | + elif xarray_open_kwargs.get('backend_kwargs', {}).get('storage_options', None) is not None: |
| 109 | + xarray_open_kwargs['backend_kwargs']['storage_options'] = storage_opts_template[ |
| 110 | + 'backend_kwargs' |
| 111 | + ]['storage_options'] |
| 112 | + elif xarray_open_kwargs.get('backend_kwargs', None) is not None: |
| 113 | + xarray_open_kwargs['backend_kwargs'] = storage_opts_template['backend_kwargs'] |
| 114 | + else: |
| 115 | + xarray_open_kwargs = storage_opts_template |
| 116 | + |
| 117 | + return xarray_open_kwargs |
| 118 | + |
| 119 | + |
60 | 120 | OPTIONS = {
|
61 | 121 | 'attrs_prefix': 'intake_esm_attrs',
|
62 | 122 | 'dataset_key': 'intake_esm_dataset_key',
|
|
0 commit comments