Skip to content
This repository was archived by the owner on Jan 17, 2025. It is now read-only.

Commit 654aff0

Browse files
authored
use bson instead of json in StoredDict (#120)
1 parent c769b67 commit 654aff0

File tree

4 files changed

+29
-11
lines changed

4 files changed

+29
-11
lines changed

.mypy.ini

+3
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,6 @@ disallow_untyped_decorators = False
3838
[mypy-pwnlib]
3939
ignore_missing_imports = True
4040

41+
[mypy-bson]
42+
ignore_missing_imports = True
43+

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
setuptools.setup(
1111
name="enochecker",
12-
version="0.4.0",
12+
version="0.4.1",
1313
author="domenukk",
1414
author_email="[email protected]",
1515
description="Library to build checker scripts for EnoEngine A/D CTF Framework in Python",

src/enochecker/storeddict.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Backend for team_db based on a local filesystem directory."""
22

3-
import json
43
import logging
54
import os
65
import threading
@@ -10,6 +9,8 @@
109
from pathlib import Path
1110
from typing import Any, Callable, Dict, Iterator, Optional, Set
1211

12+
import bson
13+
1314
from .utils import base64ify, debase64ify, ensure_valid_filename
1415

1516
logging.basicConfig(level=logging.DEBUG)
@@ -22,7 +23,7 @@
2223
6 # 2**6 / 10 seconds are 6.4 secs. -> That's how long the db will wait for a log
2324
)
2425
DB_PREFIX = "_store_" # Prefix all db files will get
25-
DB_EXTENSION = ".json" # Extension all db files will get
26+
DB_EXTENSION = ".bson" # Extension all db files will get
2627
DB_LOCK_EXTENSION = ".lock" # Extension all lock folders will get
2728
DB_GLOBAL_CACHE_SETTING = True
2829

@@ -129,9 +130,9 @@ def _dir(self, key: str) -> str:
129130
"""
130131
return os.path.join(self.path, DB_PREFIX + base64ify(key, b"+-"))
131132

132-
def _dir_jsonname(self, key: str) -> str:
133+
def _dir_bsonname(self, key: str) -> str:
133134
"""
134-
Return the path for the json db file for this key.
135+
Return the path for the bson db file for this key.
135136
136137
See :func:`_dir`
137138
"""
@@ -240,7 +241,7 @@ def persist(self) -> None:
240241
locked = self.is_locked(key) or self.ignore_locks
241242
if not locked:
242243
self.lock(key)
243-
os.remove(self._dir_jsonname(key))
244+
os.remove(self._dir_bsonname(key))
244245
if not locked:
245246
self.release(key)
246247
self.logger.debug(f"Deleted {key} from db {self.name}")
@@ -251,8 +252,8 @@ def persist(self) -> None:
251252
if not locked:
252253
self.lock(key)
253254
try:
254-
with open(self._dir_jsonname(key), "wb") as f:
255-
f.write(json.dumps(self._cache[key]).encode("utf-8"))
255+
with open(self._dir_bsonname(key), "wb") as f:
256+
f.write(bson.BSON.encode({"value": self._cache[key]}))
256257
finally:
257258
if not locked:
258259
self.release(key)
@@ -272,9 +273,9 @@ def __getitem__(self, key: str) -> Any:
272273
if not locked:
273274
self.lock(key)
274275
try:
275-
with open(self._dir_jsonname(key), "rb") as f:
276-
val = json.loads(f.read().decode("utf-8"))
277-
except (OSError, json.decoder.JSONDecodeError) as ex:
276+
with open(self._dir_bsonname(key), "rb") as f:
277+
val = bson.BSON(f.read()).decode()["value"]
278+
except (OSError, bson.errors.BSONError) as ex:
278279
raise KeyError("Key {} not found - {}".format(key, ex))
279280
finally:
280281
if not locked:

tests/test_enochecker.py

+14
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,20 @@ def test_dict():
171171
assert len(db) == 0
172172

173173

174+
@pytest.mark.parametrize(
175+
"value", [b"binarydata", {"test": b"test", "test2": 123}, ["asd", 123, b"xyz"]]
176+
)
177+
@temp_storage_dir
178+
def test_storeddict_complex_types(value):
179+
db = enochecker.storeddict.StoredDict(name="test", base_path=STORAGE_DIR)
180+
181+
db["test"] = value
182+
db.persist()
183+
184+
db.reload()
185+
assert db["test"] == value
186+
187+
174188
@temp_storage_dir
175189
def test_checker():
176190
flag = "ENOFLAG"

0 commit comments

Comments
 (0)