|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import asyncio |
4 | | -from typing import TYPE_CHECKING |
| 4 | +import json |
| 5 | +from enum import Enum |
| 6 | +from itertools import zip_longest |
| 7 | +from typing import TYPE_CHECKING, Final, NamedTuple |
5 | 8 |
|
6 | 9 | from zarr.abc.store import set_or_delete |
| 10 | +from zarr.core._json import buffer_to_json_object |
7 | 11 | from zarr.core.buffer.core import default_buffer_prototype |
| 12 | +from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype |
8 | 13 | from zarr.errors import ContainsArrayError |
9 | 14 | from zarr.storage._common import StorePath, ensure_no_existing_node |
10 | 15 |
|
11 | 16 | if TYPE_CHECKING: |
12 | | - from zarr.core.common import ZarrFormat |
| 17 | + from collections.abc import Iterator, Mapping |
| 18 | + |
| 19 | + from zarr.core.buffer import Buffer |
| 20 | + from zarr.core.common import JSON, ZarrFormat |
13 | 21 | from zarr.core.group import GroupMetadata |
14 | 22 | from zarr.core.metadata import ArrayMetadata |
15 | 23 |
|
16 | 24 |
|
| 25 | +class _Absent(Enum): |
| 26 | + ABSENT = "absent" |
| 27 | + |
| 28 | + |
| 29 | +ABSENT: Final = _Absent.ABSENT |
| 30 | +"""Where a `DocumentChange` has no value: the document, member or element is not there.""" |
| 31 | + |
| 32 | + |
| 33 | +class DocumentChange(NamedTuple): |
| 34 | + """A JSON value that differs between a node's stored metadata documents and the |
| 35 | + documents its metadata would store.""" |
| 36 | + |
| 37 | + path: tuple[str | int, ...] |
| 38 | + """Where the value is: the document's key (e.g. `.zarray`), then the object members |
| 39 | + and array indices within it.""" |
| 40 | + stored: JSON | _Absent |
| 41 | + new: JSON | _Absent |
| 42 | + |
| 43 | + |
| 44 | +def diff_documents( |
| 45 | + stored: Mapping[str, JSON], new: Mapping[str, JSON] |
| 46 | +) -> tuple[DocumentChange, ...]: |
| 47 | + """What differs between a node's stored metadata documents and the documents its |
| 48 | + metadata would store, each keyed by its store key (a document missing from `stored` |
| 49 | + is not stored). Empty if they are identical. |
| 50 | +
|
| 51 | + Objects and arrays are compared member by member, so a change is the smallest value |
| 52 | + that differs; any other two values are identical only if their JSON encodings are, so |
| 53 | + `true` differs from `1` and `1.0` from `1`. |
| 54 | + """ |
| 55 | + return tuple(_diff((), stored, new)) |
| 56 | + |
| 57 | + |
| 58 | +def _diff( |
| 59 | + path: tuple[str | int, ...], stored: JSON | _Absent, new: JSON | _Absent |
| 60 | +) -> Iterator[DocumentChange]: |
| 61 | + match stored, new: |
| 62 | + case dict(), dict(): |
| 63 | + for key in dict.fromkeys([*stored, *new]): |
| 64 | + yield from _diff((*path, key), stored.get(key, ABSENT), new.get(key, ABSENT)) |
| 65 | + case list(), list(): |
| 66 | + for index, pair in enumerate(zip_longest(stored, new, fillvalue=ABSENT)): |
| 67 | + yield from _diff((*path, index), *pair) |
| 68 | + case _ if ABSENT in (stored, new) or json.dumps(stored) != json.dumps(new): |
| 69 | + yield DocumentChange(path, stored, new) |
| 70 | + |
| 71 | + |
| 72 | +async def store_documents(store_path: StorePath, documents: Mapping[str, Buffer]) -> None: |
| 73 | + """Store metadata documents encoded by `to_buffer_dict` under `store_path`.""" |
| 74 | + await asyncio.gather( |
| 75 | + *(set_or_delete(store_path / key, value) for key, value in documents.items()) |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +async def upsert_metadata( |
| 80 | + store_path: StorePath, metadata: ArrayMetadata | GroupMetadata |
| 81 | +) -> tuple[DocumentChange, ...]: |
| 82 | + """Store the documents of `metadata` under `store_path` that differ from the stored |
| 83 | + ones, and return how they differed (see `diff_documents`): empty if nothing was |
| 84 | + stored. |
| 85 | +
|
| 86 | + The documents are encoded before the store is read, so metadata that cannot be |
| 87 | + stored fails with the store untouched. |
| 88 | + """ |
| 89 | + documents = metadata.to_buffer_dict(default_buffer_prototype()) |
| 90 | + stored = await asyncio.gather( |
| 91 | + *((store_path / key).get(prototype=cpu_buffer_prototype) for key in documents) |
| 92 | + ) |
| 93 | + changes = diff_documents( |
| 94 | + { |
| 95 | + key: buffer_to_json_object(buf) |
| 96 | + for key, buf in zip(documents, stored, strict=True) |
| 97 | + if buf is not None |
| 98 | + }, |
| 99 | + {key: buffer_to_json_object(buf) for key, buf in documents.items()}, |
| 100 | + ) |
| 101 | + changed = {change.path[0] for change in changes} |
| 102 | + await store_documents(store_path, {k: v for k, v in documents.items() if k in changed}) |
| 103 | + return changes |
| 104 | + |
| 105 | + |
17 | 106 | def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str, GroupMetadata]: |
18 | 107 | from zarr.core.group import GroupMetadata |
19 | 108 |
|
@@ -52,7 +141,7 @@ async def save_metadata( |
52 | 141 | ValueError |
53 | 142 | """ |
54 | 143 | to_save = metadata.to_buffer_dict(default_buffer_prototype()) |
55 | | - set_awaitables = [set_or_delete(store_path / key, value) for key, value in to_save.items()] |
| 144 | + set_awaitables = [store_documents(store_path, to_save)] |
56 | 145 |
|
57 | 146 | if ensure_parents: |
58 | 147 | # To enable zarr.create(store, path="a/b/c"), we need to create all the intermediate groups. |
|
0 commit comments