-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsharded_trie.py
64 lines (58 loc) · 2.01 KB
/
sharded_trie.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
from trie import Trie
import tempfile
import json
import os
from datetime import datetime
import threading
# TODO: Extract KV store from this, provide it as API for in-mem component
class ShardedTrie:
def __init__(self, config, wal):
self.range_tries = {}
self.config = config
self.checkpoint_dir = config.current()["checkpoint_dir"]
self.wal = wal
# TODO: Lock per trie
self.sem = threading.Semaphore()
def matches(self, query):
k_factor = self.config.current()["k_factor"]
prefix, rem = query[:k_factor], query[k_factor+1:]
if prefix not in self.range_tries:
return []
return self.range_tries[prefix].matches(query)
def add(self, word, commit_to_wal=True):
# todo: return nice error if fails
k_factor = self.config.current()["k_factor"]
prefix, rem = word[:k_factor], word[k_factor+1:]
if len(prefix) != k_factor:
# we dont support words less than k factor
return
self.sem.acquire()
if commit_to_wal: self.wal.commit("add", word)
if prefix not in self.range_tries:
self.range_tries[prefix] = Trie()
trie = self.range_tries[prefix]
trie.add(word)
self.sem.release()
return True
def remove(self, word, commit_to_wal=True):
k_factor = self.config.current()["k_factor"]
prefix, rem = word[:k_factor], word[k_factor+1:]
if len(prefix) != k_factor or prefix not in self.range_tries:
# we dont support words less than k factor
return
self.sem.acquire()
if commit_to_wal: self.wal.commit("remove", word)
trie = self.range_tries[prefix]
trie.remove(word)
self.sem.release()
return True
def load(self, prefix, trie_dict):
trie = Trie()
trie.load(trie_dict)
self.range_tries[prefix] = trie
def replay_wal(self):
for action, word in self.wal.readlines():
match action:
case "add": self.add(word, commit_to_wal=False)
case "remove": self.remove(word, commit_to_wal=False)
case _: print(f"Unrecognized action in WAL {action} for word {word}")