Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/zarr-metadata/changes/4610.removal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`to_key_value` takes a writer instead of an `indent` keyword. The writer is a `JSONWriter`, a frozen dataclass exported from `zarr_metadata` and `zarr_metadata.model` that owns how a document becomes JSON bytes: its settings are `indent`, `sort_keys`, `ensure_ascii` and `trailing_newline`, and its `encode` method does the writing. `to_key_value` also accepts a mapping of the settings (`JSONWriterSchema`), so `to_key_value(indent=2)` becomes `to_key_value({"indent": 2})`, with no import. The defaults are those of `json.dumps`, which the models already used, so a bare `to_key_value()` writes the same bytes as before. A setting that `json.dumps` would accept but misread, such as `indent=True`, a negative indent or a non-whitespace string indent, raises, and so does a mapping key that is not a setting.
28 changes: 28 additions & 0 deletions packages/zarr-metadata/docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,34 @@ To change a model, use one of these methods:
must claim what this context left unclaimed and contradict nothing.
Otherwise it raises `ScopeConflictError`.

## Writing store bytes

`to_key_value` writes a model's document as the JSON bytes a store holds.
A `JSONWriter` decides how those bytes are spelled: `indent`, `sort_keys`,
`ensure_ascii` and `trailing_newline`. Its defaults are those of
`json.dumps`. `to_key_value` takes a `JSONWriter` or a mapping of its
settings, so you do not need to import the class to change one:

```python test="true" session="models"
from zarr_metadata.model import JSONWriter, ZarrV3GroupMetadata

group = ZarrV3GroupMetadata.create_default(attributes={"b": 1, "a": 2})
print(group.to_key_value({"indent": 2, "sort_keys": True})["zarr.json"].decode())
# {
# "attributes": {
# "a": 2,
# "b": 1
# },
# "node_type": "group",
# "zarr_format": 3
# }
assert group.to_key_value({"indent": 2}) == group.to_key_value(JSONWriter(indent=2))
```

A mapping with a key that is not a setting raises `TypeError`, so a
misspelled setting is not ignored. `JSONWriter.from_dict` turns a mapping
into a writer, and `to_dict` turns a writer back into a mapping.

## Extra fields

An extra field is a top-level member that the spec does not define. The
Expand Down
6 changes: 6 additions & 0 deletions packages/zarr-metadata/src/zarr_metadata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@

