-
Notifications
You must be signed in to change notification settings - Fork 32
/
slob.py
2357 lines (1887 loc) · 71.2 KB
/
slob.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
# pylint: disable=C0111,C0103,C0302,R0903,R0904,R0914,R0201
import argparse
import array
import collections
import encodings
import functools
import io
import os
import pickle
import random
import sys
import tempfile
import unicodedata
import unittest
import warnings
from abc import abstractmethod
from bisect import bisect_left
from builtins import open as fopen
from collections import namedtuple
from collections.abc import Sequence
from datetime import datetime, timezone
from functools import lru_cache
from struct import pack, unpack, calcsize
from threading import RLock
from types import MappingProxyType
from uuid import uuid4, UUID
import icu
DEFAULT_COMPRESSION = "lzma2"
UTF8 = "utf-8"
MAGIC = b"!-1SLOB\x1F"
Compression = namedtuple("Compression", "compress decompress")
Ref = namedtuple("Ref", "key bin_index item_index fragment")
Header = namedtuple(
"Header",
"magic uuid encoding "
"compression tags content_types "
"blob_count "
"store_offset "
"refs_offset "
"size",
)
U_CHAR = ">B"
U_CHAR_SIZE = calcsize(U_CHAR)
U_SHORT = ">H"
U_SHORT_SIZE = calcsize(U_SHORT)
U_INT = ">I"
U_INT_SIZE = calcsize(U_INT)
U_LONG_LONG = ">Q"
U_LONG_LONG_SIZE = calcsize(U_LONG_LONG)
def calcmax(len_size_spec):
return 2 ** (calcsize(len_size_spec) * 8) - 1
MAX_TEXT_LEN = calcmax(U_SHORT)
MAX_TINY_TEXT_LEN = calcmax(U_CHAR)
MAX_LARGE_BYTE_STRING_LEN = calcmax(U_INT)
MAX_BIN_ITEM_COUNT = calcmax(U_SHORT)
from icu import Locale, Collator, UCollAttribute, UCollAttributeValue
PRIMARY = Collator.PRIMARY
SECONDARY = Collator.SECONDARY
TERTIARY = Collator.TERTIARY
QUATERNARY = Collator.QUATERNARY
IDENTICAL = Collator.IDENTICAL
def init_compressions():
ident = lambda x: x
compressions = {"": Compression(ident, ident)}
for name in ("bz2", "zlib"):
try:
m = __import__(name)
except ImportError:
warnings.warn("%s is not available" % name)
else:
compressions[name] = Compression(lambda x: m.compress(x, 9), m.decompress)
try:
import lzma
except ImportError:
warnings.warn("lzma is not available")
else:
filters = [{"id": lzma.FILTER_LZMA2}]
compress = lambda s: lzma.compress(s, format=lzma.FORMAT_RAW, filters=filters)
decompress = lambda s: lzma.decompress(
s, format=lzma.FORMAT_RAW, filters=filters
)
compressions["lzma2"] = Compression(compress, decompress)
return compressions
COMPRESSIONS = init_compressions()
del init_compressions
MIME_TEXT = "text/plain"
MIME_HTML = "text/html"
MIME_CSS = "text/css"
MIME_JS = "application/javascript"
MIME_TYPES = {
"html": MIME_HTML,
"txt": MIME_TEXT,
"js": MIME_JS,
"css": MIME_CSS,
"json": "application/json",
"woff": "application/font-woff",
"svg": "image/svg+xml",
"png": "image/png",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"gif": "image/gif",
"ttf": "application/x-font-ttf",
"otf": "application/x-font-opentype",
}
class FileFormatException(Exception):
pass
class UnknownFileFormat(FileFormatException):
pass
class UnknownCompression(FileFormatException):
pass
class UnknownEncoding(FileFormatException):
pass
class IncorrectFileSize(FileFormatException):
pass
class TagNotFound(Exception):
pass
@lru_cache(maxsize=None)
def sortkey(strength, maxlength=None):
c = Collator.createInstance(Locale(""))
c.setStrength(strength)
c.setAttribute(UCollAttribute.ALTERNATE_HANDLING, UCollAttributeValue.SHIFTED)
if maxlength is None:
return c.getSortKey
else:
return lambda x: c.getSortKey(x)[:maxlength]
def sortkey_length(strength, word):
c = Collator.createInstance(Locale(""))
c.setStrength(strength)
c.setAttribute(UCollAttribute.ALTERNATE_HANDLING, UCollAttributeValue.SHIFTED)
coll_key = c.getSortKey(word)
return len(coll_key) - 1 # subtract 1 for ending \x00 byte
class MultiFileReader(io.BufferedIOBase):
def __init__(self, *args):
filenames = []
for arg in args:
if isinstance(arg, str):
filenames.append(arg)
else:
for name in arg:
filenames.append(name)
files = []
ranges = []
offset = 0
for name in filenames:
size = os.stat(name).st_size
ranges.append(range(offset, offset + size))
files.append(fopen(name, "rb"))
offset += size
self.size = offset
self._ranges = ranges
self._files = files
self._fcount = len(self._files)
self._offset = -1
self.seek(0)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False
def close(self):
for f in self._files:
f.close()
self._files.clear()
self._ranges.clear()
def closed(self):
return len(self._ranges) == 0
def isatty(self):
return False
def readable(self):
return True
def seek(self, offset, whence=io.SEEK_SET):
if whence == io.SEEK_SET:
self._offset = offset
elif whence == io.SEEK_CUR:
self._offset = self._offset + offset
elif whence == io.SEEK_END:
self._offset = self.size + offset
else:
raise ValueError("Invalid value for parameter whence: %r" % whence)
return self._offset
def seekable(self):
return True
def tell(self):
return self._offset
def writable(self):
return False
def read(self, n=-1):
file_index = -1
actual_offset = 0
for i, r in enumerate(self._ranges):
if self._offset in r:
file_index = i
actual_offset = self._offset - r.start
break
result = b""
if n == -1 or n is None:
to_read = self.size
else:
to_read = n
while -1 < file_index < self._fcount:
f = self._files[file_index]
f.seek(actual_offset)
read = f.read(to_read)
read_count = len(read)
self._offset += read_count
result += read
to_read -= read_count
if to_read > 0:
file_index += 1
actual_offset = 0
else:
break
return result
class CollationKeyList(object):
def __init__(self, lst, sortkey_):
self.lst = lst
self.sortkey = sortkey_
def __len__(self):
return len(self.lst)
def __getitem__(self, i):
return self.sortkey(self.lst[i].key)
class KeydItemDict(object):
def __init__(self, lst, strength, maxlength=None):
self.lst = lst
self.sortkey = sortkey(strength, maxlength=maxlength)
self.sortkeylist = CollationKeyList(lst, self.sortkey)
def __len__(self):
return len(self.lst)
def __getitem__(self, key):
key_as_sk = self.sortkey(key)
i = bisect_left(self.sortkeylist, key_as_sk)
if i != len(self.lst):
while i < len(self.lst):
if self.sortkey(self.lst[i].key) == key_as_sk:
yield self.lst[i]
else:
break
i += 1
def __contains__(self, key):
try:
next(self[key])
except StopIteration:
return False
else:
return True
class Blob(object):
def __init__(self, content_id, key, fragment, read_content_type_func, read_func):
self._content_id = content_id
self._key = key
self._fragment = fragment
self._read_content_type = read_content_type_func
self._read = read_func
@property
def id(self):
return self._content_id
@property
def key(self):
return self._key
@property
def fragment(self):
return self._fragment
@property
def content_type(self):
return self._read_content_type()
@property
def content(self):
return self._read()
def __str__(self):
return self.key
def __repr__(self):
return "<{0.__class__.__module__}.{0.__class__.__name__} " "{0.key}>".format(
self
)
def read_byte_string(f, len_spec):
length = unpack(len_spec, f.read(calcsize(len_spec)))[0]
return f.read(length)
class StructReader:
def __init__(self, file_, encoding=None):
self._file = file_
self.encoding = encoding
def read_int(self):
s = self.read(U_INT_SIZE)
return unpack(U_INT, s)[0]
def read_long(self):
b = self.read(U_LONG_LONG_SIZE)
return unpack(U_LONG_LONG, b)[0]
def read_byte(self):
s = self.read(U_CHAR_SIZE)
return unpack(U_CHAR, s)[0]
def read_short(self):
return unpack(U_SHORT, self._file.read(U_SHORT_SIZE))[0]
def _read_text(self, len_spec):
max_len = 2 ** (8 * calcsize(len_spec)) - 1
byte_string = read_byte_string(self._file, len_spec)
if len(byte_string) == max_len:
terminator = byte_string.find(0)
if terminator > -1:
byte_string = byte_string[:terminator]
return byte_string.decode(self.encoding)
def read_tiny_text(self):
return self._read_text(U_CHAR)
def read_text(self):
return self._read_text(U_SHORT)
def __getattr__(self, name):
return getattr(self._file, name)
class StructWriter:
def __init__(self, file_, encoding=None):
self._file = file_
self.encoding = encoding
def write_int(self, value):
self._file.write(pack(U_INT, value))
def write_long(self, value):
self._file.write(pack(U_LONG_LONG, value))
def write_byte(self, value):
self._file.write(pack(U_CHAR, value))
def write_short(self, value):
self._file.write(pack(U_SHORT, value))
def _write_text(self, text, len_size_spec, encoding=None, pad_to_length=None):
if encoding is None:
encoding = self.encoding
text_bytes = text.encode(encoding)
length = len(text_bytes)
max_length = calcmax(len_size_spec)
if length > max_length:
raise ValueError("Text is too long for size spec %s" % len_size_spec)
self._file.write(
pack(len_size_spec, pad_to_length if pad_to_length else length)
)
self._file.write(text_bytes)
if pad_to_length:
for _ in range(pad_to_length - length):
self._file.write(pack(U_CHAR, 0))
def write_tiny_text(self, text, encoding=None, editable=False):
pad_to_length = 255 if editable else None
self._write_text(text, U_CHAR, encoding=encoding, pad_to_length=pad_to_length)
def write_text(self, text, encoding=None):
self._write_text(text, U_SHORT, encoding=encoding)
def __getattr__(self, name):
return getattr(self._file, name)
def set_tag_value(filename, name, value):
with fopen(filename, "rb+") as f:
f.seek(len(MAGIC) + 16)
encoding = read_byte_string(f, U_CHAR).decode(UTF8)
if encodings.search_function(encoding) is None:
raise UnknownEncoding(encoding)
f = StructWriter(StructReader(f, encoding=encoding), encoding=encoding)
f.read_tiny_text()
tag_count = f.read_byte()
for _ in range(tag_count):
key = f.read_tiny_text()
if key == name:
f.write_tiny_text(value, editable=True)
return
f.read_tiny_text()
raise TagNotFound(name)
def read_header(f):
f.seek(0)
magic = f.read(len(MAGIC))
if magic != MAGIC:
raise UnknownFileFormat()
uuid = UUID(bytes=f.read(16))
encoding = read_byte_string(f, U_CHAR).decode(UTF8)
if encodings.search_function(encoding) is None:
raise UnknownEncoding(encoding)
f = StructReader(f, encoding)
compression = f.read_tiny_text()
if not compression in COMPRESSIONS:
raise UnknownCompression(compression)
def read_tags():
tags = {}
count = f.read_byte()
for _ in range(count):
key = f.read_tiny_text()
value = f.read_tiny_text()
tags[key] = value
return tags
tags = read_tags()
def read_content_types():
content_types = []
count = f.read_byte()
for _ in range(count):
content_type = f.read_text()
content_types.append(content_type)
return tuple(content_types)
content_types = read_content_types()
blob_count = f.read_int()
store_offset = f.read_long()
size = f.read_long()
refs_offset = f.tell()
return Header(
magic=magic,
uuid=uuid,
encoding=encoding,
compression=compression,
tags=MappingProxyType(tags),
content_types=content_types,
blob_count=blob_count,
store_offset=store_offset,
refs_offset=refs_offset,
size=size,
)
def meld_ints(a, b):
return (a << 16) | b
def unmeld_ints(c):
bstr = bin(c).lstrip("0b").zfill(48)
a, b = bstr[-48:-16], bstr[-16:]
return int(a, 2), int(b, 2)
class Slob(Sequence):
def __init__(self, file_or_filenames):
self._f = MultiFileReader(file_or_filenames)
try:
self._header = read_header(self._f)
if self._f.size != self._header.size:
raise IncorrectFileSize(
"File size should be {0}, {1} bytes found".format(
self._header.size, self._f.size
)
)
except FileFormatException:
self._f.close()
raise
self._refs = RefList(
self._f, self._header.encoding, offset=self._header.refs_offset
)
self._g = MultiFileReader(file_or_filenames)
self._store = Store(
self._g,
self._header.store_offset,
COMPRESSIONS[self._header.compression].decompress,
self._header.content_types,
)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False
@property
def id(self):
return self._header.uuid.hex
@property
def content_types(self):
return self._header.content_types
@property
def tags(self):
return self._header.tags
@property
def blob_count(self):
return self._header.blob_count
@property
def compression(self):
return self._header.compression
@property
def encoding(self):
return self._header.encoding
def __len__(self):
return len(self._refs)
def __getitem__(self, i):
ref = self._refs[i]
def read_func():
return self._store.get(ref.bin_index, ref.item_index)[1]
read_func = lru_cache(maxsize=None)(read_func)
def read_content_type_func():
return self._store.content_type(ref.bin_index, ref.item_index)
content_id = meld_ints(ref.bin_index, ref.item_index)
return Blob(
content_id, ref.key, ref.fragment, read_content_type_func, read_func
)
def get(self, blob_id):
bin_index, bin_item_index = unmeld_ints(blob_id)
return self._store.get(bin_index, bin_item_index)
@lru_cache(maxsize=None)
def as_dict(self, strength=TERTIARY, maxlength=None):
return KeydItemDict(self, strength, maxlength=maxlength)
def close(self):
self._f.close()
self._g.close()
def find_parts(fname):
fname = os.path.expanduser(fname)
dirname = os.path.dirname(fname) or os.getcwd()
basename = os.path.basename(fname)
candidates = []
for name in os.listdir(dirname):
if name.startswith(basename):
candidates.append(os.path.join(dirname, name))
return sorted(candidates)
def open(file_or_filenames):
if isinstance(file_or_filenames, str):
if not os.path.exists(file_or_filenames):
file_or_filenames = find_parts(file_or_filenames)
return Slob(file_or_filenames)
def create(*args, **kwargs):
return Writer(*args, **kwargs)
class BinMemWriter:
def __init__(self):
self.content_type_ids = []
self.item_dir = []
self.items = []
self.current_offset = 0
def add(self, content_type_id, blob):
self.content_type_ids.append(content_type_id)
self.item_dir.append(pack(U_INT, self.current_offset))
length_and_bytes = pack(U_INT, len(blob)) + blob
self.items.append(length_and_bytes)
self.current_offset += len(length_and_bytes)
def __len__(self):
return len(self.item_dir)
def finalize(self, fout: "output file", compress: "function"):
count = len(self)
fout.write(pack(U_INT, count))
for content_type_id in self.content_type_ids:
fout.write(pack(U_CHAR, content_type_id))
content = b"".join(self.item_dir + self.items)
compressed = compress(content)
fout.write(pack(U_INT, len(compressed)))
fout.write(compressed)
self.content_type_ids.clear()
self.item_dir.clear()
self.items.clear()
class ItemList(Sequence):
def __init__(self, file_, offset, count_or_spec, pos_spec, cache_size=None):
self.lock = RLock()
self._file = file_
file_.seek(offset)
if isinstance(count_or_spec, str):
count_spec = count_or_spec
self.count = unpack(count_spec, file_.read(calcsize(count_spec)))[0]
else:
self.count = count_or_spec
self.pos_offset = file_.tell()
self.pos_spec = pos_spec
self.pos_size = calcsize(pos_spec)
self.data_offset = self.pos_offset + self.pos_size * self.count
if cache_size:
self.__getitem__ = lru_cache(maxsize=cache_size)(self.__getitem__)
def __len__(self):
return self.count
def pos(self, i):
with self.lock:
self._file.seek(self.pos_offset + self.pos_size * i)
return unpack(self.pos_spec, self._file.read(self.pos_size))[0]
def read(self, pos):
with self.lock:
self._file.seek(self.data_offset + pos)
return self._read_item()
@abstractmethod
def _read_item(self):
pass
def __getitem__(self, i):
if i >= len(self) or i < 0:
raise IndexError("index out of range")
return self.read(self.pos(i))
class RefList(ItemList):
def __init__(self, f, encoding, offset=0, count=None):
super().__init__(
StructReader(f, encoding),
offset,
U_INT if count is None else count,
U_LONG_LONG,
cache_size=512,
)
def _read_item(self):
key = self._file.read_text()
bin_index = self._file.read_int()
item_index = self._file.read_short()
fragment = self._file.read_tiny_text()
return Ref(
key=key, bin_index=bin_index, item_index=item_index, fragment=fragment
)
@lru_cache(maxsize=None)
def as_dict(self, strength=TERTIARY, maxlength=None):
return KeydItemDict(self, strength, maxlength=maxlength)
class Bin(ItemList):
def __init__(self, count, bin_bytes):
super().__init__(StructReader(io.BytesIO(bin_bytes)), 0, count, U_INT)
def _read_item(self):
content_len = self._file.read_int()
content = self._file.read(content_len)
return content
StoreItem = namedtuple("StoreItem", "content_type_ids compressed_content")
class Store(ItemList):
def __init__(self, file_, offset, decompress, content_types):
super().__init__(StructReader(file_), offset, U_INT, U_LONG_LONG, cache_size=32)
self.decompress = decompress
self.content_types = content_types
def _read_item(self):
bin_item_count = self._file.read_int()
packed_content_type_ids = self._file.read(bin_item_count * U_CHAR_SIZE)
content_type_ids = []
for i in range(bin_item_count):
content_type_id = unpack(U_CHAR, packed_content_type_ids[i : i + 1])[0]
content_type_ids.append(content_type_id)
content_length = self._file.read_int()
content = self._file.read(content_length)
return StoreItem(content_type_ids=content_type_ids, compressed_content=content)
def _content_type(self, bin_index, item_index):
store_item = self[bin_index]
content_type_id = store_item.content_type_ids[item_index]
content_type = self.content_types[content_type_id]
return content_type, store_item
def content_type(self, bin_index, item_index):
return self._content_type(bin_index, item_index)[0]
@lru_cache(maxsize=16)
def _decompress(self, bin_index):
store_item = self[bin_index]
return self.decompress(store_item.compressed_content)
def get(self, bin_index, item_index):
content_type, store_item = self._content_type(bin_index, item_index)
content = self._decompress(bin_index)
count = len(store_item.content_type_ids)
store_bin = Bin(count, content)
content = store_bin[item_index]
return (content_type, content)
def find(word, slobs, match_prefix=True):
seen = set()
if isinstance(slobs, Slob):
slobs = [slobs]
variants = []
for strength in (QUATERNARY, TERTIARY, SECONDARY, PRIMARY):
variants.append((strength, None))
if match_prefix:
for strength in (QUATERNARY, TERTIARY, SECONDARY, PRIMARY):
variants.append((strength, sortkey_length(strength, word)))
for strength, maxlength in variants:
for slob in slobs:
d = slob.as_dict(strength=strength, maxlength=maxlength)
for item in d[word]:
dedup_key = (slob.id, item.id, item.fragment)
if dedup_key in seen:
continue
else:
seen.add(dedup_key)
yield slob, item
WriterEvent = namedtuple("WriterEvent", "name data")
class KeyTooLongException(Exception):
@property
def key(self):
return self.args[0]
class Writer(object):
def __init__(
self,
filename,
workdir=None,
encoding=UTF8,
compression=DEFAULT_COMPRESSION,
min_bin_size=512 * 1024,
max_redirects=5,
observer=None,
):
self.filename = filename
self.observer = observer
if os.path.exists(self.filename):
raise SystemExit("File %r already exists" % self.filename)
# make sure we can write
with fopen(self.filename, "wb"):
pass
self.encoding = encoding
if encodings.search_function(self.encoding) is None:
raise UnknownEncoding(self.encoding)
self.workdir = workdir
self.tmpdir = tmpdir = tempfile.TemporaryDirectory(
prefix="{0}-".format(os.path.basename(filename)), dir=workdir
)
self.f_ref_positions = self._wbfopen("ref-positions")
self.f_store_positions = self._wbfopen("store-positions")
self.f_refs = self._wbfopen("refs")
self.f_store = self._wbfopen("store")
self.max_redirects = max_redirects
if max_redirects:
self.aliases_path = os.path.join(tmpdir.name, "aliases")
self.f_aliases = Writer(
self.aliases_path,
workdir=tmpdir.name,
max_redirects=0,
compression=None,
)
if compression is None:
compression = ""
if not compression in COMPRESSIONS:
raise UnknownCompression(compression)
else:
self.compress = COMPRESSIONS[compression].compress
self.compression = compression
self.content_types = {}
self.min_bin_size = min_bin_size
self.current_bin = None
self.blob_count = 0
self.ref_count = 0
self.bin_count = 0
self._tags = {
"version.python": sys.version.replace("\n", " "),
"version.pyicu": icu.VERSION,
"version.icu": icu.ICU_VERSION,
"created.at": datetime.now(timezone.utc).isoformat(),
}
self.tags = MappingProxyType(self._tags)
def _wbfopen(self, name):
return StructWriter(
fopen(os.path.join(self.tmpdir.name, name), "wb"), encoding=self.encoding
)
def tag(self, name, value=""):
if len(name.encode(self.encoding)) > MAX_TINY_TEXT_LEN:
self._fire_event("tag_name_too_long", (name, value))
return
if len(value.encode(self.encoding)) > MAX_TINY_TEXT_LEN:
self._fire_event("tag_value_too_long", (name, value))
value = ""
self._tags[name] = value
def _split_key(self, key):
if isinstance(key, str):
actual_key = key
fragment = ""
else:
actual_key, fragment = key
if len(actual_key) > MAX_TEXT_LEN or len(fragment) > MAX_TINY_TEXT_LEN:
raise KeyTooLongException(key)
return actual_key, fragment
def add(self, blob, *keys, content_type=""):
if len(blob) > MAX_LARGE_BYTE_STRING_LEN:
self._fire_event("content_too_long", blob)
return
if len(content_type) > MAX_TEXT_LEN:
self._fire_event("content_type_too_long", content_type)
return
actual_keys = []
for key in keys:
try:
actual_key, fragment = self._split_key(key)
except KeyTooLongException as e:
self._fire_event("key_too_long", e.key)
else:
actual_keys.append((actual_key, fragment))
if len(actual_keys) == 0:
return
if self.current_bin is None:
self.current_bin = BinMemWriter()
self.bin_count += 1
if content_type not in self.content_types:
self.content_types[content_type] = len(self.content_types)
self.current_bin.add(self.content_types[content_type], blob)
self.blob_count += 1
bin_item_index = len(self.current_bin) - 1
bin_index = self.bin_count - 1
for actual_key, fragment in actual_keys:
self._write_ref(actual_key, bin_index, bin_item_index, fragment)
if (
self.current_bin.current_offset > self.min_bin_size
or len(self.current_bin) == MAX_BIN_ITEM_COUNT
):
self._write_current_bin()
def add_alias(self, key, target_key):
if self.max_redirects:
try:
self._split_key(key)
except KeyTooLongException as e:
self._fire_event("alias_too_long", e.key)
return
try:
self._split_key(target_key)
except KeyTooLongException as e:
self._fire_event("alias_target_too_long", e.key)
return
self.f_aliases.add(pickle.dumps(target_key), key)
else:
raise NotImplementedError()
def _fire_event(self, name, data=None):
if self.observer:
self.observer(WriterEvent(name, data))
def _write_current_bin(self):
self.f_store_positions.write_long(self.f_store.tell())
self.current_bin.finalize(self.f_store, self.compress)
self.current_bin = None
def _write_ref(self, key, bin_index, item_index, fragment=""):
self.f_ref_positions.write_long(self.f_refs.tell())
self.f_refs.write_text(key)
self.f_refs.write_int(bin_index)
self.f_refs.write_short(item_index)