true-level-replication 0.10.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,245 @@
1
+ # ##### BEGIN GPL LICENSE BLOCK #####
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
+ #
16
+ # ##### END GPL LICENSE BLOCK #####
17
+
18
+
19
+ import logging
20
+
21
+ from deepdiff import Delta, DeepDiff
22
+
23
+
24
+ class ReplicatedDatablock(object):
25
+ """
26
+ Datablock translation definition to handle DCC<->Replication data exchange.
27
+ """
28
+
29
+ # Type parameters
30
+ is_root = False
31
+ use_delta = False
32
+
33
+ @staticmethod
34
+ def construct(data: dict) -> object:
35
+ """
36
+ Create a new datablock of the corresponding instance according to the
37
+ given data dtype entry.
38
+
39
+ :param data: data dumped according to the dump() definition
40
+ :type data: dict
41
+ :return: datablock instance
42
+ """
43
+ raise NotImplementedError()
44
+
45
+ @staticmethod
46
+ def dump(datablock: object) -> dict:
47
+ """
48
+ Extract the given datablock instance data into a dict.
49
+
50
+ :param datablock: datablock instance
51
+ :type datablock: datablock type
52
+ :return: dict
53
+ """
54
+ raise NotImplementedError()
55
+
56
+ @staticmethod
57
+ def load(data: dict, datablock: object):
58
+ """
59
+ Load extracted data into the given datablock.
60
+
61
+ :param data: data dumped according to the dump() implementation
62
+ :type data: dict
63
+ :param datablock: datablock instance
64
+ :type datablock: datablock type
65
+ """
66
+ raise NotImplementedError()
67
+
68
+ @staticmethod
69
+ def resolve(data: dict) -> object:
70
+ """
71
+ Find a corresponding datablock instance according to the given data
72
+
73
+ :param datablock: datablock instance
74
+ :type datablock: datablock type
75
+ :return: datablock instance
76
+ """
77
+ raise NotImplementedError()
78
+
79
+ @staticmethod
80
+ def resolve_deps(datablock: object) -> [object]:
81
+ """
82
+ Get all dependencies of the given datablock.
83
+
84
+ :param datablock: datablock instance
85
+ :type datablock: datablock type
86
+ :return: list() of datablock dependencies
87
+ """
88
+ raise NotImplementedError()
89
+
90
+ @staticmethod
91
+ def needs_update(datablock: object, data: dict) -> bool:
92
+ """
93
+ Fastcheck to test if a the latest commited state of the datablock
94
+ is outdated.
95
+
96
+ :param datablock: datablock instance
97
+ :type datablock: datablock type
98
+ :param data: node data in its last committed state
99
+ :type data: dict
100
+ """
101
+ return True
102
+
103
+ @staticmethod
104
+ def compute_delta(last_data: dict, current_data: dict) -> Delta:
105
+ """
106
+ Compute the node delta between current_state and last committed state
107
+
108
+ :param last_data: last committed data
109
+ :type last_data: dict
110
+ :param current_data: current datablock state
111
+ :type current_data: dict
112
+ :return: deepdiff.Delta
113
+ """
114
+ return Delta(DeepDiff(last_data, current_data, cache_size=5000))
115
+
116
+
117
+ class DataTranslationProtocol(object):
118
+ """
119
+ A simple protocol to handle programs data translation between a program
120
+ and replication based on a given ReplicatedDatablock implementations.
121
+ # TODO: validate implementations
122
+ # TODO: tests implementations
123
+ # TODO: version implementation/protocol
124
+ """
125
+
126
+ def __init__(self):
127
+ self._supported_types = {}
128
+
129
+ def register_implementation(self, dcc_types, implementation):
130
+ """
131
+ Register a new replicated datatype implementation
132
+ """
133
+
134
+ if type(dcc_types) is list:
135
+ for dcc_type in dcc_types:
136
+ self._supported_types[dcc_type.__name__] = implementation
137
+ logging.debug(f"Registering DCC type {dcc_type.__name__}")
138
+ else:
139
+ self._supported_types[dcc_types.__name__] = implementation
140
+ logging.debug(f"Registering DCC type {dcc_types.__name__}")
141
+
142
+ def construct(self, data: dict) -> object:
143
+ """
144
+ Create a new datablock of the corresponding instance according to the
145
+ given data type_id entry.
146
+
147
+ :param data: data dumped according to the dump() implementation
148
+ :type data: dict
149
+ :return: datablock instance
150
+ """
151
+ type_id = data.get("type_id")
152
+ return self._supported_types.get(type_id).construct(data)
153
+
154
+ def dump(self, datablock: object, stamp_uuid: str = None) -> dict:
155
+ """
156
+ Extract the given datablock instance data into a dict.
157
+
158
+ :param datablock: datablock instance
159
+ :type datablock: datablock type
160
+ :return: dict
161
+ """
162
+ type_id = type(datablock).__name__
163
+
164
+ data = self._supported_types.get(type_id).dump(datablock)
165
+
166
+ # stamp with type id
167
+ data["type_id"] = type_id
168
+ if stamp_uuid:
169
+ data["uuid"] = stamp_uuid
170
+
171
+ return data
172
+
173
+ def load(self, data: dict, datablock: object):
174
+ """
175
+ Load extracted data into the given datablock.
176
+
177
+ :param data: data dumped according to the dump() implementation
178
+ :type data: dict
179
+ :param datablock: datablock instance
180
+ :type datablock: datablock type
181
+ """
182
+ type_id = data.get("type_id")
183
+ self._supported_types.get(type_id).load(data, datablock)
184
+
185
+ def resolve(self, data: dict) -> object:
186
+ """
187
+ Find a corresponding datablock instance according to the given data
188
+
189
+ :param datablock: datablock instance
190
+ :type datablock: datablock type
191
+ :return: datablock instance
192
+ """
193
+ type_id = data.get("type_id")
194
+ return self._supported_types.get(type_id).resolve(data)
195
+
196
+ def resolve_deps(self, datablock: object) -> [object]:
197
+ """
198
+ Get all dependencies of the given datablock.
199
+
200
+ :param datablock: datablock instance
201
+ :type datablock: datablock type
202
+ :return: list() of datablock dependencies
203
+ """
204
+ type_id = type(datablock).__name__
205
+ return self._supported_types.get(type_id).resolve_deps(datablock)
206
+
207
+ def needs_update(self, datablock: object, data: dict) -> bool:
208
+ """
209
+ Fastcheck to test if a the latest commited state of the datablock
210
+ is outdated.
211
+
212
+ :param datablock: datablock instance
213
+ :type datablock: datablock type
214
+ :param data: node data in its last committed state
215
+ :type
216
+ """
217
+ type_id = type(datablock).__name__
218
+ return self._supported_types[type_id].needs_update(datablock, data)
219
+
220
+ def get_implementation(self, datablock) -> ReplicatedDatablock:
221
+ """Retrieve a registered implementation"""
222
+ if isinstance(datablock, str):
223
+ type_id = datablock
224
+ else:
225
+ type_id = type(datablock).__name__
226
+
227
+ return self._supported_types.get(type_id)
228
+
229
+ @property
230
+ def implementations(self) -> dict:
231
+ """Get a dict containing the protocol registered implementations"""
232
+ return self._supported_types
233
+
234
+ def compute_delta(self, last_data: dict, current_data: dict) -> Delta:
235
+ """
236
+ Compute the node delta between current_state and last committed state
237
+
238
+ :param last_data: last committed data
239
+ :type last_data: dict
240
+ :param current_data: current datablock state
241
+ :type current_data: dict
242
+ :return: deepdiff.Delta
243
+ """
244
+ type_id = current_data.get("type_id")
245
+ return self._supported_types.get(type_id).compute_delta(last_data, current_data)
@@ -0,0 +1,338 @@
1
+ # ##### BEGIN GPL LICENSE BLOCK #####
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
+ #
16
+ # ##### END GPL LICENSE BLOCK #####
17
+
18
+
19
+ import collections.abc
20
+ import copy
21
+ import gzip
22
+ import logging
23
+ import threading
24
+ from pathlib import Path
25
+ from uuid import uuid4
26
+ from datetime import datetime
27
+
28
+
29
+ from . import net
30
+ from .constants import FETCHED, RP_COMMON, STATE_INITIAL
31
+ from .exception import NonAuthorizedOperationError
32
+ from .protocol import DataTranslationProtocol
33
+ from .objects import Commit, Node, ReplicationObject
34
+
35
+ try:
36
+ import _pickle as pickle
37
+ except ImportError:
38
+ import pickle
39
+
40
+
41
+ class GraphObjectStore(collections.abc.MutableMapping):
42
+ """A basic structure to store object as a graph
43
+
44
+ Reads of a single key (``__getitem__``/``get``) rely on the GIL making a
45
+ plain dict lookup atomic and are left unlocked. Anything that mutates the
46
+ store or iterates over more than one key takes ``_lock`` so that a writer
47
+ on one thread (e.g. ``Repository.do_commit`` from the server's data
48
+ thread) can never be observed mid-mutation by a reader on another thread
49
+ (e.g. ``ServerNetService.disconnect_client``) - which previously could
50
+ raise "RuntimeError: dictionary changed size during iteration".
51
+ """
52
+
53
+ def __init__(self, *args, **kwargs):
54
+ self._lock = threading.RLock()
55
+ self.store = dict()
56
+ self.update(dict(*args, **kwargs)) # use the free update to set keys
57
+
58
+ def __getitem__(self, key):
59
+ return self.store[key]
60
+
61
+ def __setitem__(self, key, value):
62
+ with self._lock:
63
+ self.store[key] = value
64
+
65
+ def __delitem__(self, key):
66
+ with self._lock:
67
+ del self.store[key]
68
+
69
+ def __iter__(self):
70
+ with self._lock:
71
+ return iter(list(self.store.keys()))
72
+
73
+ def __len__(self):
74
+ return len(self.store)
75
+
76
+ def __repr__(self):
77
+ str = "\n"
78
+ for item in self.values():
79
+ str += repr(item)
80
+ return str
81
+
82
+ def keys(self):
83
+ with self._lock:
84
+ return list(self.store.keys())
85
+
86
+ def values(self):
87
+ with self._lock:
88
+ return list(self.store.values())
89
+
90
+ def items(self):
91
+ with self._lock:
92
+ return list(self.store.items())
93
+
94
+ def get_parents(self, target: str):
95
+ """Retrieve node's parents
96
+
97
+ :param node: target node
98
+ :type node: Node
99
+ """
100
+ parents = []
101
+ for node in self.values():
102
+ if node.dependencies and target in node.dependencies:
103
+ parents.append(node)
104
+
105
+ return parents
106
+
107
+ def rbfs_from(self, node: Node):
108
+ """Run a reversed Breadth Fist Search from the given nodes
109
+
110
+ :param node:
111
+ """
112
+ visited = []
113
+ queue = node if isinstance(node, list) else [node]
114
+
115
+ with self._lock:
116
+ store_snapshot = dict(self.store)
117
+
118
+ while queue:
119
+ current = queue.pop(0)
120
+
121
+ if current not in visited:
122
+ visited.append(current)
123
+ current_ref = store_snapshot.get(current)
124
+ if current_ref and current_ref.dependencies:
125
+ queue.extend(current_ref.dependencies)
126
+
127
+ return reversed(visited)
128
+
129
+
130
+ class Remote:
131
+ def __init__(
132
+ self,
133
+ name="origin",
134
+ address="127.0.0.1",
135
+ port=5555,
136
+ server_password=None,
137
+ admin_password=None,
138
+ realtime=False,
139
+ ):
140
+ self.name = name
141
+ self.address = address
142
+ self.port = port
143
+ self.realtime = realtime
144
+ self.server_password = server_password
145
+ self.admin_password = admin_password
146
+
147
+ self.online_users = {}
148
+ self.connection_status = STATE_INITIAL
149
+ self.uuid = uuid4()
150
+ self.poller = net.Poller()
151
+
152
+ # Both connect to the same port - command/data are distinguished by
153
+ # role at connect-handshake time, not by a separate port each.
154
+ self.command = net.Dealer(
155
+ address, port, identity=self.uuid.bytes, role=net.ROLE_COMMAND
156
+ )
157
+ self.command.connect()
158
+
159
+ self.data = net.Dealer(
160
+ address, port, identity=self.uuid.bytes, role=net.ROLE_DATA
161
+ )
162
+ self.data.connect()
163
+
164
+ self.poller.register(self.command)
165
+ self.poller.register(self.data)
166
+
167
+ def is_admin(self):
168
+ return self.admin_password is not None
169
+
170
+ def is_private(self):
171
+ return self.server_password is not None
172
+
173
+
174
+ class Repository:
175
+ """
176
+ Structure responsible for replication graph manipulation
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ rdp: DataTranslationProtocol = None,
182
+ username: str = None,
183
+ bare=False,
184
+ *args,
185
+ **kwargs,
186
+ ):
187
+ self.username = username
188
+ self.object_store = GraphObjectStore()
189
+ self.staging = GraphObjectStore()
190
+ self.rdp = rdp
191
+ self.remotes = {}
192
+ self.remote = None
193
+ self._bare = bare
194
+
195
+ def dumps(self, filepath: str):
196
+ """Dumps the repository data to a .db file
197
+
198
+ :param filepath: target filepath
199
+ :type filepath: str
200
+ """
201
+ nodes = []
202
+ for node in self.graph.values():
203
+ nodes.append(node.as_raw_chunks())
204
+
205
+ db = dict()
206
+ db["nodes"] = nodes
207
+
208
+ if self.remote:
209
+ db["users"] = copy.copy(self.remote.online_users)
210
+
211
+ stime = datetime.now().strftime("%Y_%m_%d_%H-%M-%S")
212
+
213
+ filepath = Path(filepath)
214
+ filepath = filepath.with_name(f"{filepath.stem}_{stime}{filepath.suffix}")
215
+
216
+ with gzip.open(filepath, "wb") as f:
217
+ logging.info(f"Writing session snapshot to {filepath}")
218
+ pickle.dump(db, f, protocol=4)
219
+
220
+ def loads(self, filepath: str):
221
+ """Load a repository snapshot
222
+
223
+ :param filepath: snapshot filepath
224
+ :type filepath: str
225
+ """
226
+ f = gzip.open(filepath, "rb")
227
+ db = pickle.load(f)
228
+
229
+ nodes = db.get("nodes")
230
+
231
+ logging.info(f"Loading {len(nodes)} node")
232
+ self.object_store.clear()
233
+ for node_data in nodes:
234
+ instance = Node.from_raw_chunks(node_data)
235
+ self.do_commit(instance)
236
+ instance.state = FETCHED
237
+
238
+ logging.info(f"Repository loaded from {filepath}")
239
+
240
+ def get_orphans_nodes(self):
241
+ return list(set(self.object_store.keys()).difference(self.index_sorted))
242
+
243
+ def get_node_by_datablock(self, datablock, default=None):
244
+ for v in self.object_store.values():
245
+ if not v.instance:
246
+ continue
247
+ if datablock == v.instance:
248
+ return v
249
+ return default
250
+
251
+ def do_commit(self, update: ReplicationObject, cache_delta=False):
252
+ node_id = getattr(update, "uuid", getattr(update, "node_id", None))
253
+ delta_based = isinstance(update, Commit)
254
+ if node_id:
255
+ existing_node = self.object_store.get(node_id)
256
+
257
+ if existing_node:
258
+ if delta_based:
259
+ existing_node.patch(update)
260
+ else:
261
+ existing_node.data = update.data
262
+ existing_node.dependencies = update.dependencies
263
+ elif not delta_based:
264
+ self.object_store[node_id] = update
265
+ else:
266
+ logging.error(f"Skipping update : {update}")
267
+ logging.debug(f"Committed {node_id}")
268
+
269
+ def assert_modification_rights(self, node_id):
270
+ node = self.graph.get(node_id)
271
+ if node is None:
272
+ logging.warning(f"Node {node_id} not found in graph")
273
+ if node and node.owner not in [self.username, RP_COMMON]:
274
+ raise NonAuthorizedOperationError(
275
+ f"Not authorized to modify the node {node_id}"
276
+ )
277
+
278
+ def is_node_readonly(self, node_id: str) -> bool:
279
+ """Check local user modification rights on a node
280
+
281
+ :param node_id: node identifier
282
+ :type node_id: str
283
+ :return: bool
284
+ """
285
+ node = self.graph.get(node_id)
286
+ return node and (node.owner in [self.username, RP_COMMON])
287
+
288
+ def push(self, socket, replication_object, identity=None, force=False):
289
+ chunks = replication_object.as_raw_chunks()
290
+ if identity is not None:
291
+ # Server to specific Client case
292
+ return socket.send(identity, chunks)
293
+ else:
294
+ return socket.send(chunks)
295
+
296
+ def fetch(self, socket):
297
+ """
298
+ Here we receive data from the wire:
299
+ - read data from the socket
300
+ - reconstruct an instance
301
+
302
+ Returns None if no message is currently available (socket.recv() is
303
+ non-blocking) - callers should only call this after their poll loop
304
+ indicated the socket has something ready.
305
+ """
306
+ if self._bare:
307
+ result = socket.recv()
308
+ if result is None:
309
+ return None
310
+ identity, chunks = result
311
+ else:
312
+ chunks = socket.recv()
313
+ if chunks is None:
314
+ return None
315
+ identity = "server"
316
+
317
+ return (identity, ReplicationObject.from_raw_chunks(chunks))
318
+
319
+ @property
320
+ def heads(self):
321
+ return [
322
+ n.uuid
323
+ for n in self.object_store.values()
324
+ if self.rdp.implementations[n.data["type_id"]].is_root
325
+ ]
326
+
327
+ @property
328
+ def index_sorted(self):
329
+ """Return the repository graph node index sorted by dependencies
330
+ order
331
+
332
+ :return: list
333
+ """
334
+ return self.object_store.rbfs_from(self.heads)
335
+
336
+ @property
337
+ def graph(self):
338
+ return self.object_store