-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcontainer.py
2860 lines (2482 loc) · 133 KB
/
container.py
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
"""
The main implementation of the ``Container`` class of the object store.
"""
from __future__ import annotations
# pylint: disable=too-many-lines
import dataclasses
import io
import json
import os
import shutil
import uuid
from collections import defaultdict, namedtuple
from contextlib import contextmanager
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, overload
from sqlalchemy.orm.session import Session
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import delete, select, text, update
from .database import Obj, get_session
from .dataclasses import ObjectCount, ObjectMeta, TotalSize, ValidationIssues
from .exceptions import InconsistentContent, NotExistent, NotInitialised
from .utils import (
CallbackStreamWrapper,
CompressMode,
LazyLooseStream,
LazyOpener,
Location,
ObjectWriter,
PackedObjectReader,
StreamReadBytesType,
StreamSeekBytesType,
StreamWriteBytesType,
ZlibStreamDecompresser,
chunk_iterator,
compute_hash_and_size,
detect_where_sorted,
get_compressobj_instance,
get_hash_cls,
get_stream_decompresser,
is_known_hash,
merge_sorted,
nullcontext,
rename_callback,
safe_flush_to_disk,
should_compress,
yield_first_element,
)
if TYPE_CHECKING:
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
)
from mypy_extensions import Arg
ObjQueryResults = namedtuple(
"ObjQueryResults", ["hashkey", "offset", "length", "compressed", "size"]
)
class ObjectType(Enum):
"""Enum that describes the various types of an objec (as returned in ``meta['type']``)."""
LOOSE = "loose"
PACKED = "packed"
MISSING = "missing"
class Container: # pylint: disable=too-many-public-methods
"""A class representing a container of objects (which is stored on a disk folder)"""
_PACK_INDEX_SUFFIX = ".idx"
# Size in bytes of each of the chunks used when (internally) reading or writing in chunks, e.g.
# when packing.
_CHUNKSIZE = 65536
# The pack ID that is used for repacking as a temporary location.
# NOTE: It MUST be an integer and it MUST be < 0 to avoid collisions with 'actual' packs
_REPACK_PACK_ID = -1
# When performing an `in_` query in SQLite, this is converted to something like
# 'SELECT * FROM db_object WHERE db_object.hashkey IN (?, ?)' with parameters = ('hash1', 'hash2')
# Now, the maximum number of parameters is limited in SQLite, see variable SQLITE_MAX_VARIABLE_NUMBER
# as described in https://www.sqlite.org/limits.html
# Now, until recently (at the moment of writing) this defaults to 999 for SQLite versions
# prior to 3.32.0 (2020-05-22) or 32766 for SQLite versions after 3.32.0.
# So we need to assume that we cannot put more than 999 elements in the `.in_` parameter.
# Note that on some OSs, the value is increased at compile time. E.g. on my Mac OS X with python 3.6
# compiled with HomeBrew, the limit (I tested it) is 250000.
# See also e.g. this comment https://bugzilla.redhat.com/show_bug.cgi?id=1798134
_IN_SQL_MAX_LENGTH = 950
# If the length of required elements is larger than this, instead of iterating an IN statement over chunks of size
# _IN_SQL_MAX_LENGTH, it just quickly lists all elements (ordered by hashkey, requires a VACUUMed DB for
# performance) and returns only the intersection.
# This length might need some benchmarking, but seems OK on very large DBs of 6M nodes
# (after VACUUMing, as mentioned above).
_MAX_CHUNK_ITERATE_LENGTH = 9500
def __init__(self, folder: str | Path) -> None:
"""Create the class that represents the container.
:param folder: the path to a folder that will host this object-store container.
"""
self._folder = Path(folder).resolve()
# Will be populated by the _get_session function
self._session: Session | None = None
# These act as caches and will be populated by the corresponding properties
# IMPORANT! IF YOU ADD MORE, REMEMBER TO CLEAR THEM IN `init_container()`!
self._current_pack_id: int | None = None
self._config: dict | None = None
def get_folder(self) -> Path:
"""Return the path to the folder that will host the object-store container."""
return self._folder
def close(self) -> None:
"""Close open files (in particular, the connection to the SQLite DB)."""
if self._session is not None:
self._session.close()
self._session = None
def __enter__(self) -> Container:
"""Return a context manager that will close the session when exiting the context."""
return self
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
"""Close the session when exiting the context."""
self.close()
def _get_sandbox_folder(self) -> Path:
"""Return the path to the sandbox folder that is used during a new object creation.
It is a subfolder of the container folder.
"""
return self._folder / "sandbox"
def _get_loose_folder(self) -> Path:
"""Return the path to the folder that will host the loose objects.
It is a subfolder of the container folder.
"""
return self._folder / "loose"
def _get_pack_folder(self) -> Path:
"""Return the path to the folder that will host the packed objects.
It is a subfolder of the container folder.
"""
return self._folder / "packs"
def _get_duplicates_folder(self) -> Path:
"""Return the path to the folder that will host the duplicate loose objects that couldn't be written.
This should happen only in race conditions on Windows. See `utils.ObjectWriter.__exit__` for its usage, and
`utils._store_duplicate_copy`.
It is a subfolder of the container folder.
"""
return self._folder / "duplicates"
def _get_config_file(self) -> Path:
"""Return the path to the container config file."""
return self._folder / "config.json"
@overload
def _get_session(
self, create: bool = False, raise_if_missing: Literal[True] = True
) -> Session:
...
@overload
def _get_session(
self, create: bool = False, raise_if_missing: Literal[False] = False
) -> Session | None:
...
def _get_session(
self, create: bool = False, raise_if_missing: bool = False
) -> Session | None:
"""Return a new session to connect to the pack-index SQLite DB.
:param create: if True, creates the sqlite file and schema.
:param raise_if_missing: ignored if create==True. If create==False, and the index file
is missing, either raise an exception (FileNotFoundError) if this flag is True, or return None
"""
return get_session(
self._get_pack_index_path(),
create=create,
raise_if_missing=raise_if_missing,
)
def _get_cached_session(self) -> Session:
"""Return the SQLAlchemy session to access the SQLite file,
reusing the same one."""
# We want to catch both if it's missing, and if it's None
# the latter means that in the previous run the pack file was missing
# but maybe by now it has been created!
if self._session is None:
self._session = self._get_session(create=False, raise_if_missing=True)
return self._session
def _get_loose_path_from_hashkey(self, hashkey: str) -> Path:
"""Return the path of a loose object on disk containing the data of a given hash key.
:param hashkey: the hashkey of the object to get.
"""
if self.loose_prefix_len:
return (
self._get_loose_folder()
/ hashkey[: self.loose_prefix_len]
/ hashkey[self.loose_prefix_len :]
)
# if loose_prefix_len is zero, there is no subfolder
return self._get_loose_folder() / hashkey
def _get_pack_path_from_pack_id(
self, pack_id: str | int, allow_repack_pack: bool = False
) -> Path:
"""Return the path of the pack file on disk for the given pack ID.
:param pack_id: the pack ID.
:param pack_id: Whether to allow the repack pack id
"""
pack_id = str(pack_id)
assert self._is_valid_pack_id(
pack_id, allow_repack_pack=allow_repack_pack
), f"Invalid pack ID {pack_id}"
return self._get_pack_folder() / pack_id
def _get_pack_index_path(self) -> Path:
"""Return the path to the SQLite file containing the index of packed objects."""
return self._folder / f"packs{self._PACK_INDEX_SUFFIX}"
def _get_pack_id_to_write_to(self) -> int:
"""Return the pack ID to write the next object.
This function checks that there is a pack file with the current pack ID.
If it does not exist, that it returns that ID (the file is new and must be created).
If it exists, it returns the ID only if the size is smaller than the container's pack_size_target,
otherwise it increases by one until it finds a valid "non-full" pack ID.
:return: an integer pack ID.
"""
# Default to zero if not set (e.g. if it's None)
pack_id = self._current_pack_id or 0
while True:
pack_path = self._get_pack_path_from_pack_id(pack_id)
if not pack_path.exists():
# Use this ID - the pack file does not exist yet
break
if pack_path.stat().st_size < self.pack_size_target:
# Use this ID - the pack file is not "full" yet
break
# Try the next pack
pack_id += 1
# Cache the value
self._current_pack_id = pack_id
return pack_id
@property
def is_initialised(self) -> bool:
"""Return True if the container is already initialised."""
# If the config file does not exist, the container is not initialised
try:
with open(self._get_config_file(), encoding="utf8") as fhandle:
json.load(fhandle)
except (ValueError, OSError):
return False
# I also check that the four sub-folders exist
subfolders = [
self._get_pack_folder(),
self._get_loose_folder(),
self._get_duplicates_folder(),
self._get_sandbox_folder(),
]
for folder in subfolders:
if not folder.exists():
return False
return True
def init_container(
self,
clear: bool = False,
pack_size_target: int = 4 * 1024 * 1024 * 1024,
loose_prefix_len: int = 2,
hash_type: str = "sha256",
compression_algorithm: str = "zlib+1",
) -> None:
"""Initialise the container folder, if not already done.
If this is called multiple times, it does not corrupt the data,
unless you add the ``clear=True`` option.
:param clear: if True, delete everything in the container and
initialise a new, empty one.
:param pack_size_target: The minimum size (in bytes) of a pack file before
a new pack file is created. Pack files will be typically larger than this.
:param loose_prefix_len: The length of the prefix of the loose objects.
The longer the length, the more folders will be used to store loose
objects. Suggested values: 0 (for not using subfolders) or 2.
:param hash_type: a string defining the hash type to use.
:param compression_algorithm: a string defining the compression algorithm to use for compressed objects.
"""
if loose_prefix_len < 0:
raise ValueError(
"The loose prefix length can only be zero or a positive integer"
)
if pack_size_target <= 0:
raise ValueError(
"The pack size target can only be a non-zero positive integer"
)
if not is_known_hash(hash_type):
raise ValueError(f'Unknown hash type "{hash_type}"')
if clear:
if self._folder.exists():
shutil.rmtree(self._folder)
# Reinitialize the configuration cache, since this will change
# (at least the container_id, possibly the rest), and the other caches
self._config = None
self._current_pack_id = None
if self.is_initialised:
raise FileExistsError(
"The container already exists, so you cannot initialise it - "
"use the clear option if you want to overwrite with a clean one"
)
# If we are here, either the folder is empty, or just cleared.
# It could also be that one of the folders does not exist. This is considered an invalid situation.
# But this will be catched later, where I check that the folder is empty before overwriting the
# configuration file.
# In this case, I have to generate a new UUID to be used as the container_id
container_id = uuid.uuid4().hex
try:
os.makedirs(self._folder)
except FileExistsError:
# The directory already exists: it's ok
pass
if os.listdir(self._folder):
raise FileExistsError(
"There is already some file or folder in the Container folder, I cannot initialise it!"
)
# validate the compression algorithm: check if I'm able to load the classes to compress and decompress
# with the given specified string
get_compressobj_instance(compression_algorithm)
get_stream_decompresser(compression_algorithm)
# Create config file
with open(self._get_config_file(), "w", encoding="utf8") as fhandle:
json.dump(
{
"container_version": 1, # For future compatibility, this is the version of the format
"loose_prefix_len": loose_prefix_len,
"pack_size_target": pack_size_target,
"hash_type": hash_type,
"container_id": container_id,
"compression_algorithm": compression_algorithm,
},
fhandle,
)
for folder in [
self._get_pack_folder(),
self._get_loose_folder(),
self._get_duplicates_folder(),
self._get_sandbox_folder(),
]:
os.makedirs(folder)
self._get_session(create=True)
def _get_repository_config(self) -> dict[str, int | str]:
"""Return the repository config."""
if self._config is None:
if not self.is_initialised:
raise NotInitialised(
"The container is not initialised yet - use .init_container() first"
)
with open(self._get_config_file(), encoding="utf8") as fhandle:
self._config = json.load(fhandle)
return self._config
@property
def loose_prefix_len(self) -> int:
"""Return the length of the prefix of loose objects, when sharding.
This is read from the (cached) repository configuration.
"""
return self._get_repository_config()["loose_prefix_len"] # type: ignore[return-value]
@property
def pack_size_target(self) -> int:
"""Return the length of the pack name, when sharding.
This is read from the (cached) repository configuration.
"""
return self._get_repository_config()["pack_size_target"] # type: ignore[return-value]
@property
def hash_type(self) -> str:
"""Return the length of the prefix of loose objects, when sharding.
This is read from the (cached) repository configuration.
"""
return self._get_repository_config()["hash_type"] # type: ignore[return-value]
@property
def container_id(self) -> str:
"""Return the repository unique ID.
This is read from the (cached) repository configuration, and is a UUID uniquely identifying
this specific container. This is generated at the container initialization (call `init_container`) and will
never change for this container.
Clones of the container should have a different ID even if they have the same content.
"""
return self._get_repository_config()["container_id"] # type: ignore[return-value]
@property
def compression_algorithm(self) -> str:
"""Return the compression algorithm defined for this container.
This is read from the repository configuration."""
return self._get_repository_config()["compression_algorithm"] # type: ignore[return-value]
def _get_compressobj_instance(self):
"""Return the correct `compressobj` class for the compression algorithm defined for this container."""
return get_compressobj_instance(self.compression_algorithm)
def _get_stream_decompresser(self) -> type[ZlibStreamDecompresser]:
"""Return a new instance of the correct StreamDecompresser class for the compression algorithm
defined for this container.
"""
return get_stream_decompresser(self.compression_algorithm)
def get_object_content(self, hashkey: str) -> bytes:
"""Get the content of an object with a given hash key.
:param hashkey: The hash key of the object to retrieve.
:return: a byte stream with the object content.
"""
with self.get_object_stream(hashkey) as handle:
return handle.read()
@contextmanager
def get_object_stream(self, hashkey: str) -> Iterator[StreamReadBytesType]:
"""Return a context manager yielding a stream to get the content of an object.
To be used as a context manager::
with container.get_object_stream(hashkey) as fhandle:
data = fhandle.read()
The returned object supports *at least* the read() method that
accepts an optional parameter to read the file in chunks, and might
not be seekable.
:param hashkey: the hashkey of the object to stream.
"""
with self.get_object_stream_and_meta(hashkey=hashkey) as (fhandle, _):
yield fhandle
@contextmanager
def get_object_stream_and_meta(
self, hashkey: str
) -> Iterator[tuple[StreamReadBytesType, ObjectMeta],]:
"""Return a context manager yielding a stream to get the content of an object, and a metadata dictionary.
To be used as a context manager::
with container.get_object_stream(hashkey) as (fhandle, meta):
data = fhandle.read()
assert len(data) == meta['size']
The returned file-handle object supports *at least* the read() method that
accepts an optional parameter to read the file in chunks, and might
not be seekable.
The returned metadata is an ObjectMeta dataclass.
:param hashkey: the hashkey of the object to stream.
"""
with self.get_objects_stream_and_meta(
hashkeys=[hashkey], skip_if_missing=False
) as triplets:
counter = 0
for (
obj_hashkey,
stream,
meta,
) in triplets: # pylint: disable=not-an-iterable
counter += 1
assert (
counter == 1
), "There is more than one item returned by get_objects_stream_and_meta"
assert obj_hashkey == hashkey
if stream is None:
raise NotExistent(f"No object with hash key {hashkey}")
yield stream, meta
@overload
def _get_objects_stream_meta_generator(
self,
hashkeys: Sequence[str],
skip_if_missing: bool,
with_streams: Literal[False],
) -> Iterator[tuple[str, ObjectMeta]]:
...
@overload
def _get_objects_stream_meta_generator(
self,
hashkeys: Sequence[str],
skip_if_missing: bool,
with_streams: Literal[True],
) -> Iterator[tuple[str, StreamSeekBytesType | None, ObjectMeta]]:
...
def _get_objects_stream_meta_generator( # pylint: disable=too-many-branches,too-many-statements,too-many-locals
self,
hashkeys: Sequence[str],
skip_if_missing: bool,
with_streams: bool,
) -> Iterator[
(tuple[str, ObjectMeta] | tuple[str, StreamSeekBytesType | None, ObjectMeta])
]:
"""Return a generator yielding triplets of (hashkey, open stream, size).
:note: The stream is already open and at the right position, and can
just be read.
:note: size is the length of the object (uncompressed) when doing a
``read()`` on the returned stream
:note: do not use directly! Call always the proper public methods. This is only
for internal use
:param hashkeys: a list of hash keys for which we want to get a stream reader
:param skip_if_missing: if True, just skip hash keys that are not in the container
(i.e., neither packed nor loose). If False, return ``None`` instead of the
stream.
:param with_streams: if True, yield triplets (hashkey, stream, meta).
If False, yield pairs (hashkey, meta) and avoid to open any file.
"""
# pylint: disable=too-many-nested-blocks
# During the run, this variable is updated with the currently open file.
# This file is closed before opening a new one - so we ensure only one is
# open at a given time.
# The try/finally block makes sure we close it at the end, if any was open.
last_open_file = None
lazy_loose_stream: LazyLooseStream | None = None
# Operate on a set - only return once per required hashkey, even if required more than once
hashkeys_set = set(hashkeys)
hashkeys_in_packs: set[str] = set()
packs = defaultdict(list)
# Currently ordering in the DB (it's ordered across all packs, but this should not be
# a problem as we then split them by pack). To be checked, performance-wise, if it's better
# to order in python instead
session = self._get_cached_session()
obj_reader: StreamReadBytesType
if len(hashkeys_set) <= self._MAX_CHUNK_ITERATE_LENGTH:
# Operate in chunks, due to the SQLite limits
# (see comment above the definition of self._IN_SQL_MAX_LENGTH)
for chunk in chunk_iterator(hashkeys_set, size=self._IN_SQL_MAX_LENGTH):
stmt = select(
Obj.pack_id,
Obj.hashkey,
Obj.offset,
Obj.length,
Obj.compressed,
Obj.size,
).where(Obj.hashkey.in_(chunk))
for res in session.execute(stmt):
packs[res[0]].append(
ObjQueryResults(res[1], res[2], res[3], res[4], res[5])
)
else:
sorted_hashkeys = sorted(hashkeys_set)
pack_iterator = session.execute(
text(
"SELECT pack_id, hashkey, offset, length, compressed, size FROM db_object ORDER BY hashkey"
)
)
# The left_key returns the second element of the tuple, i.e. the hashkey (that is the value to compare
# with the right iterator)
for res, where in detect_where_sorted(
pack_iterator, sorted_hashkeys, left_key=lambda x: x[1]
):
if where == Location.BOTH:
# If it's in both, it returns the left one, i.e. the full data from the DB
packs[res[0]].append(
ObjQueryResults(res[1], res[2], res[3], res[4], res[5])
)
for pack_int_id, pack_metadata in packs.items():
pack_metadata.sort(key=lambda metadata: metadata.offset)
hashkeys_in_packs.update(obj.hashkey for obj in pack_metadata)
pack_path = self._get_pack_path_from_pack_id(str(pack_int_id))
try:
# Open only once per file (if in `with_streams` mode)
if with_streams:
last_open_file = open( # pylint: disable=consider-using-with
pack_path, mode="rb"
)
for metadata in pack_metadata:
meta = {
"type": ObjectType.PACKED,
"size": metadata.size,
"pack_id": pack_int_id,
"pack_compressed": metadata.compressed,
"pack_offset": metadata.offset,
"pack_length": metadata.length,
}
if with_streams:
assert last_open_file is not None
obj_reader = PackedObjectReader(
fhandle=last_open_file,
offset=metadata.offset,
length=metadata.length,
)
lazy_loose_stream = None
if metadata.compressed:
# I create a LazyLooseStream. It is the
# responsibility of the stream decompresser to open
# the stream if it feels it needs it.
lazy_loose_stream = self.get_lazy_loose_stream(
hashkey=metadata.hashkey
)
obj_reader = self._get_stream_decompresser()(
obj_reader, lazy_uncompressed_stream=lazy_loose_stream
)
yield metadata.hashkey, obj_reader, ObjectMeta(**meta)
# Here I check if the LazyLooseStream that I passed has
# been openeed - if so, I close it so I don't leave
# open file streams around
if (
lazy_loose_stream is not None
and not lazy_loose_stream.closed
):
lazy_loose_stream.close_stream()
else:
yield metadata.hashkey, ObjectMeta(**meta)
finally:
if last_open_file is not None:
if not last_open_file.closed:
last_open_file.close()
# Collect loose hash keys that are not found
# Reason: a concurrent process might have packed them,
# in the meantime.
loose_not_found = set()
for loose_hashkey in hashkeys_set.difference(hashkeys_in_packs):
obj_path = self._get_loose_path_from_hashkey(hashkey=loose_hashkey)
try:
if with_streams:
last_open_file = open( # pylint: disable=consider-using-with
obj_path, mode="rb"
)
# I do not use Pathlib to get the size, in case the file has just
# been deleted by a concurrent writer, but I use the lower-level os.fstat
# on the fileno() of the open file
meta = {
"type": ObjectType.LOOSE,
"size": os.fstat(last_open_file.fileno()).st_size,
"pack_id": None,
"pack_compressed": None,
"pack_offset": None,
"pack_length": None,
}
yield loose_hashkey, last_open_file, ObjectMeta(**meta)
else:
# This will also raise a FileNotFoundError if the file does not exist
size = obj_path.stat().st_size
meta = {
"type": ObjectType.LOOSE,
"size": size,
"pack_id": None,
"pack_compressed": None,
"pack_offset": None,
"pack_length": None,
}
yield loose_hashkey, ObjectMeta(**meta)
except FileNotFoundError:
loose_not_found.add(loose_hashkey)
continue
finally:
# Close each loose file, if open
if last_open_file is not None:
if not last_open_file.closed:
last_open_file.close()
# There were some loose objects that were not found
# Give a final try - if they have been deleted in the meantime
# while being packed, I should have the guarantee that they
# are by now in the pack.
# If they are not, the object does not exist.
if loose_not_found:
# IMPORTANT. I need to close the session (and flush the
# self._session cache) to refresh the DB, otherwise since I am
# reading in WAL mode, I will be keeping to read from the "old"
# state of the DB.
# Note that this is an expensive operation!
# This means that asking for non-existing objects will be
# slow.
if self._session is not None:
self._session.close()
self._session = None
packs = defaultdict(list)
session = self._get_cached_session()
if len(loose_not_found) <= self._MAX_CHUNK_ITERATE_LENGTH:
for chunk in chunk_iterator(
loose_not_found, size=self._IN_SQL_MAX_LENGTH
):
stmt = select(
Obj.pack_id,
Obj.hashkey,
Obj.offset,
Obj.length,
Obj.compressed,
Obj.size,
).where(Obj.hashkey.in_(chunk))
for res in session.execute(stmt):
packs[res[0]].append(
ObjQueryResults(res[1], res[2], res[3], res[4], res[5])
)
else:
sorted_hashkeys = sorted(loose_not_found)
pack_iterator = session.execute(
text(
"SELECT pack_id, hashkey, offset, length, compressed, size FROM db_object ORDER BY hashkey"
)
)
# The left_key returns the second element of the tuple, i.e. the hashkey (that is the value to compare
# with the right iterator)
for res, where in detect_where_sorted(
pack_iterator, sorted_hashkeys, left_key=lambda x: x[1]
):
if where == Location.BOTH:
# If it's in both, it returns the left one, i.e. the full data from the DB
packs[res[0]].append(
ObjQueryResults(res[1], res[2], res[3], res[4], res[5])
)
# I will construct here the really missing objects.
# I make a copy of the set.
really_not_found = loose_not_found.copy()
for pack_int_id, pack_metadata in packs.items():
pack_metadata.sort(key=lambda metadata: metadata.offset)
# I remove those that I found
really_not_found.difference_update(obj.hashkey for obj in pack_metadata)
pack_path = self._get_pack_path_from_pack_id(str(pack_int_id))
try:
if with_streams:
last_open_file = open( # pylint: disable=consider-using-with
pack_path, mode="rb"
)
for metadata in pack_metadata:
meta = {
"type": ObjectType.PACKED,
"size": metadata.size,
"pack_id": pack_int_id,
"pack_compressed": metadata.compressed,
"pack_offset": metadata.offset,
"pack_length": metadata.length,
}
if with_streams:
assert last_open_file is not None
obj_reader = PackedObjectReader(
fhandle=last_open_file,
offset=metadata.offset,
length=metadata.length,
)
lazy_loose_stream = None
if metadata.compressed:
# I create a LazyLooseStream.
# It is the responsibility of the stream decompresser to open the stream if it feels it
# needs it.
lazy_loose_stream = self.get_lazy_loose_stream(
hashkey=metadata.hashkey
)
obj_reader = self._get_stream_decompresser()(
obj_reader,
lazy_uncompressed_stream=lazy_loose_stream,
)
yield metadata.hashkey, obj_reader, ObjectMeta(**meta)
# Here I check if the LazyLooseStream that I passed has
# been openeed - if so, I close it so I don't leave
# open file streams around
if (
lazy_loose_stream is not None
and not lazy_loose_stream.closed
):
lazy_loose_stream.close_stream()
else:
yield metadata.hashkey, ObjectMeta(**meta)
finally:
if last_open_file is not None:
if not last_open_file.closed:
last_open_file.close()
# If there are really missing objects, and skip_if_missing is False, yield them
if really_not_found and not skip_if_missing:
for missing_hashkey in really_not_found:
meta = {
"type": ObjectType.MISSING,
"size": None,
"pack_id": None,
"pack_compressed": None,
"pack_offset": None,
"pack_length": None,
}
if with_streams:
yield missing_hashkey, None, ObjectMeta(**meta)
else:
yield missing_hashkey, ObjectMeta(**meta)
@contextmanager
def get_objects_stream_and_meta(
self, hashkeys: Sequence[str], skip_if_missing: bool = True
) -> Iterator[Iterator[tuple[str, StreamSeekBytesType | None, ObjectMeta]]]:
"""A context manager returning a generator yielding triplets of (hashkey, open stream, metadata).
:note: the hash keys yielded are often in a *different* order than the original
``hashkeys`` list. This is done for efficiency reasons, to reduce to a minimum
file opening and to try to read file chunks (for packs) in sequential
order rather than in random order.
To use it, you should do something like the following::
with container.get_objects_stream_and_meta(hashkeys=hashkeys) as triplets:
for obj_hashkey, stream, meta in triplets:
if stream is None:
# This should happen only if you pass skip_if_missing=False
retrieved[obj_hashkey] = None
else:
# len(stream.read() will be equal to size
retrieved[obj_hashkey] = stream.read()
The returned metadata is an ObjectMeta dataclass.
:param hashkeys: a list of hash keys for which we want to get a stream reader
:param skip_if_missing: if True, just skip hash keys that are not in the container
(i.e., neither packed nor loose). If False, return ``None`` instead of the
stream. In this latter case, the length of the generator returned by this context
manager has always the same length as the input ``hashkeys`` list.
"""
yield self._get_objects_stream_meta_generator(
hashkeys=hashkeys, skip_if_missing=skip_if_missing, with_streams=True
)
def get_lazy_loose_stream(self, hashkey: str) -> LazyLooseStream:
"""Return a LazyLooseStream pointing to the given hashkey.
As explained in the docsring of LazyLooseStream, the goal is to return a stream that needs to be explicitly
opened and points to a "cached copy" of an already existing packed object, that is made loose again
in order to have an uncompressed version of it.
"""
return LazyLooseStream(container=self, hashkey=hashkey)
def get_objects_meta(
self, hashkeys: Sequence[str], skip_if_missing: bool = True
) -> Iterator[tuple[str, ObjectMeta]]:
"""A generator yielding pairs of (hashkey, metadata).
:note: the hash keys yielded are often in a *different* order than the original
``hashkeys`` list. This is to have the same behavior of ``get_objects_stream_and_meta``,
and for efficiency (even if efficiency is less of an issue for this method).
To use it, you should do something like the following::
for obj_hashkey, meta in container.get_objects_meta(hashkeys=hashkeys):
sizes[obj_hashkey] = meta['size']
Note that if you can afford putting everything in memory and do not want to bother with the
different ordering, you can just do::
metas = dict(container.get_objects_meta(hashkeys=hashkeys))
and then you can access the meta of an object via ``metas[hashkey]``.
The returned metadata is an ObjectMeta dataclass.
:param hashkeys: a list of hash keys for which we want to get a stream reader
:param skip_if_missing: if True, just skip hash keys that are not in the container
(i.e., neither packed nor loose). If False, return them (``meta['type']`` will have value
ObjectType.MISSING in this case).
In this latter case, the length of the generator returned by this context
manager has always the same length as the input ``hashkeys`` list.
"""
return self._get_objects_stream_meta_generator(
hashkeys=hashkeys, skip_if_missing=skip_if_missing, with_streams=False
)
def get_object_meta(self, hashkey: str) -> ObjectMeta:
"""Return the metadata dictionary for the given hash key.
To be used as follows:
meta = container.get_object_meta(hashkey)
print(meta['size'])
The returned metadata is an ObjectMeta dataclass.
:param hashkey: the hashkey of the object to stream.
"""
counter = 0
for (
obj_hashkey,
meta,
) in self.get_objects_meta( # pylint: disable=not-an-iterable
hashkeys=[hashkey], skip_if_missing=False
):
counter += 1
assert (
counter == 1
), "There is more than one item returned by get_objects_stream_and_meta"
assert obj_hashkey == hashkey
if meta["type"] != ObjectType.MISSING:
return meta
assert (
counter == 1
), "No object found, this should never happen since I pass skip_if_missing=False!"
raise NotExistent(f"No object with hash key {hashkey}")
def has_objects(self, hashkeys: list[str] | tuple[str, ...]) -> list[bool]:
"""Return whether the container contains objects with the given hash keys.
:param hashkeys: a list of hash keys to check.
:return: a list of booleans, where the i-th value is True if the i-th object of the ``hashkeys``
list exists, False otherwise.
"""
existing_hashkeys = set()
# Note: This iterates in a 'random' order, different than the `hashkeys` list
for obj_hashkey, _ in self.get_objects_meta( # pylint: disable=not-an-iterable
hashkeys=hashkeys, skip_if_missing=True
):
# Since I use skip_if_missing=True, I should only iterate on those that exist
existing_hashkeys.add(obj_hashkey)
# Return a list of booleans
return [hashkey in existing_hashkeys for hashkey in hashkeys]
def has_object(self, hashkey: str) -> bool:
"""Return whether the container contains an object with the given hashkey.
:param hashkey: the hashkey of the object.
:return: True if the object exists, False otherwise.
"""
return self.has_objects([hashkey])[0]
def get_objects_content(
self, hashkeys: list[str], skip_if_missing: bool = True
) -> dict[str, bytes | None]:
"""Get the content of a number of objects with given hash keys.
:note: use this method only if you know objects fit in memory.
Otherwise, use the ``get_objects_stream_and_meta`` context manager and
process the objects one by one.