⚡ Use json serialization for announcements cache (#4339)
* Use json for annoucements cache Parsing this XML file is very slow, so there's no reason to do it more than we have to. See 4480-2021-12-11T13:23:48-05:00.json, MainThread -> parse On my system, this reduces the time for /plugin/announcements/channels from 250ms CPU time to 50ms. The rough improvment in this specific function call is from 8% to 0.32% of total runtime. * ♻️ Refactor json serializer * Move back to octoprint.util.json * Leave old encoding helper as is but add additional one focused on serialization (with full roundtrips). Use each as needed (primarily encoding one). octoprint.util.encoding -> old one octoprint.util.serializing -> new one Each serves different purpose, we don't want to end up with `__jsonclass__` stuff in our API output at some point, so separate the concerns here and allow different handling. * Ensure wrappers are in place for backwards compatibility (e.g. dump vs dumps). * 🐛 Fix handling of invalid cache We get different exceptions now and in any case just throw *anything* away that we can't parse. * 🎨 Use fallback typing annotation for Py3.7.{0,1} Better solution than getting stuck to Dict only, thanks @flaviut for the suggestion! * 🐛 Fix bytes encoding bytes objects are explicitly not always UTF-8, so encode them in a way that doesn't lead to errors and encoding/decoding problems when they are actually binary data. Co-authored-by: Gina Häußge <gina@octoprint.org>
This commit is contained in:
1 parent
a7f7e63489
commit
1758efb82d
9 files changed
+405
-61
No files matched your search
@@ -23,7 +23,7 @@ from octoprint.server.util.flask import (
|
||||
no_firstrun_access,
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.util import count, utmify
|
||||
from octoprint.util import count, deserialize, serialize, utmify
|
||||
from octoprint.util.text import sanitize
|
||||
|
||||
|
||||
@@ -428,12 +428,22 @@ class AnnouncementPlugin(
|
||||
|
||||
ttl *= 60
|
||||
now = time.time()
|
||||
if os.stat(channel_path).st_mtime + ttl > now:
|
||||
d = feedparser.parse(channel_path)
|
||||
if now > os.stat(channel_path).st_mtime + ttl:
|
||||
return None
|
||||
|
||||
try:
|
||||
d = deserialize(channel_path)
|
||||
self._logger.debug(f"Loaded channel {key} from cache at {channel_path}")
|
||||
return d
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Could not read channel {key} from cache {channel_path}"
|
||||
)
|
||||
try:
|
||||
os.remove(channel_path)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
def _get_channel_data_from_network(self, key, config):
|
||||
"""Fetch channel feed from network."""
|
||||
@@ -456,11 +466,12 @@ class AnnouncementPlugin(
|
||||
)
|
||||
return None
|
||||
|
||||
response = r.text
|
||||
channel_path = self._get_channel_cache_path(key)
|
||||
with open(channel_path, mode="wt", encoding="utf-8") as f:
|
||||
f.write(response)
|
||||
return feedparser.parse(response)
|
||||
response = feedparser.parse(r.text)
|
||||
try:
|
||||
serialize(self._get_channel_cache_path(key), response)
|
||||
except Exception:
|
||||
self._logger.exception(f"Failed to cache data for channel {key}")
|
||||
return response
|
||||
|
||||
def _to_internal_feed(self, feed, read_until=None):
|
||||
"""Convert feed to internal data structure."""
|
||||
|
||||
@@ -275,7 +275,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
try:
|
||||
additional = hook(initial=initial)
|
||||
if additional and isinstance(additional, dict):
|
||||
octoprint.util.json.dump({name: additional})
|
||||
octoprint.util.json.dumps({name: additional})
|
||||
plugin_data[name] = additional
|
||||
except ValueError:
|
||||
self._logger.exception(
|
||||
|
||||
@@ -24,7 +24,7 @@ from octoprint.access.permissions import Permissions
|
||||
from octoprint.access.users import LoginStatusListener
|
||||
from octoprint.events import Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util.json import dump as json_dump
|
||||
from octoprint.util.json import dumps as json_dumps
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
|
||||
class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
|
||||
def send_message(self, msg, stats=True, binary=False):
|
||||
self.send_jsonified(
|
||||
json_dump(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)),
|
||||
json_dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)),
|
||||
stats,
|
||||
)
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import codecs
|
||||
import collections
|
||||
import contextlib
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pickle
|
||||
@@ -1712,9 +1711,13 @@ def serialize(filename, data, encoding="utf-8", compressed=True):
|
||||
"""
|
||||
Serializes data to a file
|
||||
|
||||
In the current implementation this uses json.dumps and - if compressed is True (the
|
||||
default) - zlib.compress. Only data that can be serialized by json.dumps in the stock
|
||||
configuration is supported.
|
||||
In the current implementation this uses json.dumps.
|
||||
|
||||
If `compressed` is True (the default), the serialized data put through zlib.compress.
|
||||
|
||||
Supported data types are listed at the bottom of
|
||||
:ref:`octoprint.util.comprehensive_json`, and include some data types that are not
|
||||
supported by json.dumps by default.
|
||||
|
||||
This is not thread-safe, if concurrent access is required, the caller needs to ensure
|
||||
that only one thread is writing to the file at any given time.
|
||||
@@ -1725,7 +1728,9 @@ def serialize(filename, data, encoding="utf-8", compressed=True):
|
||||
encoding (str): The encoding to use for the file
|
||||
compressed (bool): Whether to compress the data before writing it to the file
|
||||
"""
|
||||
serialized = json.dumps(data).encode(encoding)
|
||||
from octoprint.util import json
|
||||
|
||||
serialized = json.serializing.dumps(data).encode(encoding)
|
||||
|
||||
if compressed:
|
||||
serialized = zlib.compress(serialized)
|
||||
@@ -1756,4 +1761,6 @@ def deserialize(filename, encoding="utf-8"):
|
||||
except zlib.error:
|
||||
pass
|
||||
|
||||
return json.loads(serialized.decode(encoding))
|
||||
from octoprint.util import json
|
||||
|
||||
return json.serializing.loads(serialized.decode(encoding))
|
||||
@@ -1,46 +1,13 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.util import deprecated
|
||||
|
||||
import collections
|
||||
import json
|
||||
from . import serializing # noqa: F401
|
||||
from .encoding import JsonEncoding, dumps, loads # noqa: F401
|
||||
|
||||
from frozendict import frozendict
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
|
||||
def dump(obj):
|
||||
return json.dumps(
|
||||
obj,
|
||||
separators=(",", ":"),
|
||||
default=JsonEncoding.encode,
|
||||
allow_nan=False,
|
||||
)
|
||||
|
||||
|
||||
class JsonEncoding:
|
||||
|
||||
encoders = collections.OrderedDict()
|
||||
|
||||
@classmethod
|
||||
def add_encoder(cls, type, encoder):
|
||||
cls.encoders[type] = encoder
|
||||
|
||||
@classmethod
|
||||
def remove_encoder(cls, type):
|
||||
try:
|
||||
del cls.encoders[type]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def encode(cls, obj):
|
||||
for type, encoder in cls.encoders.items():
|
||||
if isinstance(obj, type):
|
||||
return encoder(obj)
|
||||
raise TypeError
|
||||
|
||||
|
||||
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
|
||||
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
|
||||
dump = deprecated(
|
||||
"dump has been renamed to dumps, please adjust your implementation",
|
||||
includedoc="dump has been renamed to dumps",
|
||||
since="1.8.0",
|
||||
)(dumps)
|
||||
@@ -0,0 +1,69 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
try:
|
||||
from typing import OrderedDict as OrderedDictType
|
||||
except ImportError:
|
||||
OrderedDictType = Dict # py3.7.{0,1}
|
||||
|
||||
from frozendict import frozendict
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
|
||||
class JsonEncoding:
|
||||
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
|
||||
|
||||
@classmethod
|
||||
def add_encoder(cls, typ: type, encoder: Callable[[Any], Any]) -> None:
|
||||
"""
|
||||
Add an encoder for a type.
|
||||
|
||||
:param typ: the type to add an encoder for
|
||||
:param encoder: the encoder. Must take a single argument and return a
|
||||
tuple (name, parameters...)
|
||||
"""
|
||||
cls.encoders[typ] = encoder
|
||||
|
||||
@classmethod
|
||||
def remove_encoder(cls, typ):
|
||||
try:
|
||||
del cls.encoders[typ]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def dumps(cls, obj: Any) -> str:
|
||||
"""
|
||||
Dump an object to JSON, handles additional types that the JSON encoder can't, like
|
||||
bytes and frozendicts.
|
||||
"""
|
||||
return json.dumps(
|
||||
obj,
|
||||
default=cls.encode,
|
||||
separators=(",", ":"),
|
||||
indent=None,
|
||||
allow_nan=False,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def loads(cls, s: str) -> Any:
|
||||
return json.loads(s)
|
||||
|
||||
@classmethod
|
||||
def encode(cls, obj):
|
||||
for type, encoder in cls.encoders.items():
|
||||
if isinstance(obj, type):
|
||||
return encoder(obj)
|
||||
raise TypeError(f"Unserializable type {type(obj)}")
|
||||
|
||||
|
||||
JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj))
|
||||
JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj))
|
||||
|
||||
dumps = JsonEncoding.dumps
|
||||
loads = JsonEncoding.loads
|
||||
@@ -0,0 +1,158 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
try:
|
||||
from typing import OrderedDict as OrderedDictType
|
||||
except ImportError:
|
||||
OrderedDictType = Dict # py3.7.{0,1}
|
||||
|
||||
from frozendict import frozendict
|
||||
|
||||
from .encoding import JsonEncoding
|
||||
|
||||
|
||||
class SerializableJsonEncoding(JsonEncoding):
|
||||
"""
|
||||
A JSON encoding that can serialize and deserialize objects, including additional
|
||||
objects otherwise not serializable by the standard JSON encoder:
|
||||
|
||||
* ``bytes``
|
||||
* ``frozendict.frozendict``
|
||||
* ``datetime.datetime``
|
||||
* ``time.struct_time``
|
||||
"""
|
||||
|
||||
encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict()
|
||||
decoders: OrderedDictType[str, Callable[[dict], object]] = OrderedDict()
|
||||
|
||||
@classmethod
|
||||
def add_decoder(cls, classname, decoder):
|
||||
cls.decoders[classname] = decoder
|
||||
|
||||
@classmethod
|
||||
def remove_decoder(cls, classname):
|
||||
try:
|
||||
del cls.decoders[classname]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def dumps(cls, obj: Any) -> str:
|
||||
return json.dumps(
|
||||
cls.encode(obj), separators=(",", ":"), indent=None, allow_nan=False
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def loads(cls, s: str) -> Any:
|
||||
return json.loads(s, object_hook=cls.decode)
|
||||
|
||||
@classmethod
|
||||
def encode(cls, val):
|
||||
"""
|
||||
Recursively replace all instances of encodable types with their encoded
|
||||
value. This is useful over the ``default=`` functionallity of the JSON
|
||||
encoder because JSON will not call default for tuples, lists, ints, etc:
|
||||
https://docs.python.org/3/library/json.html#json.JSONEncoder
|
||||
|
||||
Cannot handle circular references.
|
||||
"""
|
||||
|
||||
if isinstance(val, tuple(cls.encoders.keys())):
|
||||
# we can't directly index into the encoders dict because
|
||||
# we need to be able to handle subclasses
|
||||
encoder = next(
|
||||
encoder for typ, encoder in cls.encoders.items() if isinstance(val, typ)
|
||||
)
|
||||
return cls.encode(encoder(val))
|
||||
elif isinstance(val, dict):
|
||||
return {k: cls.encode(v) for k, v in val.items()}
|
||||
elif isinstance(val, (tuple, list)):
|
||||
return [cls.encode(v) for v in val]
|
||||
elif isinstance(val, (bool, int, float, str)) or val is None:
|
||||
return val
|
||||
else:
|
||||
raise TypeError(f"Unserializable type {type(val)}")
|
||||
|
||||
@classmethod
|
||||
def decode(cls, dct):
|
||||
"""
|
||||
Recursively replace all instances of decodable types with their decoded
|
||||
values.
|
||||
|
||||
You'll want to have used ``class_encode()`` in your encoder to get this
|
||||
to work properly.
|
||||
"""
|
||||
if "__jsonclass__" not in dct:
|
||||
return dct
|
||||
|
||||
if len(dct["__jsonclass__"]) == 0:
|
||||
raise ValueError("__jsonclass__ must not be empty")
|
||||
|
||||
decoded_name = dct["__jsonclass__"][0]
|
||||
params = dct["__jsonclass__"][1:]
|
||||
|
||||
for classname, decoder in cls.decoders.items():
|
||||
if decoded_name == classname:
|
||||
return decoder(*params)
|
||||
return dct
|
||||
|
||||
|
||||
def class_encode(name: str, *params: Any) -> Dict[str, List]:
|
||||
"""
|
||||
Encode a class name and parameters into a serializable dict. You'll
|
||||
probably want to use this if you're going to set a custom decoder.
|
||||
|
||||
This stores the class names in a format inspired by the JSON-RPC spec at
|
||||
https://www.jsonrpc.org/specification_v1#a3.JSONClasshinting
|
||||
"""
|
||||
return {"__jsonclass__": [name] + list(params)}
|
||||
|
||||
|
||||
# frozendict
|
||||
|
||||
SerializableJsonEncoding.add_encoder(
|
||||
frozendict, lambda obj: class_encode("frozendict.frozendict", dict(obj))
|
||||
)
|
||||
SerializableJsonEncoding.add_decoder("frozendict.frozendict", lambda obj: frozendict(obj))
|
||||
|
||||
# bytes
|
||||
|
||||
SerializableJsonEncoding.add_encoder(
|
||||
bytes, lambda obj: class_encode("bytes", base64.b85encode(obj).decode("ascii"))
|
||||
)
|
||||
SerializableJsonEncoding.add_decoder("bytes", lambda obj: base64.b85decode(obj))
|
||||
|
||||
# time.struct_time
|
||||
|
||||
|
||||
def _struct_time_decoder(params):
|
||||
if len(params) == 9 and all(isinstance(p, int) and p >= 0 for p in params):
|
||||
return time.struct_time(params)
|
||||
raise ValueError(f"Invalid time.struct_time params `{params}`")
|
||||
|
||||
|
||||
SerializableJsonEncoding.add_encoder(
|
||||
time.struct_time, lambda obj: class_encode("time.struct_time", list(obj))
|
||||
)
|
||||
SerializableJsonEncoding.add_decoder("time.struct_time", _struct_time_decoder)
|
||||
|
||||
# datetime.datetime
|
||||
|
||||
SerializableJsonEncoding.add_encoder(
|
||||
datetime.datetime, lambda obj: class_encode("datetime.datetime", obj.isoformat())
|
||||
)
|
||||
SerializableJsonEncoding.add_decoder(
|
||||
"datetime.datetime", lambda params: datetime.datetime.fromisoformat(params)
|
||||
)
|
||||
|
||||
# shortcut for dumps and loads
|
||||
|
||||
dumps = SerializableJsonEncoding.dumps
|
||||
loads = SerializableJsonEncoding.loads
|
||||
Reference in new issue
Block a user