Skip to content

Commit fa70f43

Browse files
authored
Merge pull request #405 from aiven/jjaakola-aiven-remove-ujson
Remove ujson dependency
2 parents 9e3cf20 + 1d14492 commit fa70f43

28 files changed

+293
-307
lines changed

.pylintrc

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
[MASTER]
22
jobs=4
3-
extension-pkg-allow-list=ujson
43

54
[MESSAGES CONTROL]
65
enable=

karapace/config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
from pathlib import Path
1111
from typing import Dict, IO, List, Optional, Union
1212

13+
import json
1314
import logging
1415
import os
1516
import socket
1617
import ssl
17-
import ujson
1818

1919
Config = Dict[str, Union[None, str, int, bool, List[str], AccessLogger]]
2020
LOG = logging.getLogger(__name__)
@@ -154,13 +154,13 @@ def validate_config(config: Config) -> None:
154154

155155

156156
def write_config(config_path: Path, custom_values: Config) -> None:
157-
config_path.write_text(ujson.dumps(custom_values))
157+
config_path.write_text(json.dumps(custom_values))
158158

159159

160160
def read_config(config_handler: IO) -> Config:
161161
try:
162-
config = ujson.load(config_handler)
163-
except ValueError as ex:
162+
config = json.load(config_handler)
163+
except json.JSONDecodeError as ex:
164164
raise InvalidConfiguration("Configuration is not a valid JSON") from ex
165165

166166
return set_config_defaults(config)

karapace/kafka_rest_apis/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818

1919
import asyncio
2020
import base64
21+
import json
2122
import time
22-
import ujson
2323

