A compact binary codec derived from a schema's encoded side (Effect's
encoding/SchemaBinary), byte-compatible with Effect's::
from pyfect import schema as S
from pyfect.encoding import schema_binary
codec = schema_binary.to_codec(S.Struct(Person))
data = S.encode_unknown_sync(codec)({"name": "Ada", "age": 36})
person = S.decode_unknown_sync(codec)(data)The default wire format supports compatible schema evolution: a field an old
reader does not know is skipped, and an array of structs is written as a row
run, whose rows declare their shape once and back-reference repeated strings.
fingerprint=True uses positional layouts and an 8-byte layout hash for
smaller frames, and rejects a peer whose encoded layout differs.
to_codec handles exactly one frame per encode and decode. Use parser
for concatenated frames and encoder for a writer with a connection-scoped
string dictionary; encode, decode and duplex are channels.
A datetime is written in milliseconds and a Duration in nanoseconds,
as Effect's are. A datetime cannot hold Effect's dates outside years 1 to
9999: reading one fails.
Re-exports#
- From
pyfect.schema:SchemaError
Values#
| Attribute | Type | Description |
|---|---|---|
int32 | S.Bottom[float] | A 32-bit signed integer written as four little-endian bytes, for values
that regularly need more than four bytes as a varint (hashes, full-range ids);
small values are cheaper as Switching a field between this, |
uint32 | S.Bottom[float] | A 32-bit unsigned integer written as four little-endian bytes. Rejects
non-integers and values outside |
int64 | S.Bottom[int] | A 64-bit signed integer (Effect's |
uint64 | S.Bottom[int] | A 64-bit unsigned integer (Effect's |
DEFAULT_MAX_EXPANDED_SIZE | Literal[67108864] | How many bytes of values the back-references of one frame may name, when
a schema pass walks the decoded value ( |
Types#
| Type | Definition | Description |
|---|---|---|
BytesCodec | type BytesCodec[A] = S.Codec[A, bytes, Any, Any] | A schema read from and written to one binary frame. |
Classes#
Functions#
to_codec#
to_codec[A](schema, /, *, fingerprint=False, max_expanded_size=DEFAULT_MAX_EXPANDED_SIZE) -> BytesCodec[A]schema read from and written to one binary frame, memoized by
schema identity and wire mode.
Repeated values are written once and named again by back-references.
When a schema pass checks the decoded value, max_expanded_size
limits the bytes of the values one frame's back-references name (64 MiB;
None for no limit): past it, decoding fails with a SchemaError.
Bytes carry the layout of the schema that wrote them: read them with that schema or a compatible evolution of it (fingerprint mode needs an identical encoded layout). Most union codecs prefix values with a member selector, so they cannot read bytes written by a member's own codec.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[A, Any, Any, Any] | |
fingerprint | bool = False | |
max_expanded_size | int | None = DEFAULT_MAX_EXPANDED_SIZE |
Returns BytesCodec[A]
def to_codec[A](
schema: S.Codec[A, Any, Any, Any],
/,
*,
fingerprint: bool = False,
max_expanded_size: int | None = DEFAULT_MAX_EXPANDED_SIZE,
) -> BytesCodec[A]:
"""``schema`` read from and written to one binary frame, memoized by
schema identity and wire mode.
Repeated values are written once and named again by back-references.
When a schema pass checks the decoded value, ``max_expanded_size``
limits the bytes of the values one frame's back-references name (64 MiB;
``None`` for no limit): past it, decoding fails with a ``SchemaError``.
Bytes carry the layout of the schema that wrote them: read them with that
schema or a compatible evolution of it (fingerprint mode needs an
identical encoded layout). Most union codecs prefix values with a member
selector, so they cannot read bytes written by a member's own codec."""
return make_codec(schema.__codec__(), fingerprint, max_expanded_size)to_codec_strict#
to_codec_strict[A](schema) -> BytesCodec[A]The default-mode to_codec codec, except that decoding rejects a
struct field, an extra key, a union member or a field wire kind the schema
does not know, instead of skipping it.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[A, Any, Any, Any] |
Returns BytesCodec[A]
def to_codec_strict[A](schema: S.Codec[A, Any, Any, Any], /) -> BytesCodec[A]:
"""The default-mode ``to_codec`` codec, except that decoding rejects a
struct field, an extra key, a union member or a field wire kind the schema
does not know, instead of skipping it."""
return make_strict_codec(schema.__codec__())to_codec_direct#
to_codec_direct[A](schema, /, *, fingerprint=False, max_expanded_size=DEFAULT_MAX_EXPANDED_SIZE) -> BytesCodec[A]to_codec without the schema pass around the binary layer, for
schemas the binary layer validates on its own (any other falls back to
to_codec). It encodes and decodes the same values, but is not a sound
S.is_ guard: only for callers that never guard on it.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[A, Any, Any, Any] | |
fingerprint | bool = False | |
max_expanded_size | int | None = DEFAULT_MAX_EXPANDED_SIZE |
Returns BytesCodec[A]
def to_codec_direct[A](
schema: S.Codec[A, Any, Any, Any],
/,
*,
fingerprint: bool = False,
max_expanded_size: int | None = DEFAULT_MAX_EXPANDED_SIZE,
) -> BytesCodec[A]:
"""``to_codec`` without the schema pass around the binary layer, for
schemas the binary layer validates on its own (any other falls back to
``to_codec``). It encodes and decodes the same values, but is not a sound
``S.is_`` guard: only for callers that never guard on it."""
return make_direct_codec(schema.__codec__(), fingerprint, max_expanded_size)encode_unknown_sync#
encode_unknown_sync(schema, /, *, fingerprint=False, **options) -> Callable[[object], bytes]Encodes one frame without the schema pass to_codec wraps around it
when the binary layer validates the schema on its own; any other schema
falls back to the codec, so checks and transformations still run.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[Any, Any, Any, Any] | |
fingerprint | bool = False | |
options | Unpack[ParseOptions] = {} |
Returns Callable[[object], bytes]
def encode_unknown_sync(
schema: S.Codec[Any, Any, Any, Any],
/,
*,
fingerprint: bool = False,
**options: Unpack[ParseOptions],
) -> Callable[[object], bytes]:
"""Encodes one frame without the schema pass ``to_codec`` wraps around it
when the binary layer validates the schema on its own; any other schema
falls back to the codec, so checks and transformations still run."""
compiled = compile_target(schema)
mode = compile_mode(compiled.layout, fingerprint)
def direct(value: object) -> bytes:
return _rethrown(lambda: _encode.encode_frame(compiled.layout, value, options, mode))
if compiled.exact and not excess_is_error(options):
return direct
fallback = S.encode_unknown_sync(to_codec(schema, fingerprint=fingerprint), **options)
# The binary layer drops excess keys instead of reporting them.
if not compiled.exit_success or excess_is_error(options):
return fallback
def through(value: object) -> bytes:
return direct(value) if is_success_exit(value) else fallback(value)
return throughencode_many_unknown_sync#
encode_many_unknown_sync(schema, /, *, fingerprint=False, **options) -> Callable[[Sequence[object]], bytes]Encodes concatenated frames in one writer pass, with
encode_unknown_sync's direct path and fallback.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[Any, Any, Any, Any] | |
fingerprint | bool = False | |
options | Unpack[ParseOptions] = {} |
Returns Callable[[Sequence[object]], bytes]
def encode_many_unknown_sync(
schema: S.Codec[Any, Any, Any, Any],
/,
*,
fingerprint: bool = False,
**options: Unpack[ParseOptions],
) -> Callable[[Sequence[object]], bytes]:
"""Encodes concatenated frames in one writer pass, with
``encode_unknown_sync``'s direct path and fallback."""
compiled = compile_target(schema)
if not compiled.exact or excess_is_error(options):
encode_one = encode_unknown_sync(schema, fingerprint=fingerprint, **options)
return lambda values: b"".join(map(encode_one, values))
mode = compile_mode(compiled.layout, fingerprint)
def many(values: Sequence[object]) -> bytes:
return _rethrown(lambda: _encode.encode_frames(compiled.layout, values, options, mode))
return manyparser#
parser[A](schema, /, *, fingerprint=False, dictionary=False, max_frame_size=None, max_expanded_size=DEFAULT_MAX_EXPANDED_SIZE, **options) -> Parser[A]A stateful parser of concatenated frames. max_frame_size limits a
buffered frame, and max_expanded_size the values a frame's
back-references name, as in to_codec. With dictionary, frames
share one string dictionary with the encoder that wrote them, and
must be read in order; a schema the binary layer does not fully validate
cannot use it (ValueError).
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[A, Any, Any, Any] | |
fingerprint | bool = False | |
dictionary | bool = False | |
max_frame_size | int | None = None | |
max_expanded_size | int | None = DEFAULT_MAX_EXPANDED_SIZE | |
options | Unpack[ParseOptions] = {} |
Returns Parser[A]
def parser[A](
schema: S.Codec[A, Any, Any, Any],
/,
*,
fingerprint: bool = False,
dictionary: bool = False,
max_frame_size: int | None = None,
max_expanded_size: int | None = DEFAULT_MAX_EXPANDED_SIZE,
**options: Unpack[ParseOptions],
) -> Parser[A]:
"""A stateful parser of concatenated frames. ``max_frame_size`` limits a
buffered frame, and ``max_expanded_size`` the values a frame's
back-references name, as in ``to_codec``. With ``dictionary``, frames
share one string dictionary with the ``encoder`` that wrote them, and
must be read in order; a schema the binary layer does not fully validate
cannot use it (``ValueError``)."""
compiled = compile_target(schema)
decode_target = None if compiled.exact else S.decode_unknown_sync(compiled.target, **options)
def decode_success(value: object) -> object:
assert decode_target is not None
return value if is_success_exit(value) else decode_target(value)
return make_parser(
compiled.layout,
compile_mode(compiled.layout, fingerprint),
options,
max_frame_size,
decode_success if decode_target is not None and compiled.exit_success else decode_target,
_require_dictionary(compiled.exact, dictionary),
None if compiled.exact else max_expanded_size,
)encoder#
encoder(schema, /, *, fingerprint=False, dictionary=False, **options) -> EncoderA writer for one connection. With dictionary, every frame shares
the string dictionary its matching parser rebuilds as it reads them,
so both must come from one schema and the same options.
| Parameter | Type | Description |
|---|---|---|
schema | S.Codec[Any, Any, Any, Any] | |
fingerprint | bool = False | |
dictionary | bool = False | |
options | Unpack[ParseOptions] = {} |
Returns Encoder
def encoder(
schema: S.Codec[Any, Any, Any, Any],
/,
*,
fingerprint: bool = False,
dictionary: bool = False,
**options: Unpack[ParseOptions],
) -> Encoder:
"""A writer for one connection. With ``dictionary``, every frame shares
the string dictionary its matching ``parser`` rebuilds as it reads them,
so both must come from one schema and the same options."""
compiled = compile_target(schema)
if not _require_dictionary(compiled.exact, dictionary):
return Encoder(
encode_unknown_sync(schema, fingerprint=fingerprint, **options),
encode_many_unknown_sync(schema, fingerprint=fingerprint, **options),
)
mode = compile_mode(compiled.layout, fingerprint)
validate: Callable[[object], object] = (
S.encode_unknown_sync(compiled.target, **options)
if excess_is_error(options)
else (lambda value: value)
)
dict_ = _dictionary.DictWrite()
def encode_one(value: object) -> bytes:
return _rethrown(
lambda: _encode.encode_frame(compiled.layout, validate(value), options, mode, dict_)
)
def encode_many(values: Sequence[object]) -> bytes:
return _rethrown(
lambda: _encode.encode_frames(
compiled.layout, [validate(v) for v in values], options, mode, dict_
)
)
return Encoder(encode_one, encode_many)field_id#
field_id(id) -> _FieldIdAssigns a struct property's wire field id, an integer from 1 through
4294967295: to preserve it across a rename or resolve a hash collision.
Anything else raises ValueError. The schema keeps its types.
| Parameter | Type | Description |
|---|---|---|
id | int |
Returns _FieldId
def field_id(id: int, /) -> _FieldId:
"""Assigns a struct property's wire field id, an integer from 1 through
4294967295: to preserve it across a rename or resolve a hash collision.
Anything else raises ``ValueError``. The schema keeps its types."""
if type(id) is not int or not 0 < id <= _MAX_FIELD_ID:
raise ValueError(f"Binary layout field id must be an integer in [1, 4294967295], got {id}")
return _FieldId(id)decode#
decode[A, RD, E = Never, D = None](schema, /, *, fingerprint=False, max_frame_size=None, **options) -> Channel[tuple[A, ...], E | SchemaError, D, tuple[bytes, ...], E, D, RD]Decodes chunks of frames into values, with one frame parser per run: frames may be fragmented across chunks or concatenated within one, values completed before a failure are written first, and an incomplete frame left at the end fails. A schema with transformations runs the schema pass per value, which may be asynchronous and use services.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, Any, RD, object] | |
fingerprint | bool = False | |
max_frame_size | int | None = None | |
options | Unpack[ParseOptions] = {} |
Returns Channel[tuple[A, ...], E | SchemaError, D, tuple[bytes, ...], E, D, RD]
def decode[A, RD, E = Never, D = None](
schema: Codec[A, Any, RD, object],
/,
*,
fingerprint: bool = False,
max_frame_size: int | None = None,
**options: Unpack[ParseOptions],
) -> Channel[tuple[A, ...], E | SchemaError, D, tuple[bytes, ...], E, D, RD]:
"""Decodes chunks of frames into values, with one frame parser per run:
frames may be fragmented across chunks or concatenated within one, values
completed before a failure are written first, and an incomplete frame
left at the end fails. A schema with transformations runs the schema pass
per value, which may be asynchronous and use services."""
compiled = compile_target(schema)
mode = compile_mode(compiled.layout, fingerprint)
decode_target = None if compiled.exact else S.decode_unknown_effect(compiled.target, **options)
def decode_one(value: object) -> Any:
if compiled.exit_success and is_success_exit(value):
return _Succeed(value)
assert decode_target is not None
return decode_target(value)
def transform(upstream: AnyPull, _: CloseableScope) -> Any:
frames = make_parser(compiled.layout, mode, options, max_frame_size, None, False)
stashed: list[SchemaError] = []
def decode_all(raw: list[object]) -> AnyPull:
step = _DecodeAll(raw, decode_one)
out = step.out
def caught(cause: Cause[Any]) -> AnyPull:
found = cause.find_recoverable_error()
if out and isinstance(found, Fail) and isinstance(found.error, SchemaError):
stashed.append(found.error)
return _Succeed(tuple(out))
return _FailCause(cause)
return _Suspend(step).catch_cause(caught)
def done(leftover: object) -> AnyPull:
try:
frames.end_sync()
except SchemaError as error:
return _FailCause(fail_cause(error))
return end_with(leftover)
decode = None if decode_target is None else decode_all
return _Succeed(_Suspend(_FramesPull(upstream, frames, stashed, decode, done).next))
channel: Any = from_transform(transform)
return channelduplex#
duplex[TI, TO, OE, OD, IE, ID, R, RD, RE](channel, /, *, input_schema, output_schema, fingerprint=False, max_frame_size=None, **options) -> Channel[tuple[TO, ...], SchemaError | OE, OD, tuple[TI, ...], IE, ID, R | RD | RE]channel, a channel of binary frames, reading values that
input_schema encodes and writing what output_schema decodes.
| Parameter | Type | Description |
|---|---|---|
channel | Channel[tuple[bytes, ...], OE, OD, tuple[bytes, ...], SchemaError | IE, ID, R] | |
input_schema | Codec[TI, Any, object, RE] | |
output_schema | Codec[TO, Any, RD, object] | |
fingerprint | bool = False | |
max_frame_size | int | None = None | |
options | Unpack[ParseOptions] = {} |
Returns Channel[tuple[TO, ...], SchemaError | OE, OD, tuple[TI, ...], IE, ID, R | RD | RE]
def duplex[TI, TO, OE, OD, IE, ID, R, RD, RE](
channel: Channel[tuple[bytes, ...], OE, OD, tuple[bytes, ...], SchemaError | IE, ID, R],
/,
*,
input_schema: Codec[TI, Any, object, RE],
output_schema: Codec[TO, Any, RD, object],
fingerprint: bool = False,
max_frame_size: int | None = None,
**options: Unpack[ParseOptions],
) -> Channel[tuple[TO, ...], SchemaError | OE, OD, tuple[TI, ...], IE, ID, R | RD | RE]:
"""``channel``, a channel of binary frames, reading values that
``input_schema`` encodes and writing what ``output_schema`` decodes."""
require_channel(channel, "channel")
outgoing: Channel[Any, Any, Any, Any, Any, Any, Any] = encode(
input_schema, fingerprint=fingerprint, **options
)
incoming: Channel[Any, Any, Any, Any, Any, Any, Any] = decode(
output_schema, fingerprint=fingerprint, max_frame_size=max_frame_size, **options
)
wired: Any = outgoing.pipe_to(channel).pipe_to(incoming)
return wiredencode#
encode[A, RE, E = Never, D = None](schema, /, *, fingerprint=False, **options) -> Channel[tuple[bytes, ...], E | SchemaError, D, tuple[A, ...], E, D, RE]Encodes chunks of values into frames: each input chunk gives one
bytes of concatenated frames, written in one pass. A schema with
transformations first runs one schema pass per chunk, which may be
asynchronous and use services.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, Any, object, RE] | |
fingerprint | bool = False | |
options | Unpack[ParseOptions] = {} |
Returns Channel[tuple[bytes, ...], E | SchemaError, D, tuple[A, ...], E, D, RE]
def encode[A, RE, E = Never, D = None](
schema: Codec[A, Any, object, RE],
/,
*,
fingerprint: bool = False,
**options: Unpack[ParseOptions],
) -> Channel[tuple[bytes, ...], E | SchemaError, D, tuple[A, ...], E, D, RE]:
"""Encodes chunks of values into frames: each input chunk gives one
``bytes`` of concatenated frames, written in one pass. A schema with
transformations first runs one schema pass per chunk, which may be
asynchronous and use services."""
compiled = compile_target(schema)
mode = compile_mode(compiled.layout, fingerprint)
def write(values: Sequence[object]) -> AnyPull:
try:
return _Succeed((_encode.encode_frames(compiled.layout, values, options, mode),))
except IssueError as error:
return _FailCause(fail_cause(SchemaError(error.issue)))
except Exception as defect:
return _FailCause(die_cause(defect))
if compiled.exact and not excess_is_error(options):
def direct(upstream: AnyPull, _: CloseableScope) -> Any:
return _Succeed(upstream.flat_map(write))
channel: Any = from_transform(direct)
return channel
encode_values = S.encode_unknown_effect(S.NonEmptyArray(compiled.target), **options)
def through_schema(upstream: AnyPull, _: CloseableScope) -> Any:
return _Succeed(upstream.flat_map(lambda chunk: encode_values(chunk).flat_map(write)))
passed: Any = from_transform(through_schema)
return passed