-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppd.py
123 lines (88 loc) · 3.23 KB
/
ppd.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
from collections import OrderedDict
from threading import Thread
from json import dumps, loads
from time import sleep
from hashlib import md5
from pathlib import Path
def address(s, **kwargs):
path = ""
address = md5(s.encode()).hexdigest()[:16].upper()
if "path" in kwargs:
path = kwargs["path"]
return path + "/".join([address[i*2:i*2+2] for i in range(8)])
class db:
def __init__(self, **kwargs):
self.path = ""
self.memsize = 1000
self.__dict__.update(kwargs)
self.queue = OrderedDict()
self.cache = OrderedDict()
self.read = []
Thread(target=self.reader, daemon=True).start()
Thread(target=self.writer, daemon=True).start()
def push(self, data):
if not isinstance(data, dict):
raise TypeError("Push must be dict: {}")
self.queue.update(data)
def pull(self, l):
if not isinstance(l, list):
raise TypeError("Pull must be list: []")
self.read += l
r = {}
while len(r) < len(l):
for obj in l:
if obj in self.cache:
r.update({obj:self.cache[obj]})
return r
def pullOne(self, s):
if not isinstance(s, str):
raise TypeError("pullOne must be string: ''")
return self.pull([s])[s]
def drop(self, l):
if not isinstance(l, list):
raise TypeError("Drop must be list: []")
for name in l:
self.queue[name] = None
def find(self):
"""Coming Soon: Command used to hunt for information across distributed databases."""
pass
def writer(self):
while True:
sleep(.1)
while self.queue:
data = self.queue.popitem(last=True)
for val in dict((data,)):
p = address(val, path = self.path)
Path(p[:-2]).mkdir(parents=True, exist_ok=True)
try:
with open(p, "r") as fob:
f = loads(fob.read())
f.update(data)
data = f
except:
with open(p, "a") as fob:
pass
with open(p, "w") as fob:
fob.write(dumps(dict((data,))))
self.cache.update((data,))
def reader(self):
while True:
sleep(.1)
while self.read:
name = self.read.pop(0)
found = 0
if name in self.cache:
found = 1
if name in self.queue:
self.cache[name] = self.queue[name]
found = 1
if not found:
try:
with open(address(name, path = self.path), "r") as fob:
data = loads(fob.read())
if name in data:
self.cache[name] = data[name]
except:
self.cache[name] = None
while len(self.cache) > self.memsize:
self.cache.popitem(last=True)