JackDB 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jackdb/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Init file for the JackDB package"""
2
+ import logging
3
+ from jackdb.main import JackDB
4
+
5
+ VERSION = "0.3.2"
6
+
7
+ __version__ = VERSION
8
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
jackdb/api.py ADDED
@@ -0,0 +1,75 @@
1
+ """Module that builds the API for JackDB"""
2
+ from fastapi import FastAPI, HTTPException
3
+ from fastapi.encoders import jsonable_encoder
4
+
5
+ from jackdb.core import JackDB
6
+ from jackdb.api_models import PutModel, SetModel, DeleteResponse
7
+ from jackdb.exceptions import JdbException
8
+
9
+
10
+ def serve_routes(db_name: str, db: JackDB) -> FastAPI:
11
+ """
12
+ Create the API routes for JackDB
13
+ :param db_name:
14
+ :param db:
15
+ :return:
16
+ """
17
+ app = FastAPI()
18
+
19
+ path_prefix = f"/{db_name}"
20
+
21
+ @app.get(path_prefix + "/size")
22
+ def get_size():
23
+ return len(db)
24
+
25
+ @app.get(path_prefix + "/get/{db_key}")
26
+ def get_item(db_key: str):
27
+ op = {
28
+ 'op': 'get',
29
+ 'k': db_key
30
+ }
31
+ return db.do_operation(op)
32
+
33
+ @app.put(path_prefix + "/put/{db_key}")
34
+ def put_item(db_key: str, db_value: PutModel):
35
+ encoded_item = jsonable_encoder(db_value)
36
+ op = {
37
+ 'op': 'put',
38
+ 'k': db_key,
39
+ 'v': encoded_item['value']
40
+ }
41
+ result = db.execute_and_commit(op)
42
+ return result[-1].result
43
+
44
+ @app.put(path_prefix + "/set/{db_key}")
45
+ def set_item(db_key: str, db_value: SetModel):
46
+ encoded_item = jsonable_encoder(db_value)
47
+ op = {
48
+ 'op': 'set',
49
+ 'k': db_key,
50
+ 'f': encoded_item['field'],
51
+ 'v': encoded_item['value']
52
+ }
53
+ try:
54
+ result = db.execute_and_commit(op)
55
+ if result[-1].error:
56
+ raise result[-1].error
57
+ except JdbException as exc:
58
+ raise HTTPException(status_code=409, detail="Error occurred during operation.") from exc
59
+ return result[-1].result
60
+
61
+ @app.delete(path_prefix + "/del/{db_key}")
62
+ def del_item(db_key: str):
63
+ op = {
64
+ 'op': 'del',
65
+ 'k': db_key
66
+ }
67
+ try:
68
+ result = db.execute_and_commit(op)
69
+ if result[-1].error:
70
+ raise result[-1].error
71
+ except JdbException as exc:
72
+ raise HTTPException(status_code=409, detail="Error occurred during operation.") from exc
73
+ return DeleteResponse(message="Item successfully deleted.", id=db_key)
74
+
75
+ return app
jackdb/api_models.py ADDED
@@ -0,0 +1,34 @@
1
+ """Module containing models to be used for API operations"""
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class PutModel(BaseModel):
6
+ """
7
+ PUT body with a required string or JSON object value.
8
+ Objects may contain any nested JSON values, lists, numbers and booleans.
9
+
10
+ Nulls are not supported by this HTTP endpoint.
11
+ """
12
+ value: str | int | float | dict | list | bool
13
+
14
+
15
+ class SetModel(BaseModel):
16
+ """
17
+ PUT body with a required string or JSON object value.
18
+ Field field is a required string.
19
+ Value field may contain any nested JSON values, lists, numbers and booleans.
20
+
21
+ Nulls are not supported by this HTTP endpoint.
22
+ """
23
+ field: str
24
+ value: str | int | float | dict | list | bool
25
+
26
+
27
+ class DeleteResponse(BaseModel):
28
+ """
29
+ DELETE Response body.
30
+
31
+ Nulls are not supported by this HTTP endpoint.
32
+ """
33
+ message: str
34
+ id: int | str
@@ -0,0 +1,54 @@
1
+ """Model for commit queue objects"""
2
+
3
+
4
+ class CommitQueueItem:
5
+ """
6
+ Class to be used for the database commit records
7
+ """
8
+
9
+ def __init__(self, handler, args, record):
10
+ self._handler = handler
11
+ self._args = args
12
+ self._record = record
13
+ self.error = None
14
+ self.result = None
15
+
16
+ @property
17
+ def handler(self) -> str:
18
+ """
19
+ Returns the handler property.
20
+ :return:
21
+ """
22
+ return self._handler
23
+
24
+ @property
25
+ def args(self):
26
+ """
27
+ Returns the args property.
28
+ :return:
29
+ """
30
+ return self._args
31
+
32
+ @property
33
+ def record(self):
34
+ """
35
+ Returns the record property.
36
+ :return:
37
+ """
38
+ return self._record
39
+
40
+ def set_error(self, error):
41
+ """
42
+ Set error for item
43
+ :param error:
44
+ :return:
45
+ """
46
+ self.error = error
47
+
48
+ def set_result(self, result):
49
+ """
50
+ Set result for item
51
+ :param result:
52
+ :return:
53
+ """
54
+ self.result = result
jackdb/core.py ADDED
@@ -0,0 +1,500 @@
1
+ """Database storage and operations, independent of the API layer."""
2
+ import json
3
+ import tempfile
4
+ import os
5
+ import fcntl
6
+ import threading
7
+ from contextlib import contextmanager
8
+ from copy import deepcopy
9
+ from io import TextIOWrapper
10
+ from json import JSONDecodeError
11
+ from jackdb.logger import logger
12
+ from jackdb.exceptions import JdbException
13
+ from jackdb.operations import _resolve
14
+ from jackdb.commit_record import CommitQueueItem
15
+
16
+
17
+ class JackDB:
18
+ """An embedded key-value database backed by a JSON Lines append-only log.
19
+
20
+ Every mutation (``put``/``del``) is recorded in memory and appended to the
21
+ log file when :meth:`flush_logs` is called. On open, the log is replayed in
22
+ order (later records win) to rebuild the in-memory dictionary; a torn final
23
+ line from a crash mid-write is discarded, so the database always opens to a
24
+ consistent prefix of the log.
25
+
26
+ Writers on the same log file are serialized across processes by an
27
+ exclusive ``flock`` on a sidecar lock file (``replay_path + ".lock"``).
28
+ """
29
+
30
+ def __init__(self, replay_path: str = "", auto_commit: bool = True,
31
+ commit_size: int = 1, db_name: None | str = None):
32
+ """Open (or create) the log file and replay it into memory.
33
+
34
+ :param replay_path: Path to the JSON Lines log file. Required.
35
+ :param auto_commit: Whether autocommit is enabled or not.
36
+ :param commit_size: Size of uncommitted logs before auto committing.
37
+ :raises ValueError: If ``replay_path`` is empty.
38
+ """
39
+ self.replay_file: TextIOWrapper
40
+ self.data_dict = {}
41
+ self.replay_path = replay_path
42
+ self.records = []
43
+ self.log_length = 0
44
+ self.auto_commit = auto_commit
45
+ self.commit_size = commit_size
46
+ self.db_name = db_name
47
+
48
+ self._log_version = None
49
+ self._lock = threading.RLock()
50
+
51
+ if self.replay_path == "":
52
+ logger.critical("replay_path is required")
53
+ raise ValueError("replay_path is required")
54
+
55
+ self.load_from_file()
56
+
57
+ def __enter__(self):
58
+ return self
59
+
60
+ def __exit__(self, exc_type, exc_val, exc_tb):
61
+ self.commit()
62
+ return False
63
+
64
+ def __len__(self):
65
+ return len(self.data_dict)
66
+
67
+ def __contains__(self, item):
68
+ return item in self.data_dict
69
+
70
+ def __iter__(self):
71
+ return iter(self.data_dict)
72
+
73
+ def __getitem__(self, key):
74
+ return deepcopy(self.data_dict[key])
75
+
76
+ def keys(self):
77
+ """
78
+ Return a set of the keys from the data dict.
79
+ :return:
80
+ """
81
+ return self.data_dict.keys()
82
+
83
+ @contextmanager
84
+ def _log_lock(self):
85
+ """Exclusive lock on a sidecar lock file, serializing ``commit`` and
86
+ ``compact`` across processes.
87
+
88
+ The lock lives on ``replay_path + ".lock"`` — a path that is never
89
+ replaced — because ``compact`` swaps the log's inode via ``os.replace``,
90
+ so a lock held on the log file itself would not exclude writers that
91
+ open the new inode.
92
+ """
93
+ with open(self.replay_path + ".lock", "a+", encoding='utf-8') as lock_file:
94
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
95
+ try:
96
+ yield
97
+ finally:
98
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
99
+
100
+ def load_from_file(self) -> bool:
101
+ """Replay the log file from the start into ``data_dict``.
102
+
103
+ Invalid records are skipped.
104
+
105
+ A torn final line (and anything after it) is discarded and truncated
106
+ away so the next append cannot merge onto it. Afterward ``log_length``
107
+ marks how many records were already persisted, so only new records get
108
+ flushed.
109
+
110
+ Holds the log lock while reading and truncating: a concurrent commit's
111
+ partially written line must not be mistaken for a torn tail and cut
112
+ away (the writer already counted it as persisted).
113
+
114
+ :return: The success of loading the replay file.
115
+ """
116
+ with self._log_lock():
117
+ if not self.has_new_line():
118
+ logger.info("Adding new line to end of replay file.")
119
+ self.add_new_line()
120
+
121
+ self.records = [] # rebuilt below: ``records`` mirrors the file
122
+ data_dict = {}
123
+ self.log_length, torn, bad_records = self._replay_log(data_dict, journal=True)
124
+ self.data_dict = data_dict
125
+ self._log_version = self._file_version(os.stat(self.replay_path))
126
+ if len(bad_records) > 0:
127
+ logger.debug("logs rejected on replay.")
128
+ return not torn
129
+
130
+ @staticmethod
131
+ def _file_version(stat: os.stat_result) -> tuple:
132
+ """Identify the log and detect changes made by cooperating writers."""
133
+ return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
134
+
135
+ def _replay_log(self, db: dict, journal: bool = False) -> tuple:
136
+ """Apply every complete, valid record in the log file to ``data_dict``.
137
+
138
+ Stops at the first line that is not valid JSON (a torn final line);
139
+ the fragment and everything after it is truncated away so the file ends
140
+ cleanly after the last valid record.
141
+
142
+ :param db: Database to use.
143
+ :param journal: When True (initial load), also append each record to
144
+ ``records`` so the in-memory bookkeeping mirrors the file — this is
145
+ what keeps ``log_length`` aligned and stops ``commit`` from
146
+ re-writing or skipping already-persisted records. Compaction
147
+ replays with journal=False and tracks its own pending slice.
148
+ :return: Tuple of (number of records applied, whether a torn tail was
149
+ found and truncated, and records rejected.).
150
+ """
151
+ with open(self.replay_path, "rb") as byte_file:
152
+ raw = byte_file.read()
153
+
154
+ offset = 0 # byte offset just past the last complete, valid record
155
+ count = 0
156
+ bad_records = []
157
+ tail_offset = 0
158
+
159
+ for line in raw.split(b'\n'):
160
+ offset += len(line) + 1 # +1 for the '\n'
161
+
162
+ try:
163
+ record = json.loads(line)
164
+ except (JSONDecodeError, UnicodeDecodeError):
165
+ continue
166
+
167
+ tail_offset = offset
168
+
169
+ try:
170
+ self._apply(db, record)
171
+ if journal:
172
+ self.records.append(record)
173
+ count += 1
174
+ except (JdbException, TypeError):
175
+ bad_records.append(record)
176
+ continue
177
+
178
+ torn = tail_offset < len(raw)
179
+ if torn:
180
+ with open(self.replay_path, "r+b") as byte_file:
181
+ logger.error("Torn tail in fail, truncating file.")
182
+ byte_file.truncate(tail_offset)
183
+ return count, torn, bad_records
184
+
185
+ def _apply(self, db: dict, record):
186
+ """Validate and execute one operation record without journaling it.
187
+
188
+ Used for log replay, where the record is already persisted.
189
+
190
+ :param db: Database to use.
191
+ :return: The result of the underlying do_* handler call.
192
+ """
193
+ _, handler_name, args = _resolve(record)
194
+ if args[0] and not isinstance(args[0], str):
195
+ logger.error("Operation key field must be of type str.")
196
+ raise JdbException("Operation key field must be of type str.", 7)
197
+ args = [db] + args
198
+ return getattr(self, handler_name)(*args)
199
+
200
+ def execute_and_commit(self, operation) -> list[CommitQueueItem]:
201
+ """
202
+ Execute, commit, and returns a list of the mutating operation results.
203
+ :param operation: A dict (or JSON string) with an ``op`` key —
204
+ ``put`` (``k``, ``v``), ``del`` (``k``), ``get`` (``k``),
205
+ ``get_many`` (``k``) or ``set`` (``k``, ``f``, ``v``).
206
+ :return:
207
+ """
208
+ with self._lock:
209
+ try:
210
+ record = json.loads(operation) if not isinstance(operation, dict) else operation
211
+ except JSONDecodeError as e:
212
+ raise JdbException("Operation is not valid JSON.", 5) from e
213
+
214
+ journaled, handler_name, args = _resolve(record)
215
+ if journaled:
216
+ self._enqueue(handler_name, args, record)
217
+ results = self.commit()
218
+ return results
219
+
220
+ def do_operation(self, operation):
221
+ """Execute one database operation given as a dict or a JSON string.
222
+
223
+ Mutating operations (``put``, ``del``, ``set``) append to the pending
224
+ record list; read operations (``get``, ``get_many``) write nothing to
225
+ the log. Operation shape is driven by ``OPERATION_SPECS``.
226
+
227
+ :param operation: A dict (or JSON string) with an ``op`` key —
228
+ ``put`` (``k``, ``v``), ``del`` (``k``), ``get`` (``k``),
229
+ ``get_many`` (``k``) or ``set`` (``k``, ``f``, ``v``).
230
+ :return: The result of the underlying do_* handler call.
231
+ :raises JdbException: If the operation is not valid JSON, has an
232
+ unknown ``op`` or is missing required fields.
233
+ """
234
+ with self._lock:
235
+ try:
236
+ record = json.loads(operation) if not isinstance(operation, dict) else operation
237
+ except JSONDecodeError as e:
238
+ raise JdbException("Operation is not valid JSON.", 5) from e
239
+
240
+ journaled, handler_name, args = _resolve(record)
241
+
242
+ if journaled:
243
+ self._enqueue(handler_name, args, record)
244
+ result = {"status": "pending"}
245
+ # Placed in this block so only mutating operations trigger auto commit.
246
+ if self.auto_commit and self.log_length <= (len(self.records) - self.commit_size):
247
+ self.commit()
248
+ else:
249
+ result = getattr(self, handler_name)(*args)
250
+
251
+ return result
252
+
253
+ def _enqueue(self, handler_name, args, record):
254
+ # Deep copy to prevent the record being changed as easily
255
+ item = deepcopy(CommitQueueItem(handler_name, args, record))
256
+ self.records.append(item)
257
+ return item
258
+
259
+ def do_put(self, db: dict, key: str, value):
260
+ """Store ``value`` under ``key``, overwriting any existing value.
261
+
262
+ :param db: Database to use.
263
+ :param key: Database key.
264
+ :param value: Value to store (anything JSON-serializable).
265
+ :return: The stored value.
266
+ """
267
+ db[key] = value
268
+ return deepcopy(db[key])
269
+
270
+ def do_del(self, db: dict, key: str) -> bool:
271
+ """Remove ``key`` and its value from the database.
272
+
273
+ :param db: Database to use.
274
+ :param key: Database key.
275
+ :return: True if the key existed and was removed, False otherwise.
276
+ """
277
+ try:
278
+ del db[key]
279
+ return True
280
+ except KeyError:
281
+ return False
282
+
283
+ def do_get(self, key: str):
284
+ """Retrieve the value stored under a key.
285
+
286
+ :param key: Database key.
287
+ :return: The value, or None if the key is missing.
288
+ """
289
+ return deepcopy(self.data_dict.get(key))
290
+
291
+ def do_get_many(self, keys: list[str]):
292
+ """Retrieve values in bulk.
293
+
294
+ :param keys: Array of database keys.
295
+ :return: A list of tuples containing key and value.
296
+ """
297
+ results = []
298
+ for key in keys:
299
+ result = deepcopy((key, self.data_dict.get(key)))
300
+ results.append(result)
301
+ return results
302
+
303
+ def do_set(self, db: dict, key: str, field, value):
304
+ """Set a field of an already existing entry. Allowing for partial updates.
305
+
306
+ :param db: Database to use.
307
+ :param key: Database key.
308
+ :param field: Field key.
309
+ :param value: The value.
310
+ :return:
311
+ """
312
+ try:
313
+ db_data = db[key]
314
+ except KeyError as e:
315
+ raise JdbException("Key does not exist.", 2) from e
316
+ if not isinstance(db_data, dict):
317
+ raise JdbException("Field must contain JSON data.", 1)
318
+
319
+ db_data[field] = value
320
+ db[key] = db_data
321
+
322
+ return deepcopy(db[key])
323
+
324
+ def commit(self) -> list[CommitQueueItem]:
325
+ """Append all pending records to the log file and flush it to disk.
326
+
327
+ This is the commit point: a record mutated in memory only survives a
328
+ crash or reopen once it has been flushed. Already-persisted records
329
+ (up to ``log_length``) are never written twice.
330
+ """
331
+ with self._lock:
332
+ if self.log_length == len(self.records):
333
+ logger.info("No new records to commit.")
334
+ return []
335
+
336
+ with self._log_lock(), open(self.replay_path, "a+b", buffering=0) as replay_file:
337
+ # Reuse the cached state only while it matches the current log.
338
+ log_stat = os.fstat(replay_file.fileno())
339
+
340
+ if self._file_version(log_stat) == self._log_version:
341
+ # Our version of the dict is the most current
342
+ data_dict_copy = deepcopy(self.data_dict)
343
+ else:
344
+ # Our file has been modified, and must reload dict from file
345
+ logger.warning("Replay file modified, reloading database from file.")
346
+ data_dict_copy = {}
347
+ self._replay_log(data_dict_copy)
348
+ log_stat = os.fstat(replay_file.fileno())
349
+
350
+ log_offset = self.log_length
351
+ original_file_size = log_stat.st_size
352
+ results = []
353
+ encoded_strings = []
354
+ try:
355
+ pending_records = []
356
+
357
+ # Create our pending records queue
358
+ while log_offset < len(self.records):
359
+ record: CommitQueueItem = self.records[log_offset]
360
+ string_record = json.dumps(record.record) + '\n'
361
+ encoded_string = string_record.encode('utf-8')
362
+ pending_records.append((record, encoded_string))
363
+ log_offset += 1
364
+
365
+ # Apply the record to the temp dict and add results to the record
366
+ for record, encoded_string in pending_records:
367
+ try:
368
+ result = getattr(self, record.handler)(data_dict_copy, *record.args)
369
+ # Check the amount of bytes written versus string length
370
+ record.result = result
371
+ results.append(record)
372
+ logger.debug("Applied record %s ", record.args[0])
373
+ encoded_strings.append(encoded_string)
374
+ except JdbException as e:
375
+ record.set_error(e)
376
+ results.append(record)
377
+ logger.debug("Failed applying record %s %s ",
378
+ record.args[0], record.args[1])
379
+ continue
380
+
381
+ # Write to log file
382
+ for encoded_string in encoded_strings:
383
+ written_bytes = replay_file.write(encoded_string)
384
+ # Check whether all bytes were written
385
+ if written_bytes != len(encoded_string):
386
+ raise OSError(f"Short journal write: "
387
+ f"wrote {written_bytes} of "
388
+ f"{len(encoded_string)} bytes")
389
+
390
+ # Apply the changes
391
+ replay_file.flush()
392
+ os.fsync(replay_file.fileno())
393
+ self._log_version = self._file_version(os.fstat(replay_file.fileno()))
394
+ self.data_dict = data_dict_copy
395
+ logger.debug("Changes applied successfully.")
396
+ except OSError as e:
397
+ # Rollback the file
398
+ logger.exception(e)
399
+ os.ftruncate(replay_file.fileno(), original_file_size)
400
+ os.fsync(replay_file.fileno())
401
+ raise
402
+ self.log_length = log_offset
403
+ logger.debug("Commit finished.")
404
+ return results
405
+
406
+ def compact(self):
407
+ """Rewrite the log as one ``put`` record per live key, dropping
408
+ tombstones and superseded records.
409
+
410
+ Also commits: ``data_dict`` already includes unflushed mutations.
411
+
412
+ Holds the log lock for the whole rewrite and first replays everything
413
+ already committed to the file — including records written by other
414
+ processes since this instance opened — so the swap cannot drop records
415
+ it never saw.
416
+
417
+ :raises OSError: If the log directory is unwritable, the disk is full,
418
+ or the atomic swap fails. The old log is left untouched.
419
+ :raises TypeError: If a stored value is not JSON-serializable.
420
+ """
421
+ with self._lock:
422
+ logger.debug("Compacting replay file.")
423
+ temp_name = ""
424
+ new_records = []
425
+ with self._log_lock():
426
+ # Rebuild in-memory state from the file as it exists right now,
427
+ # then re-apply this instance's still-pending mutations on top
428
+ # (this instance commits last, so its pending records win).
429
+ pending = self.records[self.log_length:]
430
+ pending_dict_copy = {}
431
+
432
+ logger.debug("Replaying log file.")
433
+ self._replay_log(pending_dict_copy)
434
+ logger.debug("Replay finished.\n Applying pending records.")
435
+
436
+ for record in pending:
437
+ handler = record.handler
438
+ args = record.args
439
+ getattr(self, handler)(pending_dict_copy, *args)
440
+ logger.debug("Pending records applied.")
441
+
442
+ dir_fd = os.open(os.path.dirname(self.replay_path) or '.', os.O_RDONLY)
443
+ try:
444
+ with tempfile.NamedTemporaryFile(
445
+ mode="w", dir=os.path.dirname(self.replay_path) or ".",
446
+ prefix="jackdb-compact-", suffix=".json", delete=False
447
+ ) as temp_file:
448
+ temp_name = temp_file.name
449
+
450
+ logger.debug("Writing database to temporary file.")
451
+
452
+ for key, value in pending_dict_copy.items():
453
+ temp_record = {"op": "put", "k": key, "v": value}
454
+ new_records.append(temp_record)
455
+ temp_file.write(json.dumps(temp_record) + '\n')
456
+
457
+ logger.debug("Database written to temporary file.\n Flushing to disk.")
458
+
459
+ temp_file.flush()
460
+ os.fsync(temp_file.fileno())
461
+ os.replace(temp_name, self.replay_path)
462
+ os.fsync(dir_fd)
463
+ self._log_version = self._file_version(os.fstat(temp_file.fileno()))
464
+
465
+ logger.debug("Replay file replaced with temporary file.")
466
+ except Exception:
467
+ logger.critical("Error compacting file. Removing temporary file.")
468
+ if temp_name and os.path.exists(temp_name):
469
+ os.remove(temp_name)
470
+ raise
471
+ finally:
472
+ os.close(dir_fd)
473
+ self.data_dict = pending_dict_copy
474
+
475
+ self.records = new_records
476
+ self.log_length = len(new_records)
477
+ logger.debug("Compact finished.")
478
+
479
+ def has_new_line(self):
480
+ """
481
+ Check whether a file has a new line at the end of it.
482
+ :return: Bool: If a new line is found at the end of the file.
483
+ """
484
+ with open(self.replay_path, 'a+b') as f:
485
+ try:
486
+ # Move the file pointer to 1 byte before the end of the file
487
+ f.seek(-1, 2)
488
+ last_char = f.read(1)
489
+ return last_char == b'\n'
490
+ except OSError:
491
+ # The file is likely empty
492
+ return False
493
+
494
+ def add_new_line(self):
495
+ """
496
+ Add a new line to the end of a file.
497
+ :return:
498
+ """
499
+ with open(self.replay_path, "a+", encoding='utf-8') as f:
500
+ f.write("\n")
jackdb/exceptions.py ADDED
@@ -0,0 +1,13 @@
1
+ """Module for exception class for JackDB"""
2
+
3
+
4
+ class JdbException(Exception):
5
+ """Exception related to JackDB."""
6
+
7
+ def __init__(self, message, error_code):
8
+ self.message = message
9
+ self.error_code = error_code
10
+ super().__init__(self.message)
11
+
12
+ def __str__(self):
13
+ return f"{self.message} (Error Code: {self.error_code})"
jackdb/logger.py ADDED
@@ -0,0 +1,4 @@
1
+ """Module for logger setup."""
2
+ import logging
3
+
4
+ logger = logging.getLogger(__name__)
jackdb/main.py ADDED
@@ -0,0 +1,23 @@
1
+ """Public JackDB class with optional API setup."""
2
+ from jackdb.core import JackDB as CoreJackDB
3
+ from jackdb.api import serve_routes
4
+ from jackdb.exceptions import JdbException
5
+
6
+
7
+ class JackDB(CoreJackDB):
8
+ """An embedded database that can also expose an API when named."""
9
+
10
+ def __init__(self, replay_path: str = "", auto_commit: bool = True,
11
+ commit_size: int = 1, db_name: None | str = None):
12
+ super().__init__(replay_path, auto_commit, commit_size, db_name)
13
+ self.api = None
14
+ if self.db_name:
15
+ self.serve()
16
+
17
+ def serve(self):
18
+ """
19
+ Build and attach the API app for this database.
20
+ """
21
+ if self.db_name is None:
22
+ raise JdbException("Database name must be set before serving API", 6)
23
+ self.api = serve_routes(self.db_name, self)
jackdb/operations.py ADDED
@@ -0,0 +1,37 @@
1
+ """Module containing specification for the operations."""
2
+ from jackdb.exceptions import JdbException
3
+
4
+ OPERATION_SPECS = {
5
+ # op: (required fields, journaled, handler)
6
+ "put": (("k", "v"), True, "do_put"),
7
+ "del": (("k",), True, "do_del"),
8
+ "get": (("k",), False, "do_get"),
9
+ "get_many": (("k",), False, "do_get_many"),
10
+ "set": (("k", "f", "v"), True, "do_set"),
11
+ }
12
+ OPERATION_TYPES = list(OPERATION_SPECS)
13
+
14
+
15
+ def _resolve(record):
16
+ """Validate one operation record's shape against ``OPERATION_SPECS``.
17
+
18
+ :return: Tuple of (journaled, handler name, extracted arguments).
19
+ :raises JdbException: On unknown ``op`` or missing required fields.
20
+ """
21
+ try:
22
+ op_code = record["op"]
23
+ except (KeyError, TypeError) as e:
24
+ raise JdbException("Can not parse operation key.", 4) from e
25
+
26
+ spec = OPERATION_SPECS.get(op_code)
27
+ if spec is None:
28
+ raise JdbException("Unsupported operation type.", 3)
29
+
30
+ fields, journaled, handler_name = spec
31
+ args = []
32
+ for field_name in fields:
33
+ try:
34
+ args.append(record[field_name])
35
+ except KeyError as e:
36
+ raise JdbException("Can not parse key value", 4) from e
37
+ return journaled, handler_name, args
@@ -0,0 +1,302 @@
1
+ Metadata-Version: 2.4
2
+ Name: JackDB
3
+ Version: 0.3.2
4
+ Summary: Simple embedded key-value database
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/gamecube7561/JackDB
7
+ Project-URL: Issues, https://github.com/gamecube7561/JackDB/issues
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: fastapi[standard]>=0.162.0
12
+ Requires-Dist: pydantic>=2.14.2
13
+ Dynamic: license-file
14
+
15
+ # JackDB
16
+
17
+ JackDB is an embedded Python key-value database backed by a JSON Lines
18
+ append-only log. Data is held in memory, replayed from disk when opened, and
19
+ persisted through explicit or automatic commits. Reads see an instance's
20
+ committed state. JackDB can compact the log and expose the database through
21
+ FastAPI size, get, put, set, and del endpoints.
22
+
23
+ [![Pylint](https://github.com/gamecube7561/JackDB/actions/workflows/pylint.yml/badge.svg)](https://github.com/gamecube7561/JackDB/actions/workflows/pylint.yml)
24
+ [![Tests](https://github.com/gamecube7561/JackDB/actions/workflows/tests.yml/badge.svg)](https://github.com/gamecube7561/JackDB/actions/workflows/tests.yml)
25
+ ## Quick Start
26
+
27
+ Requires Python 3.10+ and a Unix-like system such as Linux or macOS. File
28
+ locking uses `fcntl`, so native Windows is currently unsupported.
29
+
30
+ By default, JackDB attempts to commit each write immediately.
31
+
32
+ From the repository root:
33
+
34
+ ```bash
35
+ python -m pip install .
36
+ ```
37
+
38
+
39
+
40
+ ```python
41
+ from jackdb import JackDB
42
+
43
+ with JackDB("./mydb.log") as db:
44
+ db.do_operation({"op": "put", "k": "user:1", "v": {"name": "Aoba"}})
45
+ db.do_operation({"op": "set", "k": "user:1", "f": "state", "v": "NY"})
46
+ user = db.do_operation({"op": "get", "k": "user:1"})
47
+ print(user) # {'name': 'Aoba', 'state': 'NY'}
48
+ ```
49
+ Installing the project uses `pyproject.toml`, which declares
50
+ `fastapi[standard]` and `pydantic`. FastAPI's standard extras include Uvicorn.
51
+ `requirements.txt` contains an exported, pinned dependency set.
52
+
53
+ ## Usage
54
+
55
+ ```python
56
+ from jackdb import JackDB
57
+
58
+ with JackDB("./mydb.log", auto_commit=False) as db:
59
+ receipt = db.do_operation({"op": "put", "k": "user:1", "v": {"name": "Aoba"}})
60
+ print(receipt) # {'status': 'pending'}
61
+ db.do_operation({"op": "set", "k": "user:1", "f": "state", "v": "NY"})
62
+ db.commit()
63
+ user = db.do_operation({"op": "get", "k": "user:1"})
64
+ print(user) # {'name': 'Aoba', 'state': 'NY'}
65
+ print(len(db)) # 1
66
+ ```
67
+
68
+ `from jackdb.main import JackDB` also remains supported. Operations accept
69
+ Python dictionaries or JSON strings. Use string keys and JSON-serializable
70
+ values. Replay rejects nonempty non-string keys, even if the live write
71
+ accepted them. Tuples in values become lists after reopening.
72
+
73
+ ### Constructor
74
+
75
+ ```python
76
+ from jackdb import JackDB
77
+
78
+ JackDB(replay_path="./mydb.log", auto_commit=True, commit_size=1, db_name=None)
79
+ ```
80
+
81
+ | Argument | Behavior |
82
+ |---------------|-----------------------------------------------------------------------------------------------------------------------|
83
+ | `replay_path` | Required nonempty string path. Creates the log if absent; its parent directory must already exist. |
84
+ | `auto_commit` | Enables automatic commits during `do_operation()`. Defaults to `True`. |
85
+ | `commit_size` | Commits when pending records **reach** this number. The default `1` commits on the first pending mutation. |
86
+ | `db_name` | A nonempty name builds a FastAPI app and attaches it as `db.api`. By default, both `db_name` and `db.api` are `None`. |
87
+
88
+ ### Operations
89
+
90
+ Call these through `db.do_operation(record)`:
91
+
92
+ | `op` | Required fields | Read result or successful commit result |
93
+ |------------|----------------------|----------------------------------------------------------------------------------|
94
+ | `put` | `k`, `v` | Stores or overwrites a value and returns it. |
95
+ | `del` | `k` | Removes a key; returns `True` if present, otherwise `False`. |
96
+ | `get` | `k` | Returns a value, or `None` when absent. |
97
+ | `get_many` | `k` (a list of keys) | Returns `(key, value)` tuples in input order; missing values are `None`. |
98
+ | `set` | `k`, `f`, `v` | Sets a field on an existing dictionary value and returns the updated dictionary. |
99
+
100
+ `put`, `del`, and `set` queue a copy of the operation and return
101
+ `{"status": "pending"}`, even when the call triggers an automatic commit.
102
+ `get` and `get_many` read committed values and add no records.
103
+ A stored `None` and a missing key both return `None`; use `key in db` to
104
+ check existence. The database also supports `len(db)`, `db[key]`, iteration
105
+ over keys, and `db.keys()`. `db[key]` raises `KeyError` for a missing key.
106
+ Reads return deep copies of stored values. The lower-level `do_put`, `do_del`,
107
+ and `do_set` methods operate on a supplied dictionary and bypass journaling.
108
+
109
+ ### Persistence and recovery
110
+
111
+ ```python
112
+ from jackdb import JackDB
113
+
114
+ db = JackDB("./mydb.log", auto_commit=False)
115
+ results = db.execute_and_commit({"op": "put", "k": "cfg", "v": [1, 2, 3]})
116
+ print(results[-1].result) # [1, 2, 3]
117
+ ```
118
+
119
+ `commit()` applies pending mutations in order to a working copy, appends
120
+ accepted records, and publishes the updated in-memory state after flushing
121
+ and syncing the log. It returns a list of `CommitQueueItem` objects in queue
122
+ order, or an empty list when there are no pending operations. Each item
123
+ exposes `.result` on success or `.error` if the operation raised
124
+ `JdbException` during application. For example, a rejected `set` is skipped
125
+ while other valid writes in the batch can still commit.
126
+
127
+ Use `execute_and_commit()` with a mutation to queue it and immediately commit
128
+ it alongside any earlier pending writes. To inspect a batch of queued writes,
129
+ disable automatic commits and inspect the result of an explicit `commit()`.
130
+ Pending writes can be lost if the process exits before committing. The
131
+ context manager commits on exit even if its body raises an exception.
132
+
133
+ The log stores one operation per line:
134
+
135
+ ```jsonl
136
+ {"op":"put","k":"user:1","v":{"name":"Aoba","score":10}}
137
+ {"op":"del","k":"user:2"}
138
+ {"op":"set","k":"user:1","f":"state","v":"NY"}
139
+ ```
140
+
141
+ Opening a database replays records in order, with later operations taking
142
+ precedence. Replay skips blank lines, malformed JSON, and invalid UTF-8
143
+ and continues reading later records. On open, JackDB truncates these lines
144
+ when they follow the last line that parses as JSON. This removes incomplete
145
+ final writes as well as malformed trailing lines that end with a newline.
146
+ A line that parses as JSON but is rejected during replay, such as an unknown
147
+ operation, is skipped and preserved. On open, JackDB adds a newline to a
148
+ log that lacks a final line break before replaying it.
149
+
150
+ ### Compaction and concurrency
151
+
152
+ ```python
153
+ from jackdb import JackDB
154
+
155
+ db = JackDB("./mydb.log", auto_commit=False)
156
+ db.compact()
157
+ ```
158
+
159
+ `compact()` rewrites the log as one `put` record per live key, removing
160
+ superseded records and deletion tombstones. It includes pending mutations,
161
+ so successful compaction also persists those writes. If applying a pending
162
+ operation raises an error, compaction raises it. Use `commit()` to get
163
+ individual operation results. The replacement is written and synced in a temporary
164
+ file beside the log, installed with `os.replace()`, and followed by a directory
165
+ sync. Filesystem and serialization errors propagate to the caller.
166
+
167
+ A reentrant lock serializes `do_operation()`, `commit()`, and `compact()`
168
+ within an instance. A sidecar file at `<replay_path>.lock` serializes log
169
+ loading, commits, and compaction across cooperating processes. A commit with
170
+ pending writes replays the log if it has changed since the instance last
171
+ loaded or wrote it. Compaction always replays the latest log before applying
172
+ pending writes.
173
+
174
+ Other instances do not automatically refresh their in-memory data after a
175
+ writer commits. File locking does not make multiple operations a transaction
176
+ or provide fully synchronized reads across instances. Direct `do_*` calls
177
+ also bypass the instance lock.
178
+
179
+ ### Error handling
180
+
181
+ ```python
182
+ from jackdb.exceptions import JdbException
183
+ from jackdb import JackDB
184
+
185
+ try:
186
+ db = JackDB("./mydb.log", auto_commit=False)
187
+ db.do_operation({"op": "unknown"})
188
+ except JdbException as error:
189
+ print(error.message, error.error_code)
190
+ ```
191
+
192
+ | Error code | Cause |
193
+ |------------|-------------------------------------------------|
194
+ | `1` | `set` targets a value that is not a dictionary. |
195
+ | `2` | `set` targets a missing key. |
196
+ | `3` | Unsupported operation name. |
197
+ | `4` | Missing operation key or required field. |
198
+ | `5` | Operation text is not valid JSON. |
199
+ | `6` | Database name must be set before serving API. |
200
+ | `7` | Replay found a nonempty non-string key. |
201
+
202
+ An empty log path raises `ValueError`. Filesystem errors and unsupported
203
+ Python input types may raise standard exceptions; operation validation does
204
+ not cover every possible malformed input.
205
+
206
+ JackDB uses Python's standard logging. Configure the `jackdb` logger in your
207
+ application to see diagnostics for replay, commits, and compaction.
208
+
209
+ ## HTTP API
210
+
211
+ A named database attaches a FastAPI application. To run it with Uvicorn:
212
+
213
+ ```python
214
+ from jackdb import JackDB
215
+ import uvicorn
216
+
217
+ if __name__ == "__main__":
218
+ db = JackDB("./mydb.log", db_name="demo")
219
+ uvicorn.run(db.api, host="127.0.0.1", port=8000)
220
+ ```
221
+
222
+ `GET http://127.0.0.1:8000/demo/size` returns the current number of keys as a
223
+ JSON integer. FastAPI's interactive documentation is available at `/docs`.
224
+
225
+ `GET /demo/get/{key}` returns the stored JSON value, or `null` if the key is
226
+ missing. `PUT /demo/put/{key}` accepts a body such as
227
+ `{"value": "hello"}` or `{"value": {"name": "Aoba", "score": 10}}` and
228
+ returns the stored value. `PUT /demo/set/{key}` accepts a body such as
229
+ `{"field": "score", "value": 123}`. SET adds or updates a field on an existing
230
+ JSON object and returns the updated object. A missing key or a value that is
231
+ not an object returns HTTP 409. Each successful PUT commits pending operations
232
+ before responding, regardless of `auto_commit`.
233
+
234
+ `DELETE /demo/del/{key}` takes no request body, removes the key if present,
235
+ and commits pending operations. It returns HTTP 200 with
236
+ `{"message": "Item successfully deleted.", "id": "<key>"}` even if the key
237
+ was already absent.
238
+
239
+ Both PUT endpoints require a `value` field and accept strings, integers,
240
+ fractional numbers, JSON objects, arrays, and booleans. Objects and arrays can
241
+ contain nested JSON values, including null. A top-level null or an omitted
242
+ `value` returns HTTP 422. SET also requires a string `field`; a missing field
243
+ or a non-string field returns HTTP 422. The embedded storage API additionally
244
+ supports top-level null. Keys must fit in a single URL path segment;
245
+ slash-containing keys are not supported.
246
+
247
+ `db.serve()` builds or replaces `db.api`; it does not start a server. To attach
248
+ an API later, set a nonempty `db.db_name` and call `db.serve()`. Applications
249
+ can also use `serve_routes(name, db)` from `jackdb.api` directly.
250
+
251
+ ## Project layout
252
+
253
+ ```text
254
+ src/jackdb/__init__.py # Public JackDB export and version
255
+ src/jackdb/main.py # Public JackDB subclass and API attachment
256
+ src/jackdb/core.py # Storage, replay, operations, commit, compaction
257
+ src/jackdb/api.py # FastAPI application and routes
258
+ src/jackdb/api_models.py # Models for FastAPI
259
+ src/jackdb/operations.py # Operation specifications and validation
260
+ src/jackdb/commit_record.py # Queued operations and commit results
261
+ src/jackdb/logger.py # Library logger
262
+ src/jackdb/exceptions.py # JdbException
263
+ tests/test_core.py # Custom runner with 24 database/API checks
264
+ tests/test_items.py # Test data
265
+ ```
266
+
267
+ The dependency graph is `main → api → core`, with `main → core` as well.
268
+ The API accepts the core `JackDB` type, and the public class inherits its
269
+ database methods. The core module has no dependency on the API layer.
270
+
271
+ ## Development
272
+
273
+ Run commands from the repository root. With [uv](https://docs.astral.sh/uv/):
274
+
275
+ ```bash
276
+ uv sync
277
+ PYTHONPATH=src uv run --no-sync python tests/test_core.py
278
+ ```
279
+
280
+ Setting `PYTHONPATH=src` ensures tests use the checkout, including on systems
281
+ where editable-install discovery is unreliable. The custom runner prints
282
+ passed and failed counts and exits with status 1 if any check fails.
283
+
284
+ To run the same lint command as GitHub Actions:
285
+
286
+ ```bash
287
+ python -m pip install pylint .
288
+ pylint $(git ls-files '*.py')
289
+ ```
290
+
291
+ GitHub Actions runs Pylint on pushes for Python 3.10 through 3.14.
292
+
293
+ After changing dependencies in `pyproject.toml`, update the lockfile and
294
+ regenerate the requirements export. The lockfile is local and ignored by Git.
295
+
296
+ ```bash
297
+ uv lock
298
+ uv export --locked --no-dev --no-emit-project --no-hashes -o requirements.txt
299
+ ```
300
+
301
+ Keep `pyproject.toml` as the source of dependency declarations and regenerate
302
+ `requirements.txt` instead of editing the export by hand.
@@ -0,0 +1,14 @@
1
+ jackdb/__init__.py,sha256=-4rsOOq-6S4hdOrm6_zUTHGvaiX44c2VTmskW2BIVO0,189
2
+ jackdb/api.py,sha256=AzT9sEodkt9h74lGvTPG1c-RNLAyjZ7Ivmhj034zA4Q,2204
3
+ jackdb/api_models.py,sha256=pMKFrrRCrsaH0CgSFWYSa7tWzwpzzMeJpqcWLQ-iK0M,877
4
+ jackdb/commit_record.py,sha256=icq2sBq_ukqDD9nOokzERnWpRXJeB7gTDyJ1qHZ5wls,1059
5
+ jackdb/core.py,sha256=UqB4XDv7pF13XuH9pjhEvKanzo-9xA7dsjPON3hAasc,20383
6
+ jackdb/exceptions.py,sha256=4pXBihYSYOZPXuP7F9ynCdZ70WxAH1sxMbELIcK8A30,358
7
+ jackdb/logger.py,sha256=pU5spTWSSGy9P7C99ByqTeEIAkHCrREWY97DBISnOrY,84
8
+ jackdb/main.py,sha256=C60GjG5WfV9dNTN20rXGm36DHa-2N65zc6xFyY-svdQ,831
9
+ jackdb/operations.py,sha256=aHjisPPquKR87fDtlRz67uzJKLB0waSr7D3GxZyAOO8,1226
10
+ jackdb-0.3.2.dist-info/licenses/LICENSE,sha256=rzPPc0HDuJCsnL1BiFjCh4qS1aduoYqZV_V6mS73IaU,1069
11
+ jackdb-0.3.2.dist-info/METADATA,sha256=fsJxl95RAfZmJ_E12rqEwSPCuhD-uKkXsjuerh5bcO8,13285
12
+ jackdb-0.3.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ jackdb-0.3.2.dist-info/top_level.txt,sha256=D7rdYojbkGjGV7-IaHCQQB1-H9A0jIEqNpVClUoYDto,7
14
+ jackdb-0.3.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jack Kennedy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ jackdb