2424
RECORD_KEYS = ["key", "value", "partition"]
2525
PUBLISH_KEYS = {"records", "value_schema", "value_schema_id", "key_schema", "key_schema_id"}
@@ -544,7 +544,7 @@ async def serialize(
544544
# not pretty
545545
if ser_format == "json":
546546
# TODO -> get encoding from headers
547-
return ujson.dumps(obj).encode("utf8")
547+
return json.dumps(obj).encode("utf8")
548548
if ser_format == "binary":
549549
return base64.b64decode(obj)
550550
if ser_format in {"avro", "jsonschema", "protobuf"}:

karapace/kafka_rest_apis/consumer_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515

1616
import asyncio
1717
import base64
18+
import json
1819
import logging
1920
import time
20-
import ujson
2121
import uuid
2222

2323
KNOWN_FORMATS = {"json", "avro", "binary", "jsonschema", "protobuf"}
@@ -506,7 +506,7 @@ async def deserialize(self, bytes_: bytes, fmt: str):
506506
if fmt in {"avro", "jsonschema", "protobuf"}:
507507
return await self.deserializer.deserialize(bytes_)
508508
if fmt == "json":
509-
return ujson.loads(bytes_.decode("utf-8"))
509+
return json.loads(bytes_.decode("utf-8"))
510510
return base64.b64encode(bytes_).decode("utf-8")
511511

512512
def close(self):

karapace/master_coordinator.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
from threading import Event, Thread
1414
from typing import Optional, Tuple
1515

16+
import json
1617
import logging
1718
import time
18-
import ujson
1919

2020
# SR group errors
2121
NO_ERROR = 0
@@ -42,7 +42,7 @@ def protocol_type(self):
4242
def get_identity(self, *, host, port, scheme, json_encode=True):
4343
res = {"version": 1, "host": host, "port": port, "scheme": scheme, "master_eligibility": self.master_eligibility}
4444
if json_encode:
45-
return ujson.dumps(res)
45+
return json.dumps(res)
4646
return res
4747

4848
def group_protocols(self):
@@ -55,7 +55,7 @@ def _perform_assignment(self, leader_id, protocol, members):
5555
urls = {}
5656
fallback_urls = {}
5757
for member_id, member_data in members:
58-
member_identity = ujson.loads(member_data.decode("utf8"))
58+
member_identity = json.loads(member_data.decode("utf8"))
5959
if member_identity["master_eligibility"] is True:
6060
urls[get_identity_url(member_identity["scheme"], member_identity["host"], member_identity["port"])] = (
6161
member_id,
@@ -72,7 +72,7 @@ def _perform_assignment(self, leader_id, protocol, members):
7272
# Protocol guarantees there is at least one member thus if urls is empty, fallback_urls cannot be
7373
chosen_url = sorted(fallback_urls, reverse=self.election_strategy.lower() == "highest")[0]
7474
schema_master_id, member_data = fallback_urls[chosen_url]
75-
member_identity = ujson.loads(member_data.decode("utf8"))
75+
member_identity = json.loads(member_data.decode("utf8"))
7676
identity = self.get_identity(
7777
host=member_identity["host"],
7878
port=member_identity["port"],
@@ -83,7 +83,7 @@ def _perform_assignment(self, leader_id, protocol, members):
8383

8484
assignments = {}
8585
for member_id, member_data in members:
86-
assignments[member_id] = ujson.dumps({"master": schema_master_id, "master_identity": identity, "error": error})
86+
assignments[member_id] = json.dumps({"master": schema_master_id, "master_identity": identity, "error": error})
8787
return assignments
8888

8989
def _on_join_prepare(self, generation, member_id):
@@ -98,7 +98,7 @@ def _on_join_complete(self, generation, member_id, protocol, member_assignment_b
9898
protocol,
9999
member_assignment_bytes,
100100
)
101-
member_assignment = ujson.loads(member_assignment_bytes.decode("utf8"))
101+
member_assignment = json.loads(member_assignment_bytes.decode("utf8"))
102102
member_identity = member_assignment["master_identity"]
103103

104104
master_url = get_identity_url(

karapace/protobuf/exception.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import ujson
1+
import json
22

33

44
class ProtobufParserRuntimeException(Exception):
@@ -30,7 +30,7 @@ class SchemaParseException(ProtobufException):
3030

3131

3232
def pretty_print_json(obj: str) -> str:
33-
return ujson.dumps(ujson.loads(obj), indent=2)
33+
return json.dumps(json.loads(obj), indent=2)
3434

3535

3636
class ProtobufSchemaResolutionException(ProtobufException):

karapace/rapu.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@
2020
import asyncio
2121
import cgi
2222
import hashlib
23+
import json
2324
import logging
2425
import re
2526
import time
26-
import ujson
2727

2828
SERVER_NAME = "Karapace/{}".format(__version__)
2929
JSON_CONTENT_TYPE = "application/json"
@@ -281,7 +281,7 @@ async def _handle_request(
281281
_, options = cgi.parse_header(rapu_request.get_header("Content-Type"))
282282
charset = options.get("charset", "utf-8")
283283
body_string = body.decode(charset)
284-
rapu_request.json = ujson.loads(body_string)
284+
rapu_request.json = json.loads(body_string)
285285
except UnicodeDecodeError:
286286
raise HTTPResponse( # pylint: disable=raise-missing-from
287287
body=f"Request body is not valid {charset}", status=HTTPStatus.BAD_REQUEST

karapace/schema_backup.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
from typing import Dict, List, Optional, Tuple
1616

1717
import argparse
18+
import json
1819
import logging
1920
import os
2021
import sys
2122
import time
22-
import ujson
2323

2424
LOG = logging.getLogger(__name__)
2525

@@ -138,7 +138,7 @@ def close(self):
138138
def request_backup(self):
139139
values = self._export()
140140

141-
ser = ujson.dumps(values)
141+
ser = json.dumps(values)
142142
if self.backup_location:
143143
with open(self.backup_location, mode="w", encoding="utf8") as fp:
144144
fp.write(ser)
@@ -161,7 +161,7 @@ def restore_backup(self):
161161
values = None
162162
with open(self.backup_location, mode="r", encoding="utf8") as fp:
163163
raw_msg = fp.read()
164-
values = ujson.loads(raw_msg)
164+
values = json.loads(raw_msg)
165165

166166
if not values:
167167
return
@@ -184,7 +184,7 @@ def export_anonymized_avro_schemas(self):
184184
# Check that the message has key `schema` and type is Avro schema.
185185
# The Avro schemas may have `schemaType` key, if not present the schema is Avro.
186186
if value[1] and "schema" in value[1] and value[1].get("schemaType", "AVRO") == "AVRO":
187-
original_schema = ujson.loads(value[1].get("schema"))
187+
original_schema = json.loads(value[1].get("schema"))
188188
anonymized_schema = anonymize_avro.anonymize(original_schema)
189189
if anonymized_schema:
190190
if "subject" in value[0]:
@@ -193,7 +193,7 @@ def export_anonymized_avro_schemas(self):
193193
value[1]["subject"] = anonymize_avro.anonymize_name(value[1]["subject"])
194194
value[1]["schema"] = anonymized_schema
195195
anonymized_schemas.append((value[0], value[1]))
196-
ser = ujson.dumps(anonymized_schemas)
196+
ser = json.dumps(anonymized_schemas)
197197
if self.backup_location:
198198
with open(self.backup_location, mode="w", encoding="utf8") as fp:
199199
fp.write(ser)
@@ -220,15 +220,15 @@ def _export(self) -> List[Tuple[str, Dict[str, str]]]:
220220
for message in messages:
221221
key = message.key.decode("utf8")
222222
try:
223-
key = ujson.loads(key)
224-
except ValueError:
223+
key = json.loads(key)
224+
except json.JSONDecodeError:
225225
LOG.debug("Invalid JSON in message.key: %r, value: %r", message.key, message.value)
226226
value = None
227227
if message.value:
228228
value = message.value.decode("utf8")
229229
try:
230-
value = ujson.loads(value)
231-
except ValueError:
230+
value = json.loads(value)
231+
except json.JSONDecodeError:
232232
LOG.debug("Invalid JSON in message.value: %r, key: %r", message.value, message.key)
233233
values.append((key, value))
234234

karapace/schema_models.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from typing import Any, Dict, Union
1717

1818
import json
19-
import ujson
2019

2120

2221
def parse_avro_schema_definition(s: str) -> AvroSchema:
@@ -44,7 +43,7 @@ def parse_jsonschema_definition(schema_definition: str) -> Draft7Validator:
4443
Raises:
4544
SchemaError: If `schema_definition` is not a valid Draft7 schema.
4645
"""
47-
schema = ujson.loads(schema_definition)
46+
schema = json.loads(schema_definition)
4847
Draft7Validator.check_schema(schema)
4948
return Draft7Validator(schema)
5049

@@ -89,7 +88,7 @@ def __init__(self, schema_type: SchemaType, schema_str: str):
8988
def to_dict(self) -> Dict[str, Any]:
9089
if self.schema_type is SchemaType.PROTOBUF:
9190
raise InvalidSchema("Protobuf do not support to_dict serialization")
92-
return ujson.loads(self.schema_str)
91+
return json.loads(self.schema_str)
9392

9493
def __str__(self) -> str:
9594
if self.schema_type == SchemaType.PROTOBUF:
@@ -119,14 +118,14 @@ def parse(schema_type: SchemaType, schema_str: str) -> "ValidatedTypedSchema":
119118
if schema_type is SchemaType.AVRO:
120119
try:
121120
parsed_schema = parse_avro_schema_definition(schema_str)
122-
except (SchemaParseException, ValueError, TypeError) as e:
121+
except (SchemaParseException, json.JSONDecodeError, TypeError) as e:
123122
raise InvalidSchema from e
124123

125124
elif schema_type is SchemaType.JSONSCHEMA:
126125
try:
127126
parsed_schema = parse_jsonschema_definition(schema_str)
128127
# TypeError - Raised when the user forgets to encode the schema as a string.
129-
except (TypeError, ValueError, SchemaError, AssertionError) as e:
128+
except (TypeError, json.JSONDecodeError, SchemaError, AssertionError) as e:
130129
raise InvalidSchema from e
131130

132131
elif schema_type is SchemaType.PROTOBUF:

karapace/schema_reader.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
from threading import Event, Lock, Thread
1818
from typing import Any, Dict, Optional
1919

20+
import json
2021
import logging
21-
import ujson
2222

2323
Offset = int
2424
Subject = str
@@ -260,16 +260,16 @@ def handle_messages(self) -> None:
260260
for _, msgs in raw_msgs.items():
261261
for msg in msgs:
262262
try:
263-
key = ujson.loads(msg.key.decode("utf8"))
264-
except ValueError:
263+
key = json.loads(msg.key.decode("utf8"))
264+
except json.JSONDecodeError:
265265
LOG.exception("Invalid JSON in msg.key")
266266
continue
267267

268268
value = None
269269
if msg.value:
270270
try:
271-
value = ujson.loads(msg.value.decode("utf8"))
272-
except ValueError:
271+
value = json.loads(msg.value.decode("utf8"))
272+
except json.JSONDecodeError:
273273
LOG.exception("Invalid JSON in msg.value")
274274
continue
275275

@@ -348,8 +348,8 @@ def _handle_msg_schema(self, key: dict, value: Optional[dict]) -> None:
348348
# what is available in the topic.
349349
if schema_type_parsed in [SchemaType.AVRO, SchemaType.JSONSCHEMA]:
350350
try:
351-
schema_str = ujson.dumps(ujson.loads(schema_str), sort_keys=True)
352-
except ValueError:
351+
schema_str = json.dumps(json.loads(schema_str), sort_keys=True)
352+
except json.JSONDecodeError:
353353
LOG.error("Schema is not invalid JSON")
354354
return
355355

karapace/schema_registry_apis.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import aiohttp
1919
import async_timeout
2020
import asyncio
21+
import json
2122
import time
2223

2324

@@ -784,7 +785,7 @@ def write_new_schema_local(
784785
new_schema = ValidatedTypedSchema.parse(schema_type=schema_type, schema_str=body["schema"])
785786
except (InvalidSchema, InvalidSchemaType) as e:
786787
self.log.warning("Invalid schema: %r", body["schema"], exc_info=True)
787-
if isinstance(e.__cause__, (SchemaParseException, ValueError)):
788+
if isinstance(e.__cause__, (SchemaParseException, json.JSONDecodeError)):
788789
human_error = f"{e.__cause__.args[0]}" # pylint: disable=no-member
789790
else:
790791
human_error = "Provided schema is not valid"

karapace/serialization.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
import avro
1414
import avro.schema
1515
import io
16+
import json
1617
import struct
17-
import ujson
1818

1919
START_BYTE = 0x0
2020
HEADER_FORMAT = ">bI"
@@ -247,7 +247,7 @@ def read_value(config: dict, schema: TypedSchema, bio: io.BytesIO):
247247
reader = DatumReader(writers_schema=schema.schema)
248248
return reader.read(BinaryDecoder(bio))
249249
if schema.schema_type is SchemaType.JSONSCHEMA:
250-
value = ujson.load(bio)
250+
value = json.load(bio)
251251
try:
252252
schema.schema.validate(value)
253253
except ValidationError as e:

karapace/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
from types import MappingProxyType
1616
from typing import NoReturn, overload, Union
1717

18+
import json
1819
import kafka.client_async
1920
import logging
2021
import time
21-
import ujson
2222

2323
NS_BLACKOUT_DURATION_SECONDS = 120
2424
LOG = logging.getLogger(__name__)
@@ -71,7 +71,7 @@ def default_json_serialization( # pylint: disable=inconsistent-return-statement
7171

7272

7373
def json_encode(obj, *, sort_keys: bool = True, binary=False):
74-
res = ujson.dumps(
74+
res = json.dumps(
7575
obj,
7676
sort_keys=sort_keys,
7777
default=default_json_serialization,

mypy.ini

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@ warn_no_return = True
1111
warn_unreachable = True
1212
strict_equality = True
1313

14-
[mypy-ujson]
15-
ignore_errors = True
16-
ignore_missing_imports = True
17-
1814
[mypy-karapace.schema_registry_apis]
1915
ignore_errors = True
2016

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ requests==2.27.1
88
networkx==2.5
99
python-dateutil==2.8.2
1010
protobuf==3.19.4
11-
ujson==5.1.0
1211
avro==1.11.0
1312
# Patched dependencies
1413
#

0 commit comments

Comments
 (0)