-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_table.py
More file actions
1008 lines (849 loc) · 36.2 KB
/
_table.py
File metadata and controls
1008 lines (849 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Table class for JSONLT file operations.
This module provides the Table class, the primary interface for working
with JSONLT files. It handles file loading, auto-reload, and read/write operations.
"""
# pyright: reportImportCycles=false
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, cast
from typing_extensions import override
from ._constants import JSONLT_VERSION, MAX_RECORD_SIZE
from ._encoding import validate_no_surrogates
from ._exceptions import (
ConflictError,
FileError,
InvalidKeyError,
LimitError,
TransactionError,
)
from ._filesystem import FileSystem, RealFileSystem
from ._header import Header, serialize_header
from ._json import serialize_json, utf8_byte_length
from ._keys import (
Key,
KeySpecifier,
key_specifiers_match,
normalize_key_specifier,
validate_key_arity,
validate_key_length,
)
from ._mixin import TableMixin
from ._reader import parse_table_content
from ._records import build_tombstone, extract_key, validate_record
from ._state import compute_logical_state
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from ._json import JSONObject, JSONValue
from ._transaction import Transaction
__all__ = ["Table"]
class Table(TableMixin):
"""A JSONLT table backed by a file.
The Table class provides the primary interface for working with JSONLT
files. It loads the file, computes the logical state, and provides
methods for reading records.
The table supports auto-reload: before each read operation, it checks
if the underlying file has changed (by mtime and size) and reloads
the state if necessary. This can be disabled via `auto_reload=False`.
Example:
>>> table = Table("users.jsonlt", key="id")
>>> table.get("alice")
{'id': 'alice', 'role': 'admin'}
>>> table.has("bob")
False
>>> table.count()
1
"""
__slots__: ClassVar[tuple[str, ...]] = (
"_active_transaction",
"_auto_reload",
"_cached_sorted_keys",
"_file_mtime",
"_file_size",
"_fs",
"_header",
"_key_specifier",
"_lock_timeout",
"_max_file_size",
"_path",
"_state",
)
_path: Path
_key_specifier: "KeySpecifier | None"
_auto_reload: bool
_lock_timeout: float | None
_max_file_size: int | None
_fs: FileSystem
_header: "Header | None"
_state: "dict[Key, JSONObject]"
_file_mtime: float
_file_size: int
_active_transaction: "Transaction | None"
_cached_sorted_keys: list[Key] | None
def __init__(
self,
path: "Path | str",
key: "KeySpecifier | None" = None,
*,
auto_reload: bool = True,
lock_timeout: float | None = None,
max_file_size: int | None = None,
_fs: "FileSystem | None" = None,
) -> None:
"""Open or create a table at the given path.
Args:
path: Path to the JSONLT file.
key: Key specifier for the table. If the file has a header with
a key specifier, this must match or be omitted. If the file
has operations but no header, this is required.
auto_reload: If True (default), check for file changes before
each read operation and reload if necessary.
lock_timeout: Maximum seconds to wait for file lock on write
operations. None means wait indefinitely.
max_file_size: Maximum allowed file size in bytes when loading
the file. If the file exceeds this limit, LimitError is raised.
If None (default), no limit is enforced.
_fs: Internal filesystem abstraction for testing. Do not use.
Raises:
FileError: If the file cannot be read.
LimitError: If the file size exceeds max_file_size.
ParseError: If the file contains invalid content.
InvalidKeyError: If the key specifier is invalid or mismatches
the header, or if the file has operations but no key specifier
can be determined.
"""
self._path = Path(path) if isinstance(path, str) else path
self._auto_reload = auto_reload
self._lock_timeout = lock_timeout
self._max_file_size = max_file_size
self._fs = RealFileSystem() if _fs is None else _fs
# These will be set by _load()
self._header = None
self._state = {}
self._file_mtime = 0.0
self._file_size = 0
self._key_specifier = None
self._active_transaction = None
self._cached_sorted_keys = None
# Initial load
self._load(key)
@classmethod
def from_records( # noqa: PLR0913
cls,
path: "Path | str",
records: "Mapping[str, object] | Iterable[Mapping[str, object]]",
key: KeySpecifier,
*,
auto_reload: bool = True,
lock_timeout: float | None = None,
max_file_size: int | None = None,
_fs: "FileSystem | None" = None,
) -> "Table":
"""Create a table from a list of records.
Creates a new file at the specified path with the given records.
All records are validated before writing, and the file is written
atomically. If any record is invalid, no file is written.
A header with the key specifier is always written, making the
file self-describing.
Args:
path: Path to create the JSONLT file at.
records: A single record dict or iterable of record dicts.
key: Key specifier for the table.
auto_reload: If True (default), check for file changes before
each read operation and reload if necessary.
lock_timeout: Maximum seconds to wait for file lock on write
operations. None means wait indefinitely.
max_file_size: Maximum allowed file size in bytes when loading.
If the file exceeds this limit, LimitError is raised.
_fs: Internal filesystem abstraction for testing. Do not use.
Returns:
A new Table instance backed by the created file.
Raises:
InvalidKeyError: If any record is missing required key fields,
has invalid key values, or contains $-prefixed fields.
LimitError: If any key exceeds 1024 bytes or any record exceeds 1 MiB.
FileError: If the file cannot be created.
Example:
>>> table = Table.from_records(
... "users.jsonlt",
... [
... {"id": "alice", "role": "admin"},
... {"id": "bob", "role": "user"},
... ],
... key="id",
... )
>>> table.count()
2
"""
file_path = Path(path) if isinstance(path, str) else path
fs = RealFileSystem() if _fs is None else _fs
normalized_key = normalize_key_specifier(key)
# Normalize records: single dict -> list
if isinstance(records, dict):
record_list = cast("list[Mapping[str, object]]", [records])
else:
record_list = cast("list[Mapping[str, object]]", list(records))
# Build lines: header + validated records
lines: list[str] = [
serialize_header(Header(version=JSONLT_VERSION, key=normalized_key))
]
for index, record in enumerate(record_list):
try:
record_value = cast("JSONValue", record)
record_obj = cast("JSONObject", record)
validate_no_surrogates(record_value)
validate_record(record_obj, normalized_key)
extracted_key = extract_key(record_obj, normalized_key)
validate_key_length(extracted_key)
serialized = serialize_json(record)
if utf8_byte_length(serialized) > MAX_RECORD_SIZE:
msg = f"record size exceeds maximum {MAX_RECORD_SIZE}"
raise LimitError(msg) # noqa: TRY301
lines.append(serialized)
except (InvalidKeyError, LimitError) as e: # noqa: PERF203
msg = f"record at index {index}: {e}"
raise type(e)(msg) from e
fs.ensure_parent_dir(file_path)
fs.atomic_replace(file_path, lines)
return cls(
file_path,
key=normalized_key,
auto_reload=auto_reload,
lock_timeout=lock_timeout,
max_file_size=max_file_size,
_fs=_fs,
)
@classmethod
def from_file(
cls,
path: "Path | str",
key: "KeySpecifier | None" = None,
*,
auto_reload: bool = True,
lock_timeout: float | None = None,
max_file_size: int | None = None,
_fs: "FileSystem | None" = None,
) -> "Table":
"""Load a table from an existing file.
Opens an existing JSONLT file. If the file has a header with a
key specifier, uses that key. An explicit key parameter can be
provided to override or when the file has no header.
This method is semantically equivalent to the Table constructor
but explicitly indicates the intent to load an existing file
(as opposed to potentially creating a new one).
Args:
path: Path to the existing JSONLT file.
key: Optional key specifier. If None, auto-detected from the
file header. If provided, must match the header key (if any).
auto_reload: If True (default), check for file changes before
each read operation and reload if necessary.
lock_timeout: Maximum seconds to wait for file lock on write
operations. None means wait indefinitely.
max_file_size: Maximum allowed file size in bytes when loading.
If the file exceeds this limit, LimitError is raised.
_fs: Internal filesystem abstraction for testing. Do not use.
Returns:
A Table instance backed by the file.
Raises:
FileError: If the file does not exist or cannot be read.
InvalidKeyError: If no key specifier can be determined (file
has no header and key not provided), or if the provided
key doesn't match the header key.
ParseError: If the file contains invalid content.
Example:
>>> # File has header with key
>>> table = Table.from_file("users.jsonlt")
>>> table.key_specifier
'id'
>>> # File without header, provide key explicitly
>>> table = Table.from_file("data.jsonlt", key="name")
"""
file_path = Path(path) if isinstance(path, str) else path
fs = RealFileSystem() if _fs is None else _fs
stats = fs.stat(file_path)
if not stats.exists:
msg = f"file not found: {file_path}"
raise FileError(msg)
return cls(
file_path,
key=key,
auto_reload=auto_reload,
lock_timeout=lock_timeout,
max_file_size=max_file_size,
_fs=_fs,
)
def _load(self, caller_key: "KeySpecifier | None" = None) -> None:
"""Load or reload the table from disk.
This method reads the file, parses it, validates the key specifier,
and computes the logical state.
Args:
caller_key: Key specifier provided by caller (only used on
initial load, not on auto-reload).
Raises:
FileError: If the file cannot be read.
ParseError: If the file contains invalid content.
InvalidKeyError: If the key specifier is invalid or mismatches
the header, or if the file has operations but no key specifier.
"""
stats = self._fs.stat(self._path)
if not stats.exists:
self._load_empty_table(caller_key)
return
raw_bytes = self._fs.read_bytes(self._path, max_size=self._max_file_size)
header, operations = parse_table_content(raw_bytes)
self._header = header
self._update_file_stats()
resolved_key = self._resolve_key_specifier(caller_key, header, operations)
if resolved_key is None:
# Empty file with no key specifier - OK for now
self._key_specifier = None
self._state = {}
self._cached_sorted_keys = None
return
self._key_specifier = resolved_key
if operations:
self._state = compute_logical_state(operations, self._key_specifier)
else:
self._state = {}
self._cached_sorted_keys = None
def _load_from_content(self, content: bytes) -> None:
"""Load table state from bytes content.
This is used when we already have the file content in memory
(e.g., read via a locked file handle on Windows).
Args:
content: Raw bytes of the file content.
Raises:
ParseError: If the content contains invalid data.
"""
if not content:
self._state = {}
self._cached_sorted_keys = None
return
header, operations = parse_table_content(content)
self._header = header
# Resolve key specifier (use existing since this is a reload)
resolved_key = self._resolve_key_specifier(None, header, operations)
if resolved_key is None:
self._state = {}
self._cached_sorted_keys = None
return
self._key_specifier = resolved_key
if operations:
self._state = compute_logical_state(operations, self._key_specifier)
else:
self._state = {}
self._cached_sorted_keys = None
def _load_empty_table(self, caller_key: "KeySpecifier | None") -> None:
"""Initialize state for a non-existent file."""
self._header = None
self._state = {}
self._cached_sorted_keys = None
self._file_mtime = 0.0
self._file_size = 0
# For new files, use caller's key specifier if provided
if caller_key is not None:
self._key_specifier = normalize_key_specifier(caller_key)
# Otherwise keep existing key specifier (may be None)
def _update_file_stats(self) -> None:
"""Update cached file mtime and size for auto-reload detection."""
stats = self._fs.stat(self._path)
if not stats.exists:
msg = "cannot stat file: file does not exist"
raise FileError(msg)
self._file_mtime = stats.mtime
self._file_size = stats.size
def _try_update_stats(self) -> None:
"""Update cached file stats, ignoring errors."""
try:
stats = self._fs.stat(self._path)
if stats.exists:
self._file_mtime = stats.mtime
self._file_size = stats.size
except FileError:
# Ignore stat failures - stats will refresh on next read
pass
def _reload_if_changed(self, cached_mtime: float, cached_size: int) -> None:
"""Reload file if stats differ from cached values.
Called inside lock during transaction commit. If the file's mtime
and size match the cached values, the file is unchanged and we
skip the expensive reload.
Args:
cached_mtime: File mtime when transaction started.
cached_size: File size when transaction started.
"""
stats = self._fs.stat(self._path)
if not stats.exists:
self._load()
return
if stats.mtime != cached_mtime or stats.size != cached_size:
# File changed - full reload required
self._load()
# else: file unchanged, state is already current
def _resolve_key_specifier(
self,
caller_key: "KeySpecifier | None",
header: "Header | None",
operations: "list[JSONObject]",
) -> "KeySpecifier | None":
"""Resolve which key specifier to use.
Returns the resolved key specifier, or None if the file is empty
and no key specifier is available.
Raises:
InvalidKeyError: If caller and header key specifiers conflict,
or if operations exist but no key specifier is available.
"""
header_key = header.key if header is not None else None
if caller_key is not None and header_key is not None:
# Both provided - must match
caller_normalized = normalize_key_specifier(caller_key)
header_normalized = normalize_key_specifier(header_key)
if not key_specifiers_match(caller_normalized, header_normalized):
msg = (
f"key specifier mismatch: caller provided {caller_key!r} "
f"but header specifies {header_key!r}"
)
raise InvalidKeyError(msg)
return header_normalized
if header_key is not None:
return normalize_key_specifier(header_key)
if caller_key is not None:
return normalize_key_specifier(caller_key)
if self._key_specifier is not None:
# Keep existing key specifier (from initial load)
return self._key_specifier
if operations:
# File has operations but no key specifier - error
msg = (
"file has operations but no key specifier: "
"provide key parameter or add header with key field"
)
raise InvalidKeyError(msg)
# Empty file with no key specifier
return None
def _maybe_reload(self) -> None:
"""Check if file changed and reload if necessary.
This is called before read operations when auto_reload is enabled.
"""
if not self._auto_reload:
return
stats = self._fs.stat(self._path)
if not stats.exists:
# File was deleted - clear state
if self._file_size != 0 or self._file_mtime != 0.0:
self._header = None
self._state = {}
self._cached_sorted_keys = None
self._file_mtime = 0.0
self._file_size = 0
return
if stats.mtime != self._file_mtime or stats.size != self._file_size:
self._load()
@override
def _get_state(self) -> "dict[Key, JSONObject]":
"""Return the table state dictionary."""
return self._state
@override
def _prepare_read(self) -> None:
"""Check for file changes and reload if necessary."""
self._maybe_reload()
@property
def path(self) -> Path:
"""The path to the table file."""
return self._path
@property
def key_specifier(self) -> "KeySpecifier | None":
"""The key specifier for this table."""
return self._key_specifier
@property
def header(self) -> "Header | None":
"""The header of the table file, if present."""
self._maybe_reload()
return self._header
def reload(self) -> None:
"""Force a reload of the table from disk.
This method is useful when `auto_reload=False` and you want to
manually refresh the table state after external changes.
Raises:
FileError: If the file cannot be read.
ParseError: If the file contains invalid content.
"""
self._load()
self._cached_sorted_keys = None
def _require_key_specifier(self) -> KeySpecifier:
"""Return key specifier or raise InvalidKeyError if not set."""
if self._key_specifier is None:
msg = "key specifier is required for write operations"
raise InvalidKeyError(msg)
return self._key_specifier
@override
def _get_key_specifier(self) -> KeySpecifier:
"""Return the key specifier for this table.
Returns:
The key specifier.
Raises:
InvalidKeyError: If no key specifier is set.
"""
return self._require_key_specifier()
@override
def put(self, record: "JSONObject") -> None:
"""Insert or update a record.
Validates the record, serializes it deterministically, and appends
to the file under exclusive lock.
Args:
record: The record to insert/update. Must contain key fields.
Raises:
InvalidKeyError: If key specifier not set, record missing key fields,
has invalid key values, contains $-prefixed fields, or contains
unpaired surrogates.
LimitError: If key length > 1024 bytes or record size > 1 MiB.
LockError: If file lock cannot be acquired within timeout.
FileError: If file write fails.
"""
key_specifier = self._require_key_specifier()
# Check for unpaired surrogates in all strings
validate_no_surrogates(record)
# Validate record structure (missing fields, invalid key types, $ fields)
validate_record(record, key_specifier)
# Extract and validate key
key = extract_key(record, key_specifier)
validate_key_length(key)
# Serialize record
serialized = serialize_json(record)
record_bytes = utf8_byte_length(serialized)
if record_bytes > MAX_RECORD_SIZE:
msg = f"record size {record_bytes} bytes exceeds maximum {MAX_RECORD_SIZE}"
raise LimitError(msg)
# Write under lock (put doesn't return whether key existed)
_ = self._write_with_lock(serialized, key, record)
def _finalize_write(self, key: Key, record: "JSONObject | None") -> bool:
"""Update state after successful write. Returns whether key existed."""
existed = key in self._state
if record is not None:
self._state[key] = record
else:
_ = self._state.pop(key, None)
self._cached_sorted_keys = None
self._update_file_stats()
return existed
_MAX_WRITE_RETRIES: ClassVar[int] = 3
def _write_with_lock(
self,
line: str,
key: Key,
record: "JSONObject | None",
*,
_retries: int = 0,
) -> bool:
"""Write a line to the file under exclusive lock.
On Windows, LockFileEx prevents other handles (even from the same process)
from accessing the locked file. So we must read and write using the same
file handle that holds the lock.
Args:
line: The JSON line to write.
key: The key for state update.
record: The record to add to state, or None for delete.
_retries: Internal retry counter (do not pass externally).
Returns:
True if the key existed in the table (after reload), False otherwise.
"""
self._fs.ensure_parent_dir(self._path)
try:
with self._fs.open_locked(self._path, "r+b", self._lock_timeout) as f:
content = f.read()
self._load_from_content(content)
_ = f.seek(0, 2)
encoded = (line + "\n").encode("utf-8")
_ = f.write(encoded)
f.sync()
return self._finalize_write(key, record)
except FileNotFoundError:
try:
with self._fs.open_locked(self._path, "xb", self._lock_timeout) as f:
encoded = (line + "\n").encode("utf-8")
_ = f.write(encoded)
f.sync()
return self._finalize_write(key, record)
except FileExistsError:
if _retries >= self._MAX_WRITE_RETRIES:
msg = "cannot acquire stable file handle after multiple retries"
raise FileError(msg) from None
return self._write_with_lock(line, key, record, _retries=_retries + 1)
@override
def delete(self, key: Key) -> bool:
"""Delete a record by key.
Writes a tombstone to the file. Returns whether the record existed.
Args:
key: The key to delete. Must match key specifier arity.
Returns:
True if record existed, False otherwise.
Raises:
InvalidKeyError: If key specifier not set, key is invalid,
or key arity doesn't match specifier.
LockError: If file lock cannot be acquired within timeout.
FileError: If file write fails.
"""
key_specifier = self._require_key_specifier()
# Validate key arity matches specifier
validate_key_arity(key, key_specifier)
validate_key_length(key)
tombstone = build_tombstone(key, key_specifier)
serialized = serialize_json(tombstone)
return self._write_with_lock(serialized, key, None)
def clear(self) -> None:
"""Remove all records from the table.
Atomically replaces file with header only (if present).
Raises:
LockError: If file lock cannot be acquired within timeout.
FileError: If file operations fail.
"""
# Build lines: header only if present
lines: list[str] = []
if self._header is not None:
lines.append(serialize_header(self._header))
self._fs.ensure_parent_dir(self._path)
# Atomically replace file
# On Windows, we must release the lock before atomic_replace because
# you can't rename to a locked file. We accept the small race window.
stats = self._fs.stat(self._path)
if stats.exists:
# Read current content under lock
with self._fs.open_locked(self._path, "r+b", self._lock_timeout) as f:
content = f.read()
self._load_from_content(content)
lines = []
if self._header is not None:
lines.append(serialize_header(self._header))
# Lock released, now do atomic replace
self._fs.atomic_replace(self._path, lines)
self._state = {}
self._cached_sorted_keys = None
self._try_update_stats()
elif lines:
# File doesn't exist - create with header
# No lock needed since atomic_replace handles races via temp file
self._fs.atomic_replace(self._path, lines)
self._state = {}
self._cached_sorted_keys = None
self._try_update_stats()
else:
# No header, nothing to write for empty table
self._state = {}
self._cached_sorted_keys = None
def compact(self) -> None:
"""Compact the table to its minimal representation.
Rewrites the file atomically with only the header (if present) and
current records in key order. Removes all tombstones and superseded
record versions.
Raises:
LockError: If file lock cannot be acquired within timeout.
FileError: If file operations fail.
"""
self._fs.ensure_parent_dir(self._path)
# Atomically replace file with compacted content
stats = self._fs.stat(self._path)
if stats.exists:
with self._fs.open_locked(self._path, "r+b", self._lock_timeout) as f:
# Reload state using locked handle (Windows-compatible)
content = f.read()
self._load_from_content(content)
# Build lines from fresh state
lines: list[str] = []
if self._header is not None:
lines.append(serialize_header(self._header))
lines.extend(serialize_json(r) for r in self._sorted_records())
# Lock released, now do atomic replace (Windows can't rename locked)
self._fs.atomic_replace(self._path, lines)
self._try_update_stats()
elif self._header is not None or self._state:
# File doesn't exist but we have in-memory content - create it
# No lock needed since atomic_replace handles races via temp file
lines = []
if self._header is not None:
lines.append(serialize_header(self._header))
lines.extend(serialize_json(r) for r in self._sorted_records())
self._fs.atomic_replace(self._path, lines)
self._try_update_stats()
else:
# No header, no records - nothing to write
self._state = {}
# --- Transaction Operations ---
def transaction(self) -> "Transaction":
"""Start a new transaction.
Returns a Transaction object that provides snapshot isolation for reads
and buffered writes. Use as a context manager for automatic commit/abort.
Example:
>>> with table.transaction() as tx:
... tx.put({"id": "alice", "v": 1})
... tx.delete("bob")
... # Commits on successful exit
Returns:
A new Transaction.
Raises:
InvalidKeyError: If no key specifier is set.
TransactionError: If a transaction is already active.
"""
# Import here to avoid circular import at runtime
from ._transaction import Transaction as TransactionImpl # noqa: PLC0415
key_specifier = self._require_key_specifier()
if self._active_transaction is not None:
msg = "a transaction is already active on this table"
raise TransactionError(msg)
# Reload to get fresh state
self._maybe_reload()
# Create transaction with current state
tx: Transaction = TransactionImpl(self, key_specifier, self._state)
self._active_transaction = tx
return tx
def _end_transaction(self) -> None:
"""Clear the active transaction.
Called by Transaction.commit() and Transaction.abort().
"""
self._active_transaction = None
def _commit_transaction_buffer(
self,
lines: list[str],
start_state: "dict[Key, JSONObject]",
written_keys: set[Key],
buffer_updates: "dict[Key, JSONObject | None]",
start_size: int,
*,
_retries: int = 0,
) -> None:
"""Commit a transaction's buffered writes.
Called by Transaction.commit() to write buffered changes to the file.
Performs conflict detection and writes all lines under exclusive lock.
Args:
lines: Serialized JSON lines to append.
start_state: Snapshot of table state when transaction started.
written_keys: Keys that were modified in the transaction.
buffer_updates: Map of key -> record (or None for delete).
start_size: File size when transaction started.
_retries: Internal retry counter (do not pass externally).
Raises:
ConflictError: If a write-write conflict is detected.
LockError: If file lock cannot be acquired within timeout.
FileError: If file write fails.
"""
self._fs.ensure_parent_dir(self._path)
stats = self._fs.stat(self._path)
if stats.exists:
with self._fs.open_locked(self._path, "r+b", self._lock_timeout) as f:
# Read and reload if file changed (Windows-compatible)
content = f.read()
current_size = len(content)
if current_size != start_size:
# File changed - reload from content
self._load_from_content(content)
# Check for conflicts
self._detect_conflicts(start_state, written_keys)
# Write all buffered lines using same handle
_ = f.seek(0, 2) # Seek to end
for line in lines:
encoded = (line + "\n").encode("utf-8")
_ = f.write(encoded)
f.sync()
# Update state from buffer
self._apply_buffer_updates(buffer_updates)
self._try_update_stats()
else:
# File doesn't exist - create it
try:
with self._fs.open_locked(self._path, "xb", self._lock_timeout) as f:
# Check for conflicts (should be none since start_state
# was empty)
self._detect_conflicts(start_state, written_keys)
# Write all buffered lines
for line in lines:
encoded = (line + "\n").encode("utf-8")
_ = f.write(encoded)
f.sync()
# Update state from buffer
self._apply_buffer_updates(buffer_updates)
self._try_update_stats()
except FileExistsError:
# File was created between our check and open - retry
if _retries >= self._MAX_WRITE_RETRIES:
msg = "cannot acquire stable file handle after multiple retries"
raise FileError(msg) from None
self._commit_transaction_buffer(
lines,
start_state,
written_keys,
buffer_updates,
start_size,
_retries=_retries + 1,
)
def _detect_conflicts(
self,
start_state: "dict[Key, JSONObject]",
written_keys: set[Key],
) -> None:
"""Detect write-write conflicts.
For each key in written_keys, compare the current state (after reload)
with the start_state. If they differ, another process modified the
key since the transaction started.
Args:
start_state: Snapshot of table state when transaction started.
written_keys: Keys that were modified in the transaction.
Raises:
ConflictError: If a write-write conflict is detected.
"""
for key in written_keys:
key_in_current = key in self._state
key_in_start = key in start_state
# Check if key presence differs
if key_in_current != key_in_start:
msg = f"conflict detected: key {key!r} was modified externally"
expected = start_state.get(key)
actual = self._state.get(key)
raise ConflictError(msg, key, expected, actual)
# If neither has the key, no conflict
if not key_in_current:
continue
# Both have the key - compare records
if self._state[key] != start_state[key]:
msg = f"conflict detected: key {key!r} was modified externally"
expected = start_state.get(key)
actual = self._state.get(key)
raise ConflictError(msg, key, expected, actual)
def _apply_buffer_updates(
self,
buffer_updates: "dict[Key, JSONObject | None]",
) -> None:
"""Apply buffered updates to the table state.
Args:
buffer_updates: Map of key -> record (or None for delete).
"""
for key, record in buffer_updates.items():
if record is not None:
self._state[key] = record
else:
_ = self._state.pop(key, None)
self._cached_sorted_keys = None
@override
def __repr__(self) -> str:
"""Return a string representation of the table."""
return f"Table({self._path!r}, key={self._key_specifier!r})"
@override
def __eq__(self, other: object) -> bool:
"""Value equality based on path, key_specifier, and current state.
Two tables are equal if they have the same resolved path, key specifier,
and identical record state. Triggers auto-reload on self before comparison
to ensure current disk state is reflected.
Args:
other: Object to compare with.
Returns:
True if equal, False otherwise. Returns NotImplemented for non-Tables.
"""
if not isinstance(other, Table):
return NotImplemented
self._maybe_reload()
other._maybe_reload()
return (
self._path.resolve() == other._path.resolve()
and self._key_specifier == other._key_specifier