# Serde

> Rust-backed JSON and Avro serialization that returns Either instead of raising.

Source: https://docs.pyrula.io/primitives/serde/

`serialize` and `deserialize` return an [`Either`](https://docs.pyrula.io/primitives/either.md), so a bad payload is an `Err` rather than an exception.

## JSON

```python
from pyrula import JsonSerde

serde = JsonSerde()

serde.serialize({"id": 1, "name": "alice"})  # Ok(b'{"id":1,...}')
serde.deserialize(b'{"id": 1}')  # Ok({"id": 1})
serde.deserialize(b"not json")  # Err(DeserializationError(...))
```

Decoding matches `json.loads` (key order is kept, integers of any size are exact) and refuses `NaN` and `Infinity`. Encoding writes `None`, `bool`, `int`, finite `float`, `str`, `list` and `dict` with `str` keys; anything else gives `Err(SerializationError(...))`.

## Core types as JSON

Every core type has one plain JSON form. The journal, `to_jsonable`, Pydantic (`dump_json`, `model_dump(mode="json")`, FastAPI) and the generated JSON Schema all agree on it.

| Value | JSON |
|---|---|
| `Ok(v)` / `Err(e)` | `{"ok": v}` / `{"err": e}` |
| `Some(v)` / `Nothing` | `v` / `null` |
| `Valid(v)` / `Invalid([e, ...])` | `{"valid": v}` / `{"invalid": [e, ...]}` (never empty) |
| `Success(v)` / `Failure(exc)` | `{"success": v}` / `{"failure": exc}` |
| `IList`, `NonEmptyList`, `IntList`, `FloatList`, `ISet`, `IntSet` | a list |
| `IMap` | an object |
| an exception | `{"type": "module:Qualname", "message": "...", "args": [...], "attrs": {...}}` |
| a `@sealed` case | `{"CaseName": {field: value, ...}}` |

Type optional fields as `Option[T]` and default them to `Nothing`; `Some(None)` has no form and writing one is an error.

### Reading it back

An unannotated `@step` result comes back as plain JSON. Annotate the return type and the value comes back as the declared type, on first run and on replay:

```python
@sealed
class OrderError: ...


@case
class OutOfStock(OrderError):
    sku: str


@step
def reserve(sku: str) -> Either[int, OrderError]:
    return Err(OutOfStock(sku))


match await reserve("x"):
    case Err(OutOfStock(sku=sku)):
        ...
```

An exception is rebuilt as its class only if the class is already loaded and subclasses the declared error type. Otherwise it comes back as a `RecordedError` with the original `type_path` and message, so match on `type_path` for a class a replay worker may not have imported. Type the error side of a FastAPI request body as a `@case` error rather than `Exception`. The rules are in [Errors and retries](https://docs.pyrula.io/workflows/guides/errors-and-retries.md).

## Avro

`AvroSerde` takes a schema as a JSON string.

```python
from pyrula import AvroSerde

serde = AvroSerde(schema_json=SCHEMA)
serde.serialize({"id": 1, "name": "alice"})  # Ok(bytes)
```

`deserialize` takes exactly one datum. Trailing bytes are an `Err`, including a leftover Schema Registry frame (the error points at `AvroRegistrySerde`).

Records and maps are `dict`, arrays `list`, `string` and `enum` `str`, `bytes` and `fixed` `bytes`, and a union holds whichever branch the value is. Named types may repeat or recurse.

Logical types match fastavro, and so confluent-kafka's Avro serializers:

| Logical type | Decodes to | Encodes from |
|---|---|---|
| `timestamp-millis`, `timestamp-micros` | UTC `datetime` | `datetime` (naive is local time) or `int` |
| `local-timestamp-millis`, `local-timestamp-micros` | naive `datetime` | `datetime` or `int` |
| `date` | `date` | `date`, ISO `str` or `int` |
| `time-millis`, `time-micros` | `time` | `time` or `int` |
| `decimal` (`bytes` or `fixed`) | `Decimal` | `Decimal` within precision and scale, or `bytes` |
| `uuid` | `UUID` | `UUID` or `str` |

Nanosecond timestamps and `duration` stay raw. Declare a `uuid` on a `string`, not `fixed` or `bytes`.

Two options apply to `AvroSerde` and `AvroRegistrySerde`:

```python
AvroSerde(SCHEMA, strict=True)
AvroSerde(SCHEMA, logical_types="raw")
```

`strict=True` refuses fastavro's guessed conversions, such as a naive `datetime` for a `timestamp-*` field. `logical_types="raw"` decodes every logical type to its wire value.

## Batches

Every serde has the same five batch methods. They take an [`IList`](https://docs.pyrula.io/primitives/collections.md) or any iterable, and each runs in one Rust call.

| Method | Returns | A bad record |
|---|---|---|
| `serialize_many(items)` | `IList` of `Ok(bytes)` or `Err` | one `Err` per record |
| `serialize_many_bytes(items)` | `BytesList` | raises `SerializationError` |
| `deserialize_many(rows)` | `IList` of `Ok(value)` or `Err` | one `Err` per record |
| `deserialize_many_objects(rows)` | `IList` of values | raises `DeserializationError` naming the record index |
| `deserialize_many_from_packed(packed, count)` | `IList` of values | raises `DeserializationError` naming the record index |

`deserialize_many_from_packed` reads the buffer `KafkaConsumer.poll_bytes_packed` returns: `count` records, each a little-endian `u32` length followed by the payload. A truncated buffer, or a `count` larger than the frames it holds, raises `ValueError` rather than reading past the end. Pyrula reads frames as it decodes, so the error arrives after the records before the bad frame have decoded (a decode failure in an earlier record is raised first).

```python
rows = IList([{"id": 1}, {"id": 2}])
json_serde.serialize_many(rows)  # IList([Ok(b'{"id":1}'), Ok(b'{"id":2}')])
packed = json_serde.serialize_many_bytes(rows)  # BytesList
json_serde.deserialize_many_objects(packed)  # IList([{'id': 1}, {'id': 2}])
```

## Schema Registry

`AvroRegistrySerde`, `JsonSchemaRegistrySerde` and `ProtobufRegistrySerde` handle Confluent framing, schema-id lookup and TLS/mTLS. They live on the Kafka path; see [Kafka](https://docs.pyrula.io/kafka.md).

```python
serde = AvroRegistrySerde.for_topic("http://registry:8081", "orders", SCHEMA)
```

`JsonSchemaRegistrySerde` frames and registers; it does not validate payloads against the schema.

Each takes `timeout_ms` (default 5000, 1 to 300000) bounding one registry request, so a dead registry returns its `Err` in about that long. The workflows and agents bindings set it with `schema_registry_timeout_ms` or `PYRULA_SCHEMA_REGISTRY_TIMEOUT_MS`; the confluent shim takes `timeout` in seconds on `SchemaRegistryClient`.

```python
serde = AvroRegistrySerde.for_topic("http://registry:8081", "orders", SCHEMA, timeout_ms=2000)
```

A failed lookup, including a 404 for an unknown id, is remembered for 5 seconds, so a lagging registry follower can fail a brand-new id for that long; `register()` always asks. In a batch, the raising methods stop at the first failure. If the registry is unreachable or answers 5xx the batch stops making requests, so an outage costs one `timeout_ms`.

A registry error names the registry (scheme, host and port, never a username or password from the URL), and a 401 or 403 adds a pointer to the registry credentials.
