JSON serializer
Ce contenu n’est pas encore disponible dans votre langue.
JsonSerializer is the default serializer. It wraps
JSON.stringify + JSON.parse (bytes are UTF-8) with a tree
walk that also round-trips Date, Uint8Array, Map, Set,
and bigint via type tags.
import { JsonSerializer } from 'actor-ts/serialization';
const serializer = new JsonSerializer();const bytes = serializer.toBinary({ kind: 'increment', n: 1 });// → Uint8Array of '{"kind":"increment","n":1}' as UTF-8
const decoded = serializer.fromBinary(bytes, '');// → { kind: 'increment', n: 1 }Why JSON is the default
Section titled “Why JSON is the default”- Universal — every language has a JSON parser.
- Human-readable — open a journal file with
cat; see the events. - Schema-flexible — no compile step; types evolve via ordinary code changes (+ schema-migration adapters).
- Battle-tested — every Web API speaks JSON.
For most apps, you’ll never change serializers — JSON covers it.
What it handles
Section titled “What it handles”- Plain objects, arrays.
- Strings, numbers, booleans,
null. - Nested combinations.
Date,Uint8Array,Map,Set, andbigint— round-tripped back into real instances via type tags (__date__,__bytes__,__map__,__set__,__bigint__).BidirectionalMapandBidirectionalMultiMap— the two framework classes with tags of their own (__bidirectionalmap__, #1035;__bidirectionalmultimap__, #1037), so they can be held in persistent state without an adapter. Only the forward direction is written — pairs for the first, an adjacency list for the second; the inverse is rebuilt on decode.NaN/Infinity/-Infinity/-0,RegExp(source + flags),URL,Error(name + message + cause — no stack), and every typed array /DataView/ArrayBuffer— round-tripped via type tags too (#889).Number/String/Booleanwrapper objects unwrap to their primitive, likeJSON.stringify.toJSON()— honoured likeJSON.stringifydoes, so Luxon/Temporal wrappers and your owntoJSONtypes encode as their JSON form.- User data that looks like a tag — an object whose sole key is a
reserved tag name — is wrapped in a
__literal__escape on encode and round-trips as plain data. A tag is only ever interpreted when it is an object’s sole own key.
Persistence uses exactly this tree format: every journal, snapshot store and durable-state store writes its payloads through the same tagged tree (see what events and state may contain).
What needs care:
| Type | Behavior |
|---|---|
undefined | Throws a SerializationError (stricter than raw JSON.stringify, which drops it). The persistence payload codec instead drops undefined object properties like JSON.stringify and preserves undefined in value positions (array slots, Set members, Map entries) via a tag (#889). CborSerializer carries it natively everywhere, keys included — the one place the two codecs differ (#1036). |
Function / Symbol / Promise / WeakMap / WeakSet | Throw a SerializationError — inherently non-serialisable. |
| Circular references | Throw a SerializationError naming the key path (instead of overflowing the stack). |
| Class instances | toJSON() is used when present; otherwise decoded as plain { ...fields } — methods + class identity lost. |
Date / Map / Set / bigint / Uint8Array | Round-trip as real instances, but the JSON carries an actor-ts-specific tag shape (e.g. {"__date__":"…"}) — a plain (non-actor-ts) JSON reader won’t see a bare value. |
For most actor messages, this is fine — the framework’s message conventions already discourage non-serializable shapes.
JSON is larger than binary formats for the same data:
- Numbers are decimal strings (
"42"is 4 bytes vs CBOR’s 2). - Field names are repeated (every record has
"kind":"..."). - Binary data (
Uint8Array) base64-encodes (33 % overhead).
For text-heavy or repetitive data, JSON’s overhead is small. For binary-heavy data (images, encoded payloads), CBOR saves meaningfully.
Performance
Section titled “Performance”Rough numbers per serialize/deserialize pair:
- Small object (~50 bytes): ~1-2 microseconds.
- Medium object (~1 KB): ~5-15 microseconds.
- Large object (~100 KB): ~1-2 ms.
JSON.parse / JSON.stringify are native code in V8/JSC —
fast enough that JSON serialization is rarely the bottleneck.
What the decoder refuses
Section titled “What the decoder refuses”fromBinary refuses a document that is not JSON at all with a
SerializationError naming the parse failure, and a malformed type tag inside
well-formed JSON with one naming the tag, so the two faults stay apart in a log;
the persistence payload codec reports a stored row that does not parse the same
way. An __error__ whose name or message is not a string is such a
malformed tag. A name with no built-in error class behind it is not: that
error decodes to a plain Error that keeps the name, which is how every custom
error class crosses the wire, and a member of Object.prototype such as
toString or constructor is no exception.
Decoding is where the bytes are somebody else’s, so the JSON decoder applies
the ceilings in
actor-ts.serialization.read-constraints:
| Ceiling | Default | What it refuses |
|---|---|---|
max-nesting-depth | 256 | A tree nested deeper than this — arrays, objects and tagged containers all count one level each. |
max-document-bytes | 0 (off) | A document larger than this — checked before JSON.parse runs, and on the cluster wire before the frame’s bytes are even buffered. |
max-nesting-depth is not decoration. JSON.parse gives you nothing to lean
on here: measured on Bun, Node and Deno alike, it accepts a hundred thousand
levels of [ without complaint. What overflows is actor-ts’s own
tagged-tree walker, which recurses once per level — and on the cluster wire
that walker is reached directly, on bytes any peer that completed the handshake
can send. A payload past the ceiling is a SerializationError naming the
depth, thrown before the walk goes any deeper.
The ceiling can be lowered but not raised past 256, which is the encoder’s own
hard cap: a node that read deeper than it writes would accept a payload it
cannot produce. Both are per-decode ceilings — they say nothing about what
toBinary will emit.
max-document-bytes bounds the cost rather than the shape, and it is the
only ceiling that can act before the parse allocates anything. On the cluster
wire it is checked against the frame’s 4-byte length prefix, which is earlier
than either serializer can manage — those are handed bytes that already exist.
It ships as 0, so nothing changes until a deployment sets it.
Which leaves a residual worth stating plainly: at the shipped defaults an
over-deep frame is refused only after JSON.parse has already built it.
Measured on Bun 1.4, one 16 MiB frame of balanced [ costs about 1.0 s of CPU
and 260 MiB of heap before the depth ceiling reports it — roughly four times
what a legitimate frame of the same size costs, and repeatable by any peer that
completed the handshake. Two knobs bound it and neither is on by default:
actor-ts.remote.max-frame-bytes caps the bytes at 16 MiB, and
max-document-bytes caps the document on the same prefix. A pre-parse scan of
the raw buffer would close it without either; it was measured and not shipped,
because it costs 18–28 % of every frame decode to remove a fourfold
amplification.
Journal and snapshot rows are deliberately exempt. Those bytes were written by actor-ts itself, so a tightened ceiling there would turn recoverable history into unreadable history.
One bound is not configurable, and it holds for every encode and every decode,
journal and snapshot rows included: a bigint travels only within the range
the CBOR serializer’s 1 KiB bignum cap admits, -2^8192 to 2^8192 - 1, so
the two serializers carry the same integers. An integer outside it is refused
where it is written — toBinary throws, persist() rejects without storing
anything, a remote tell drops that one message and logs it — rather than
becoming a row the next recovery fails on. A document that carries one anyway
is refused when it is read. The digit string is measured before it is parsed
— at most 2467 digits, the length of 2^8192 - 1, after an optional minus sign
— because parsing decimal digits costs more than linear time in their count:
measured on Bun 1.4, a million digits took a third of a second and four
million almost two. Only the spelling the encoder writes into a __bigint__
is parsed at all, a minus sign only below zero and then decimal digits without
a leading zero, so +5, 007, -0, whitespace and hex are refused on every
runtime alike. The parsed value is then held to the range itself, since 2467
digits reach about nine times past it. Every refusal is a
SerializationError, and the cost that remains grows only in step with the
document, which max-document-bytes bounds. An integer wider than 8192 bits
travels as a string field; check its length before your own code hands it to
BigInt().
When to switch to something else
Section titled “When to switch to something else”Need to interop with non-JSON systems? → Custom (Protobuf/Avro)Bandwidth-bound (large or many small messages)? → CBORNeed typed schemas in source control? → Custom (Protobuf)Otherwise → Stay on JSONMost production apps stay on JSON for the actor wire and persistence — the perf / size gains from switching rarely justify the operational complexity.
Where to next
Section titled “Where to next”- Serialization overview — the bigger picture.
- CBOR serializer — the binary alternative.
- Custom serializers — Protobuf / Avro / etc.
- Messages — the conventions for serialize-friendly shapes.
