Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Use static JSONEncoders #3049

Merged
merged 2 commits into from
Apr 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions synapse/handlers/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from synapse.util.async import run_on_reactor, ReadWriteLock, Limiter
from synapse.util.logcontext import preserve_fn, run_in_background
from synapse.util.metrics import measure_func
from synapse.util.frozenutils import unfreeze
from synapse.util.frozenutils import frozendict_json_encoder
from synapse.util.stringutils import random_string
from synapse.visibility import filter_events_for_client
from synapse.replication.http.send_event import send_event_to_master
Expand Down Expand Up @@ -678,7 +678,7 @@ def handle_new_client_event(

# Ensure that we can round trip before trying to persist in db
try:
dump = simplejson.dumps(unfreeze(event.content))
dump = frozendict_json_encoder.encode(event.content)
simplejson.loads(dump)
except Exception:
logger.exception("Failed to encode content: %r", event.content)
Expand Down
8 changes: 5 additions & 3 deletions synapse/replication/tcp/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

logger = logging.getLogger(__name__)

_json_encoder = simplejson.JSONEncoder(namedtuple_as_object=False)


class Command(object):
"""The base command class.
Expand Down Expand Up @@ -107,7 +109,7 @@ def to_line(self):
return " ".join((
self.stream_name,
str(self.token) if self.token is not None else "batch",
simplejson.dumps(self.row, namedtuple_as_object=False),
_json_encoder.encode(self.row),
))


Expand Down Expand Up @@ -302,7 +304,7 @@ def from_line(cls, line):

def to_line(self):
return " ".join((
self.cache_func, simplejson.dumps(self.keys, namedtuple_as_object=False)
self.cache_func, _json_encoder.encode(self.keys),
))


Expand Down Expand Up @@ -334,7 +336,7 @@ def from_line(cls, line):
)

def to_line(self):
return self.user_id + " " + simplejson.dumps((
return self.user_id + " " + _json_encoder.encode((
self.access_token, self.ip, self.user_agent, self.device_id,
self.last_seen,
))
Expand Down
23 changes: 8 additions & 15 deletions synapse/storage/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from synapse.storage.events_worker import EventsWorkerStore
from collections import OrderedDict, deque, namedtuple
from functools import wraps
import logging

import simplejson as json
from twisted.internet import defer

from synapse.events import USE_FROZEN_DICTS

from synapse.storage.events_worker import EventsWorkerStore
from synapse.util.async import ObservableDeferred
from synapse.util.frozenutils import frozendict_json_encoder
from synapse.util.logcontext import (
PreserveLoggingContext, make_deferred_yieldable
PreserveLoggingContext, make_deferred_yieldable,
)
from synapse.util.logutils import log_function
from synapse.util.metrics import Measure
from synapse.api.constants import EventTypes
from synapse.api.errors import SynapseError
from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
from synapse.types import get_domain_from_id

from canonicaljson import encode_canonical_json
from collections import deque, namedtuple, OrderedDict
from functools import wraps

import synapse.metrics

import logging
import simplejson as json

# these are only included to make the type annotations work
from synapse.events import EventBase # noqa: F401
from synapse.events.snapshot import EventContext # noqa: F401
Expand Down Expand Up @@ -71,10 +67,7 @@


def encode_json(json_object):
if USE_FROZEN_DICTS:
return encode_canonical_json(json_object)
else:
return json.dumps(json_object, ensure_ascii=False)
return frozendict_json_encoder.encode(json_object)


class _EventPeristenceQueue(object):
Expand Down
19 changes: 19 additions & 0 deletions synapse/util/frozenutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
# limitations under the License.

from frozendict import frozendict
import simplejson as json


def freeze(o):
Expand Down Expand Up @@ -49,3 +50,21 @@ def unfreeze(o):
pass

return o


def _handle_frozendict(obj):
"""Helper for EventEncoder. Makes frozendicts serializable by returning
the underlying dict
"""
if type(obj) is frozendict:
# fishing the protected dict out of the object is a bit nasty,
# but we don't really want the overhead of copying the dict.
return obj._dict
raise TypeError('Object of type %s is not JSON serializable' %
obj.__class__.__name__)


# A JSONEncoder which is capable of encoding frozendics without barfing
frozendict_json_encoder = json.JSONEncoder(
default=_handle_frozendict,
)