-
-
Notifications
You must be signed in to change notification settings - Fork 290
/
store.py
451 lines (371 loc) · 12.8 KB
/
store.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
from __future__ import annotations
from abc import ABC, abstractmethod
from asyncio import gather
from itertools import starmap
from typing import TYPE_CHECKING, Protocol, runtime_checkable
from zarr.core.buffer.core import default_buffer_prototype
from zarr.core.common import concurrent_map
from zarr.core.config import config
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, AsyncIterator, Iterable
from types import TracebackType
from typing import Any, Self, TypeAlias
from zarr.core.buffer import Buffer, BufferPrototype
from zarr.core.common import BytesLike
__all__ = ["ByteGetter", "ByteSetter", "Store", "set_or_delete"]
ByteRangeRequest: TypeAlias = tuple[int | None, int | None]
class Store(ABC):
"""
Abstract base class for Zarr stores.
"""
_read_only: bool
_is_open: bool
def __init__(self, *, read_only: bool = False) -> None:
self._is_open = False
self._read_only = read_only
@classmethod
async def open(cls, *args: Any, **kwargs: Any) -> Self:
"""
Create and open the store.
Parameters
----------
*args : Any
Positional arguments to pass to the store constructor.
**kwargs : Any
Keyword arguments to pass to the store constructor.
Returns
-------
Store
The opened store instance.
"""
store = cls(*args, **kwargs)
await store._open()
return store
def __enter__(self) -> Self:
"""Enter a context manager that will close the store upon exiting."""
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
"""Close the store."""
self.close()
async def _open(self) -> None:
"""
Open the store.
Raises
------
ValueError
If the store is already open.
"""
if self._is_open:
raise ValueError("store is already open")
self._is_open = True
async def _ensure_open(self) -> None:
"""Open the store if it is not already open."""
if not self._is_open:
await self._open()
async def is_empty(self, prefix: str) -> bool:
"""
Check if the directory is empty.
Parameters
----------
prefix : str
Prefix of keys to check.
Returns
-------
bool
True if the store is empty, False otherwise.
"""
if not self.supports_listing:
raise NotImplementedError
if prefix != "" and not prefix.endswith("/"):
prefix += "/"
async for _ in self.list_prefix(prefix):
return False
return True
async def clear(self) -> None:
"""
Clear the store.
Remove all keys and values from the store.
"""
if not self.supports_deletes:
raise NotImplementedError
if not self.supports_listing:
raise NotImplementedError
self._check_writable()
await self.delete_dir("")
@property
def read_only(self) -> bool:
"""Is the store read-only?"""
return self._read_only
def _check_writable(self) -> None:
"""Raise an exception if the store is not writable."""
if self.read_only:
raise ValueError("store was opened in read-only mode and does not support writing")
@abstractmethod
def __eq__(self, value: object) -> bool:
"""Equality comparison."""
...
@abstractmethod
async def get(
self,
key: str,
prototype: BufferPrototype,
byte_range: ByteRangeRequest | None = None,
) -> Buffer | None:
"""Retrieve the value associated with a given key.
Parameters
----------
key : str
byte_range : tuple[int | None, int | None], optional
Returns
-------
Buffer
"""
...
@abstractmethod
async def get_partial_values(
self,
prototype: BufferPrototype,
key_ranges: Iterable[tuple[str, ByteRangeRequest]],
) -> list[Buffer | None]:
"""Retrieve possibly partial values from given key_ranges.
Parameters
----------
key_ranges : Iterable[tuple[str, tuple[int | None, int | None]]]
Ordered set of key, range pairs, a key may occur multiple times with different ranges
Returns
-------
list of values, in the order of the key_ranges, may contain null/none for missing keys
"""
...
@abstractmethod
async def exists(self, key: str) -> bool:
"""Check if a key exists in the store.
Parameters
----------
key : str
Returns
-------
bool
"""
...
@property
@abstractmethod
def supports_writes(self) -> bool:
"""Does the store support writes?"""
...
@abstractmethod
async def set(self, key: str, value: Buffer) -> None:
"""Store a (key, value) pair.
Parameters
----------
key : str
value : Buffer
"""
...
async def set_if_not_exists(self, key: str, value: Buffer) -> None:
"""
Store a key to ``value`` if the key is not already present.
Parameters
----------
key : str
value : Buffer
"""
# Note for implementers: the default implementation provided here
# is not safe for concurrent writers. There's a race condition between
# the `exists` check and the `set` where another writer could set some
# value at `key` or delete `key`.
if not await self.exists(key):
await self.set(key, value)
async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None:
"""
Insert multiple (key, value) pairs into storage.
"""
await gather(*starmap(self.set, values))
@property
@abstractmethod
def supports_deletes(self) -> bool:
"""Does the store support deletes?"""
...
@abstractmethod
async def delete(self, key: str) -> None:
"""Remove a key from the store
Parameters
----------
key : str
"""
...
@property
@abstractmethod
def supports_partial_writes(self) -> bool:
"""Does the store support partial writes?"""
...
@abstractmethod
async def set_partial_values(
self, key_start_values: Iterable[tuple[str, int, BytesLike]]
) -> None:
"""Store values at a given key, starting at byte range_start.
Parameters
----------
key_start_values : list[tuple[str, int, BytesLike]]
set of key, range_start, values triples, a key may occur multiple times with different
range_starts, range_starts (considering the length of the respective values) must not
specify overlapping ranges for the same key
"""
...
@property
@abstractmethod
def supports_listing(self) -> bool:
"""Does the store support listing?"""
...
@abstractmethod
def list(self) -> AsyncIterator[str]:
"""Retrieve all keys in the store.
Returns
-------
AsyncIterator[str]
"""
# This method should be async, like overridden methods in child classes.
# However, that's not straightforward:
# https://stackoverflow.com/questions/68905848
@abstractmethod
def list_prefix(self, prefix: str) -> AsyncIterator[str]:
"""
Retrieve all keys in the store that begin with a given prefix. Keys are returned relative
to the root of the store.
Parameters
----------
prefix : str
Returns
-------
AsyncIterator[str]
"""
# This method should be async, like overridden methods in child classes.
# However, that's not straightforward:
# https://stackoverflow.com/questions/68905848
@abstractmethod
def list_dir(self, prefix: str) -> AsyncIterator[str]:
"""
Retrieve all keys and prefixes with a given prefix and which do not contain the character
“/” after the given prefix.
Parameters
----------
prefix : str
Returns
-------
AsyncIterator[str]
"""
# This method should be async, like overridden methods in child classes.
# However, that's not straightforward:
# https://stackoverflow.com/questions/68905848
async def delete_dir(self, prefix: str) -> None:
"""
Remove all keys and prefixes in the store that begin with a given prefix.
"""
if not self.supports_deletes:
raise NotImplementedError
if not self.supports_listing:
raise NotImplementedError
self._check_writable()
if prefix != "" and not prefix.endswith("/"):
prefix += "/"
async for key in self.list_prefix(prefix):
await self.delete(key)
def close(self) -> None:
"""Close the store."""
self._is_open = False
async def _get_many(
self, requests: Iterable[tuple[str, BufferPrototype, ByteRangeRequest | None]]
) -> AsyncGenerator[tuple[str, Buffer | None], None]:
"""
Retrieve a collection of objects from storage. In general this method does not guarantee
that objects will be retrieved in the order in which they were requested, so this method
yields tuple[str, Buffer | None] instead of just Buffer | None
"""
for req in requests:
yield (req[0], await self.get(*req))
async def getsize(self, key: str) -> int:
"""
Return the size, in bytes, of a value in a Store.
Parameters
----------
key : str
Returns
-------
nbytes : int
The size of the value (in bytes).
Raises
------
FileNotFoundError
When the given key does not exist in the store.
"""
# Note to implementers: this default implementation is very inefficient since
# it requires reading the entire object. Many systems will have ways to get the
# size of an object without reading it.
value = await self.get(key, prototype=default_buffer_prototype())
if value is None:
raise FileNotFoundError(key)
return len(value)
async def getsize_prefix(self, prefix: str) -> int:
"""
Return the size, in bytes, of all values under a prefix.
Parameters
----------
prefix : str
The prefix of the directory to measure.
Returns
-------
nbytes : int
The sum of the sizes of the values in the directory (in bytes).
See Also
--------
zarr.Array.nbytes_stored
Store.getsize
Notes
-----
``getsize_prefix`` is just provided as a potentially faster alternative to
listing all the keys under a prefix calling :meth:`Store.getsize` on each.
In general, ``prefix`` should be the path of an Array or Group in the Store.
Implementations may differ on the behavior when some other ``prefix``
is provided.
"""
# TODO: Overlap listing keys with getsize calls.
# Currently, we load the list of keys into memory and only then move
# on to getting sizes. Ideally we would overlap those two, which should
# improve tail latency and might reduce memory pressure (since not all keys
# would be in memory at once).
keys = [(x,) async for x in self.list_prefix(prefix)]
limit = config.get("async.concurrency")
sizes = await concurrent_map(keys, self.getsize, limit=limit)
return sum(sizes)
@runtime_checkable
class ByteGetter(Protocol):
async def get(
self, prototype: BufferPrototype, byte_range: ByteRangeRequest | None = None
) -> Buffer | None: ...
@runtime_checkable
class ByteSetter(Protocol):
async def get(
self, prototype: BufferPrototype, byte_range: ByteRangeRequest | None = None
) -> Buffer | None: ...
async def set(self, value: Buffer, byte_range: ByteRangeRequest | None = None) -> None: ...
async def delete(self) -> None: ...
async def set_if_not_exists(self, default: Buffer) -> None: ...
async def set_or_delete(byte_setter: ByteSetter, value: Buffer | None) -> None:
"""Set or delete a value in a byte setter
Parameters
----------
byte_setter : ByteSetter
value : Buffer | None
Notes
-----
If value is None, the key will be deleted.
"""
if value is None:
await byte_setter.delete()
else:
await byte_setter.set(value)