Skip to content

Commit aac1ecf

Browse files
author
Alan
committed
Fallback to json_packer and json_unpacker for orjson to handle for better resilience.
1 parent 3d9e4be commit aac1ecf

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

jupyter_client/session.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -131,15 +131,25 @@ def json_unpacker(s: str | bytes) -> t.Any:
131131
import orjson # type:ignore[import-not-found]
132132
except ModuleNotFoundError:
133133
orjson = None
134-
_default_packer_unpacker = "json", "json"
135-
_default_pack_unpack = (json_packer, json_unpacker)
134+
orjson_packer, orjson_unpacker = json_packer, json_unpacker
136135
else:
137-
orjson_packer = functools.partial(
138-
orjson.dumps, default=json_default, option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z
139-
)
140-
orjson_unpacker = orjson.loads
141-
_default_packer_unpacker = "orjson", "orjson"
142-
_default_pack_unpack = (orjson_packer, orjson_unpacker)
136+
137+
def orjson_packer(obj, *, options=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z) -> bytes:
138+
"""Convert a json object to a bytes using orjson with fallback to json_packer."""
139+
try:
140+
return orjson.dumps(obj, default=json_default, options=options)
141+
except Exception:
142+
pass
143+
return json_packer(obj)
144+
145+
def orjson_unpacker(s: str | bytes) -> t.Any:
146+
"""Convert a json bytes or string to an object using orjson with fallback to json_unpacker."""
147+
try:
148+
orjson.loads(s)
149+
except Exception:
150+
pass
151+
return json_unpacker(s)
152+
143153

144154
try:
145155
import msgpack # type:ignore[import-not-found]
@@ -377,20 +387,20 @@ class Session(Configurable):
377387

378388
# serialization traits:
379389
packer = DottedObjectName(
380-
_default_packer_unpacker[0],
390+
"orjson" if orjson else "json",
381391
config=True,
382392
help="""The name of the packer for serializing messages.
383393
Should be one of 'json', 'pickle', or an import name
384394
for a custom callable serializer.""",
385395
)
386396
unpacker = DottedObjectName(
387-
_default_packer_unpacker[1],
397+
"orjson" if orjson else "json",
388398
config=True,
389399
help="""The name of the unpacker for unserializing messages.
390400
Only used with custom functions for `packer`.""",
391401
)
392-
pack = Callable(_default_pack_unpack[0]) # the actual packer function
393-
unpack = Callable(_default_pack_unpack[1]) # the actual unpacker function
402+
pack = Callable(orjson_packer if orjson else json_packer) # the actual packer function
403+
unpack = Callable(orjson_unpacker if orjson else json_unpacker) # the actual unpacker function
394404

395405
@observe("packer", "unpacker")
396406
def _packer_unpacker_changed(self, change: t.Any) -> None:

0 commit comments

Comments
 (0)