from zarr_metadata.model import (
UNSET,
JSONWriter,
JSONWriterLike,
JSONWriterSchema,
ZarrV2ArrayMetadata,
ZarrV2ArrayMetadataUpdate,
ZarrV2ConsolidatedMetadata,
Expand Down Expand Up @@ -363,6 +366,9 @@
"Int64DataTypeName",
"Int64FillValue",
"JSONValue",
"JSONWriter",
"JSONWriterLike",
"JSONWriterSchema",
"MetadataValidationError",
"NumpyDatetime64DataTypeName",
"NumpyDatetime64FillValue",
Expand Down
11 changes: 9 additions & 2 deletions packages/zarr-metadata/src/zarr_metadata/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@
invalid model is never built. `to_json` returns the document as written.
`update` reads new members in the model's own scope. `with_context` and
`refined_in` read the document in another scope. `to_key_value` writes
the model as it is. A v3 group reads its `consolidated_metadata` as an
envelope and does not read the documents it lists, because consolidated
the model as it is, with a `JSONWriter`, or a mapping of its settings, deciding how
the bytes are spelled (indentation, key order, ASCII escaping, trailing
newline); the default is that of `json.dumps`. A v3 group reads its
`consolidated_metadata` as an envelope and does not read the documents
it lists, because consolidated
metadata is a convention of the reference implementation, not core
metadata. `ZarrV3ConsolidatedMetadata` and
`read_consolidated_metadata_v3` read those documents. The model also
Expand Down Expand Up @@ -98,6 +101,7 @@
read_node_metadata_v3,
read_openable_node_metadata_v3,
)
from zarr_metadata.model._json_writer import JSONWriter, JSONWriterLike, JSONWriterSchema
from zarr_metadata.model._repair import (
Repair,
RepairKind,
Expand All @@ -122,6 +126,9 @@

__all__ = [
"UNSET",
"JSONWriter",
"JSONWriterLike",
"JSONWriterSchema",
"Repair",
"RepairKind",
"ZarrV2ArrayMetadata",
Expand Down
13 changes: 6 additions & 7 deletions packages/zarr-metadata/src/zarr_metadata/model/_array_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@
)
from zarr_metadata.definition._scope import ScopeConflictError, claims_of
from zarr_metadata.definition._scope import refines as refines_declaration
from zarr_metadata.model._json_writer import DEFAULT_JSON_WRITER, JSONWriter, JSONWriterLike
from zarr_metadata.model._keyed import Keyed
from zarr_metadata.model._shared import (
StoreKey,
attributes_of,
check_literal,
dimension_lengths,
dump_store_json,
load_store_json,
located_conflicts,
member_changes,
Expand Down Expand Up @@ -594,17 +594,16 @@ def to_json(self) -> ZarrV2ArrayMetadataJSON:
return cast("ZarrV2ArrayMetadataJSON", copied(self._document))

def to_key_value(
self, *, indent: int | str | None = None
self, writer: JSONWriterLike = DEFAULT_JSON_WRITER
) -> Mapping[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]:
"""The document as a store holds it: `.zarray` without the attributes, and `.zattrs` with the attributes when they are set, even if empty."""
"""The document as a store holds it, spelled by `writer`, a `JSONWriter` or a mapping of its settings: `.zarray` without the attributes, and `.zattrs` with the attributes when they are set, even if empty."""
writes = JSONWriter.from_dict(writer)
zarray = {key: value for key, value in self._document.items() if key != "attributes"}
out: dict[ZarrV2ArrayMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = {
ZARR_V2_ARRAY_METADATA_STORE_KEY: dump_store_json(zarray, indent=indent)
ZARR_V2_ARRAY_METADATA_STORE_KEY: writes.encode(zarray)
}
if "attributes" in self._document:
out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(
self._document["attributes"], indent=indent
)
out[ZARR_V2_ATTRIBUTES_STORE_KEY] = writes.encode(self._document["attributes"])
return out

def __repr__(self) -> str:
Expand Down
9 changes: 5 additions & 4 deletions packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@
)
from zarr_metadata.definition._scope import ScopeConflictError, claims_of
from zarr_metadata.definition._scope import refines as refines_declaration
from zarr_metadata.model._json_writer import DEFAULT_JSON_WRITER, JSONWriter, JSONWriterLike
from zarr_metadata.model._keyed import Keyed
from zarr_metadata.model._shared import (
StoreKey,
attributes_of,
check_literal,
dimension_lengths,
dump_store_json,
load_store_json,
located_conflicts,
member_changes,
Expand Down Expand Up @@ -585,15 +585,16 @@ def to_json(self) -> ZarrV3ArrayMetadataJSON:
return cast("ZarrV3ArrayMetadataJSON", copied(self._document))

def to_key_value(
self, *, indent: int | str | None = None
self, writer: JSONWriterLike = DEFAULT_JSON_WRITER
) -> Mapping[ZarrV3ArrayMetadataStoreKey, bytes]:
"""The document as a store holds it: JSON bytes at `zarr.json`, indented by `indent`.
"""The document as a store holds it: JSON bytes at `zarr.json`, spelled by `writer`, a `JSONWriter` or a mapping of its settings.

`NaN`, `Infinity` and `-Infinity` in `attributes` are written as
bare tokens, as zarr-python writes them. A strict JSON parser
rejects these tokens.
"""
return {ZARR_V3_ARRAY_METADATA_STORE_KEY: dump_store_json(self._document, indent=indent)}
writes = JSONWriter.from_dict(writer)
return {ZARR_V3_ARRAY_METADATA_STORE_KEY: writes.encode(self._document)}

def __repr__(self) -> str:
return f"{type(self).__name__}({self._document!r}, context={self._context!r})"
Expand Down
22 changes: 10 additions & 12 deletions packages/zarr-metadata/src/zarr_metadata/model/_group_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@
read_array_node_v2,
read_array_v2,
)
from zarr_metadata.model._json_writer import DEFAULT_JSON_WRITER, JSONWriter, JSONWriterLike
from zarr_metadata.model._keyed import Keyed
from zarr_metadata.model._shared import (
StoreKey,
check_literal,
dump_store_json,
load_store_json,
located_conflicts,
member_changes,
Expand Down Expand Up @@ -342,17 +342,16 @@ def to_json(self) -> ZarrV2GroupMetadataJSON:
return cast("ZarrV2GroupMetadataJSON", copied(self._document))

def to_key_value(
self, *, indent: int | str | None = None
self, writer: JSONWriterLike = DEFAULT_JSON_WRITER
) -> Mapping[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes]:
"""The document as a store holds it: `.zgroup` without the attributes, and `.zattrs` with the attributes when they are set, even if empty."""
"""The document as a store holds it, spelled by `writer`, a `JSONWriter` or a mapping of its settings: `.zgroup` without the attributes, and `.zattrs` with the attributes when they are set, even if empty."""
writes = JSONWriter.from_dict(writer)
zgroup = {key: value for key, value in self._document.items() if key != "attributes"}
out: dict[ZarrV2GroupMetadataStoreKey | ZarrV2AttributesStoreKey, bytes] = {
ZARR_V2_GROUP_METADATA_STORE_KEY: dump_store_json(zgroup, indent=indent)
ZARR_V2_GROUP_METADATA_STORE_KEY: writes.encode(zgroup)
}
if "attributes" in self._document:
out[ZARR_V2_ATTRIBUTES_STORE_KEY] = dump_store_json(
self._document["attributes"], indent=indent
)
out[ZARR_V2_ATTRIBUTES_STORE_KEY] = writes.encode(self._document["attributes"])
return out

def __repr__(self) -> str:
Expand Down Expand Up @@ -550,12 +549,11 @@ def to_json(self) -> dict[str, JSONValue]:
return cast("dict[str, JSONValue]", copied(self._document))

def to_key_value(
self, *, indent: int | str | None = None
self, writer: JSONWriterLike = DEFAULT_JSON_WRITER
) -> Mapping[ZarrV2ConsolidatedMetadataStoreKey, bytes]:
"""The document as a store holds it: JSON bytes at `.zmetadata`, indented by `indent`."""
return {
ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: dump_store_json(self._document, indent=indent)
}
"""The document as a store holds it: JSON bytes at `.zmetadata`, spelled by `writer`, a `JSONWriter` or a mapping of its settings."""
writes = JSONWriter.from_dict(writer)
return {ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY: writes.encode(self._document)}

def __repr__(self) -> str:
return f"{type(self).__name__}({self._document!r}, context={self._context!r})"
Expand Down
9 changes: 5 additions & 4 deletions packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@
read_extra_fields_v3,
waived_members,
)
from zarr_metadata.model._json_writer import DEFAULT_JSON_WRITER, JSONWriter, JSONWriterLike
from zarr_metadata.model._keyed import Keyed
from zarr_metadata.model._shared import (
StoreKey,
attributes_of,
check_literal,
dump_store_json,
load_store_json,
located_conflicts,
member_changes,
Expand Down Expand Up @@ -262,16 +262,17 @@ def to_json(self) -> ZarrV3GroupMetadataJSON:
return cast("ZarrV3GroupMetadataJSON", copied(self._document))

def to_key_value(
self, *, indent: int | str | None = None
self, writer: JSONWriterLike = DEFAULT_JSON_WRITER
) -> Mapping[ZarrV3GroupMetadataStoreKey, bytes]:
"""The document as a store holds it: JSON bytes at `zarr.json`, indented by `indent`.
"""The document as a store holds it: JSON bytes at `zarr.json`, spelled by `writer`, a `JSONWriter` or a mapping of its settings.

`NaN`, `Infinity` and `-Infinity` in `attributes`, or in the
documents the consolidated metadata lists, are written as bare
tokens, as zarr-python writes them. A strict JSON parser rejects
these tokens.
"""
return {ZARR_V3_GROUP_METADATA_STORE_KEY: dump_store_json(self._document, indent=indent)}
writes = JSONWriter.from_dict(writer)
return {ZARR_V3_GROUP_METADATA_STORE_KEY: writes.encode(self._document)}

def __repr__(self) -> str:
return f"{type(self).__name__}({self._document!r}, context={self._context!r})"
Expand Down
143 changes: 143 additions & 0 deletions packages/zarr-metadata/src/zarr_metadata/model/_json_writer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""`JSONWriter`, the one object that turns a document into the JSON bytes a store holds."""

from __future__ import annotations

import json
from collections.abc import Mapping
from dataclasses import dataclass, fields
from typing import Final, cast, final

from typing_extensions import TypedDict


class JSONWriterSchema(TypedDict, total=False, closed=True):
"""The settings of a `JSONWriter` as a mapping, each by name and every one optional.

A setting left out takes its default. `to_key_value` accepts this mapping
wherever it accepts a `JSONWriter`, so `model.to_key_value({"indent": 2})`
writes what `model.to_key_value(JSONWriter(indent=2))` writes.
"""

indent: int | str | None
"""`JSONWriter.indent`."""
sort_keys: bool
"""`JSONWriter.sort_keys`."""
ensure_ascii: bool
"""`JSONWriter.ensure_ascii`."""
trailing_newline: bool
"""`JSONWriter.trailing_newline`."""


@final
@dataclass(frozen=True, slots=True, kw_only=True)
class JSONWriter:
"""How a document is written as JSON bytes. `encode` does the writing.

The defaults are those of `json.dumps`: everything on one line, keys
in document order, non-ASCII characters escaped, and no trailing
newline. zarr-python indents its metadata by its `json_indent`
setting, which is 2 unless configured otherwise, so it writes what
`JSONWriter(indent=2)` writes.

A setting that would change the bytes silently is refused when the
writer is built: `json.dumps` reads `True` as an indent of 1 and a
negative indent as 0, and writes a `str` indent verbatim, so one that
is not whitespace would write bytes no JSON reader parses.

The class is final: `encode` is the only way the models write JSON, so
a subclass cannot change how a model is written behind its settings.
"""

indent: int | str | None = None
"""`None` to write one line, an `int` to nest by that many spaces, or a `str` of JSON whitespace (spaces, tabs, line feeds and carriage returns) to nest by that string."""
sort_keys: bool = False
"""Write the keys of every object in sorted order instead of document order."""
ensure_ascii: bool = True
"""Escape every non-ASCII character (`"\\u00b5"`). Off, the bytes are UTF-8 text."""
trailing_newline: bool = False
"""End the bytes with `"\\n"`, for stores whose files are read by line-oriented tools."""

def __post_init__(self) -> None:
indent = cast("object", self.indent)
if isinstance(indent, bool) or not isinstance(indent, int | str | None):
msg = f"indent must be an int, a str or None, got {type(indent).__name__}"
raise TypeError(msg)
if isinstance(indent, int) and indent < 0:
msg = f"indent must not be negative, got {indent}"
raise ValueError(msg)
if isinstance(indent, str) and indent.strip(" \t\n\r") != "":
msg = f"indent must hold only JSON whitespace, got {indent!r}"
raise ValueError(msg)
for name in ("sort_keys", "ensure_ascii", "trailing_newline"):
flag = cast("object", getattr(self, name))
if not isinstance(flag, bool):
msg = f"{name} must be a bool, got {type(flag).__name__}"
raise TypeError(msg)

@classmethod
def from_dict(cls, data: JSONWriterLike) -> JSONWriter:
"""The writer that `data` describes: `data` itself when it is a `JSONWriter`, else one built from its settings.

A key that is not a setting raises `TypeError`, and a value the
setting does not allow raises as the constructor does.
"""
if isinstance(data, JSONWriter):
return data
given = cast("object", data)
if not isinstance(given, Mapping):
msg = f"expected a JSONWriter or a mapping of its settings, got {type(given).__name__}"
raise TypeError(msg)
settings = cast("Mapping[object, object]", given)
unknown = sorted(repr(key) for key in settings if key not in _SETTINGS)
if unknown:
msg = f"unknown JSONWriter setting(s) {', '.join(unknown)}; the settings are {', '.join(_SETTINGS)}"
raise TypeError(msg)
return cls(**cast("JSONWriterSchema", settings))

def to_dict(self) -> JSONWriterSchema:
"""Every setting of this writer by name, so that `JSONWriter.from_dict(writer.to_dict()) == writer`."""
return {
"indent": self.indent,
"sort_keys": self.sort_keys,
"ensure_ascii": self.ensure_ascii,
"trailing_newline": self.trailing_newline,
}

def encode(self, value: object) -> bytes:
"""`value`, a document its reader accepted, as UTF-8 JSON bytes spelled by this writer's settings.

The separators are those of Python's `json` module: `", "` between
items and `": "` after a key, with the item separator becoming
`","` when `indent` is set. A non-finite number is written as a
bare token (`NaN`, `Infinity`, `-Infinity`), as zarr-python writes
attributes; the readers keep such numbers out of every other place
in a document. With `ensure_ascii` off, a lone surrogate (a string
a reader accepts from an escape such as `"\\ud800"`, but which
UTF-8 cannot encode) is still written as that escape.
"""
text = json.dumps(
value,
indent=self.indent,
sort_keys=self.sort_keys,
ensure_ascii=self.ensure_ascii,
allow_nan=True,
)
if self.trailing_newline:
text += "\n"
# `json.dumps` writes non-ASCII characters only inside strings, and the
# only ones UTF-8 cannot encode are lone surrogates, so the replacement
# writes each as the JSON escape `ensure_ascii` would have written.
return text.encode("utf-8", "backslashreplace")


JSONWriterLike = JSONWriter | JSONWriterSchema
"""What `to_key_value` accepts as its writer: a `JSONWriter`, or a `JSONWriterSchema` mapping of the settings to change."""

_SETTINGS: Final = tuple(each.name for each in fields(JSONWriter))
"""The name of each setting, in declaration order."""

DEFAULT_JSON_WRITER: Final = JSONWriter()
"""The writer `to_key_value` uses when given none: the spelling of `json.dumps` with its own defaults."""


__all__ = ["DEFAULT_JSON_WRITER", "JSONWriter", "JSONWriterLike", "JSONWriterSchema"]
Loading
Loading