retracesoftware-proxy 0.2.18__py3-none-any.whl → 0.2.20__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.
@@ -1,506 +0,0 @@
1
- import retracesoftware.utils as utils
2
- import retracesoftware.functional as functional
3
- from functools import wraps
4
- import inspect
5
- import gc
6
- import importlib
7
- import types
8
- import sys
9
-
10
- from retracesoftware.proxy.thread import start_new_thread_wrapper, counters
11
- from retracesoftware.install.typeutils import modify
12
-
13
- def find_attr(mro, name):
14
- for cls in mro:
15
- if name in cls.__dict__:
16
- return cls.__dict__[name]
17
-
18
- def is_descriptor(obj):
19
- return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')
20
-
21
- def resolve(path):
22
- module, sep, name = path.rpartition('.')
23
- if module == None: module = 'builtins'
24
-
25
- return getattr(importlib.import_module(module), name)
26
-
27
- def phase(func):
28
- func.is_phase = True # add marker attribute
29
- return func
30
-
31
- def replace(replacements, coll):
32
- return map(lambda x: replacements.get(x, x), coll)
33
-
34
- def container_replace(container, old, new):
35
- if isinstance(container, dict):
36
- if old in container:
37
- elem = container.pop(old)
38
- container[new] = elem
39
- container_replace(container, old, new)
40
- else:
41
- for key,value in container.items():
42
- if key != '__retrace_unproxied__' and value is old:
43
- container[key] = new
44
- return True
45
- elif isinstance(container, list):
46
- for i,value in enumerate(container):
47
- if value is old:
48
- container[i] = new
49
- return True
50
- elif isinstance(container, set):
51
- container.remove(old)
52
- container.add(new)
53
- return True
54
- else:
55
- return False
56
-
57
- def select_keys(keys, dict):
58
- return {key: dict[key] for key in keys if key in dict}
59
-
60
- def map_values(f, dict):
61
- return {key: f(value) for key,value in dict.items()}
62
-
63
- def common_keys(dict, *dicts):
64
- common_keys = utils.set(dict)
65
- for d in dicts:
66
- common_keys &= d.keys()
67
-
68
- assert isinstance(common_keys, utils.set)
69
-
70
- return common_keys
71
-
72
- def intersection(*dicts):
73
- return { key: tuple(d[key] for d in dicts) for key in common_keys(*dicts) }
74
-
75
- def intersection_apply(f, *dicts):
76
- return map_values(lambda vals: f(*vals), intersection(*dicts))
77
-
78
- def patch(func):
79
- @wraps(func)
80
- def wrapper(self, spec, mod_dict):
81
- if isinstance(spec, str):
82
- return wrapper(self, [spec], mod_dict)
83
- elif isinstance(spec, list):
84
- res = {}
85
- for name in spec:
86
- if name in mod_dict:
87
- value = func(self, mod_dict[name])
88
- if value is not None:
89
- res[name] = value
90
- return res
91
- elif isinstance(spec, dict):
92
- # return {name: func(self, mod_dict[name], value) for name, value in spec.items() if name in mod_dict}
93
- res = {}
94
- for name,value in spec.items():
95
- if name in mod_dict:
96
- value = func(self, mod_dict[name], value)
97
- if value is not None:
98
- res[name] = value
99
- return res
100
- else:
101
- raise Exception('TODO')
102
-
103
- wrapper.is_phase = True
104
- return wrapper
105
-
106
- def is_special(name):
107
- return len(name) > 4 and name.startswith('__') and name.endswith('__')
108
-
109
- def superdict(cls):
110
- result = {}
111
- for cls in list(reversed(cls.__mro__))[1:]:
112
- result.update(cls.__dict__)
113
-
114
- return result
115
-
116
- def wrap_method_descriptors(wrapper, prefix, base):
117
- slots = {"__slots__": () }
118
-
119
- extended = type(f'{prefix}.{base.__module__}.{base.__name__}', (base,), {"__slots__": () })
120
-
121
- blacklist = ['__getattribute__', '__hash__', '__del__']
122
-
123
- for name,value in superdict(base).items():
124
- if name not in blacklist:
125
- if utils.is_method_descriptor(value):
126
- setattr(extended, name, wrapper(value))
127
-
128
- return extended
129
-
130
- class ElementPatcher:
131
-
132
- def __init__(self, config, phases):
133
- funcs = {}
134
-
135
- for phase in phases:
136
- if phase.name in config:
137
- for key,func in phase(config[phase.name]).items():
138
- val = funcs.get(key, [])
139
- val.append(func)
140
- funcs[key] = val
141
-
142
- self.funcs = utils.map_values(lambda funcs: functional.sequence(*funcs), funcs)
143
- self.fallback = None
144
-
145
- if 'default' in config:
146
- default_name = config['default']
147
- for phase in phases:
148
- if phase.name == default_name:
149
- self.fallback = phase.patch
150
-
151
- def __call__(self, name, value):
152
- if name in self.funcs:
153
- return self.funcs[name](value)
154
- elif not is_special(name) and self.fallback:
155
- return self.fallback(value)
156
- else:
157
- return value
158
-
159
- # class Patcher:
160
-
161
- # def __init__(self, config):
162
-
163
- # self.config = config
164
- # self.phases = []
165
- # self.patched = {}
166
-
167
- # # system.set_thread_id(0)
168
- # # self.thread_counter = system.sync(utils.counter(1))
169
- # # self.module_config = module_config
170
-
171
- # # self.thread_state = thread_state
172
- # # self.debug_level = debug_level
173
- # # self.on_function_proxy = on_function_proxy
174
- # # self.modules = config['modules']
175
- # # self.immutable_types_set = immutable_types
176
- # # self.predicate = PredicateBuilder()
177
- # # self.system = system
178
- # # self.type_attribute_filter = self.predicate(config['type_attribute_filter'])
179
- # # self.post_commit = post_commit
180
- # # self.exclude_paths = [re.compile(s) for s in config.get('exclude_paths', [])]
181
- # # self.typepatcher = {}
182
- # # self.originals = {}
183
-
184
- # # def is_phase(name): return getattr(getattr(self, name, None), "is_phase", False)
185
-
186
- # # self.phases = [(name, getattr(self, name)) for name in Patcher.__dict__.keys() if is_phase(name)]
187
-
188
- # def add_phase(self, phase):
189
- # self.phases.append(phase)
190
-
191
- # # def log(self, *args):
192
- # # self.system.tracer.log(*args)
193
-
194
- # def path_predicate(self, path):
195
- # for exclude in self.exclude_paths:
196
- # if exclude.match(str(path)) is not None:
197
- # # print(f'in path_predicate, excluding {path}')
198
- # return False
199
- # return True
200
-
201
- # # def on_proxytype(self, cls):
202
-
203
- # # def patch(spec):
204
- # # for method, transform in spec.items():
205
- # # setattr(cls, method, resolve(transform)(getattr(cls, method)))
206
-
207
- # # if cls.__module__ in self.modules:
208
- # # spec = self.modules[cls.__module__]
209
-
210
- # # if 'patchtype' in spec:
211
- # # patchtype = spec['patchtype']
212
- # # if cls.__name__ in patchtype:
213
- # # patch(patchtype[cls.__name__])
214
-
215
- # @property
216
- # def disable(self):
217
- # return self.thread_state.select('disabled')
218
-
219
- # def proxyable(self, name, obj):
220
- # if name.startswith('__') and name.endswith('__'):
221
- # return False
222
-
223
- # if isinstance(obj, (str, int, dict, list, tuple)):
224
- # return False
225
-
226
- # if isinstance(obj, type):
227
- # return not issubclass(obj, BaseException) and obj not in self.immutable_types_set
228
-
229
- class Patcher:
230
-
231
- def __init__(self, config):
232
-
233
- self.config = config
234
- self.phases = []
235
- self.patched = {}
236
-
237
- def add_phase(self, phase):
238
- self.phases.append(phase)
239
-
240
- def path_predicate(self, path):
241
- for exclude in self.exclude_paths:
242
- if exclude.match(str(path)) is not None:
243
- # print(f'in path_predicate, excluding {path}')
244
- return False
245
- return True
246
-
247
- @property
248
- def disable(self):
249
- return self.thread_state.select('disabled')
250
-
251
- def proxyable(self, name, obj):
252
- if name.startswith('__') and name.endswith('__'):
253
- return False
254
-
255
- if isinstance(obj, (str, int, dict, list, tuple)):
256
- return False
257
-
258
- if isinstance(obj, type):
259
- return not issubclass(obj, BaseException) and obj not in self.immutable_types_set
260
- else:
261
- return type(obj) not in self.immutable_types_set
262
-
263
- @phase
264
- def proxy_type_attributes(self, spec, mod_dict):
265
- for classname, attributes in spec.items():
266
- if classname in mod_dict:
267
- cls = mod_dict[classname]
268
- if isinstance(cls, type):
269
- for name in attributes:
270
- attr = find_attr(cls.__mro__, name)
271
- if attr is not None and (callable(attr) or is_descriptor(attr)):
272
- proxied = self.system(attr)
273
- # proxied = self.proxy(attr)
274
-
275
- with modify(cls):
276
- setattr(cls, name, proxied)
277
- else:
278
- raise Exception(f"Cannot patch attributes for {cls.__module__}.{cls.__name__} as object is: {cls} and not a type")
279
-
280
- @phase
281
- def replace(self, spec, mod_dict):
282
- return {key: resolve(value) for key,value in spec.items()}
283
-
284
- @patch
285
- def patch_start_new_thread(self, value):
286
- return start_new_thread_wrapper(thread_state = self.thread_state,
287
- on_exit = self.system.on_thread_exit,
288
- start_new_thread = value)
289
-
290
- # def start_new_thread(function, *args):
291
- # # synchronized, replay shoudl yield correct number
292
- # thread_id = self.thread_counter()
293
-
294
- # def threadrunner(*args, **kwargs):
295
- # nonlocal thread_id
296
- # self.system.set_thread_id(thread_id)
297
-
298
- # with self.thread_state.select('internal'):
299
- # try:
300
- # # if self.tracing:
301
- # # FrameTracer.install(self.thread_state.dispatch(noop, internal = self.checkpoint))
302
- # return function(*args, **kwargs)
303
- # finally:
304
- # print(f'exiting: {thread_id}')
305
-
306
- # return value(threadrunner, *args)
307
-
308
- # return self.thread_state.dispatch(value, internal = start_new_thread)
309
-
310
- @phase
311
- def wrappers(self, spec, mod_dict):
312
- return intersection_apply(lambda path, value: resolve(path)(value), spec, mod_dict)
313
-
314
- @patch
315
- def patch_exec(self, exec):
316
-
317
- def is_module(source, *args):
318
- return isinstance(source, types.CodeType) and source.co_name == '<module>'
319
-
320
- def after_exec(source, globals = None, locals = None):
321
- if isinstance(source, types.CodeType) and source.co_name == '<module>' and '__name__' in globals:
322
- self(sys.modules[globals['__name__']])
323
-
324
- def first(x): return x[0]
325
-
326
- def disable(func): return self.thread_state.wrap('disabled', func)
327
-
328
- return self.thread_state.dispatch(
329
- exec,
330
- internal = functional.sequence(
331
- functional.juxt(exec, functional.when(is_module, disable(after_exec))), first))
332
-
333
- # self.thread_state.wrap(desired_state = 'disabled', function = exec_wrapper)
334
-
335
- @patch
336
- def sync_types(self, value):
337
- return wrap_method_descriptors(self.system.sync, "retrace", value)
338
-
339
- @phase
340
- def with_state_recursive(self, spec, mod_dict):
341
-
342
- updates = {}
343
-
344
- for state,elems in spec.items():
345
-
346
- def wrap(obj):
347
- return functional.recurive_wrap_function(
348
- functional.partial(self.thread_state.wrap, state),
349
- obj)
350
-
351
- updates.update(map_values(wrap, select_keys(elems, mod_dict)))
352
-
353
- return updates
354
-
355
- @phase
356
- def methods_with_state(self, spec, mod_dict):
357
-
358
- # updates = {}
359
-
360
- def update(cls, name, f):
361
- setattr(cls, name, f(getattr(cls, name)))
362
-
363
- for state,cls_methods in spec.items():
364
- def wrap(obj):
365
- assert callable(obj)
366
- return self.thread_state.wrap(desired_state = state, function = obj)
367
-
368
- for typename,methodnames in cls_methods.items():
369
- cls = mod_dict[typename]
370
-
371
- for methodname in methodnames:
372
- update(cls, methodname, wrap)
373
-
374
- return {}
375
-
376
- @phase
377
- def with_state(self, spec, mod_dict):
378
-
379
- updates = {}
380
-
381
- for state,elems in spec.items():
382
-
383
- def wrap(obj):
384
- return self.thread_state.wrap(desired_state = state, function = obj)
385
-
386
- updates.update(map_values(wrap, select_keys(elems, mod_dict)))
387
-
388
- return updates
389
-
390
- @patch
391
- def patch_extension_exec(self, exec):
392
-
393
- def first(x): return x[0]
394
-
395
- def disable(func): return self.thread_state.wrap('disabled', func)
396
-
397
- return self.thread_state.dispatch(exec,
398
- internal = functional.sequence(functional.juxt(exec, disable(self)), first))
399
-
400
- # def wrapper(module):
401
- # with self.thread_state.select('internal'):
402
- # res = exec(module)
403
-
404
- # self(module)
405
- # return res
406
-
407
- # return wrapper
408
-
409
- @patch
410
- def path_predicates(self, func, param):
411
- signature = inspect.signature(func).parameters
412
-
413
- try:
414
- index = list(signature.keys()).index(param)
415
- except ValueError:
416
- print(f'parameter {param} not in: {signature.keys()} {type(func)} {func}')
417
- raise
418
-
419
- param = functional.param(name = param, index = index)
420
-
421
- assert callable(param)
422
-
423
- return functional.if_then_else(
424
- test = functional.sequence(param, self.path_predicate),
425
- then = func,
426
- otherwise = self.thread_state.wrap('disabled', func))
427
-
428
- @phase
429
- def wrap(self, spec, mod_dict):
430
- updates = {}
431
-
432
- for path, wrapper_name in spec.items():
433
-
434
- parts = path.split('.')
435
- name = parts[0]
436
- if name in mod_dict:
437
- value = mod_dict[name]
438
- assert not isinstance(value, utils.wrapped_function), \
439
- f"value for key: {name} is already wrapped"
440
-
441
- if len(parts) == 1:
442
- updates[name] = resolve(wrapper_name)(value)
443
- elif len(parts) == 2:
444
- member = getattr(value, parts[1], None)
445
- if member:
446
- new_value = resolve(wrapper_name)(member)
447
- setattr(value, parts[1], new_value)
448
- else:
449
- raise Exception('TODO')
450
-
451
- return updates
452
-
453
- def find_phase(self, name):
454
- for phase in self.phases:
455
- if phase.name == name:
456
- return phase
457
-
458
- raise Exception(f'Phase: {name} not found')
459
-
460
- # def run_transforms(self, config, obj):
461
- # if isinstance(config, str):
462
- # return find_phase(config).patch(obj)
463
- # else:
464
- # for name in config
465
-
466
- def element_patcher(self, name):
467
- if name in self.config:
468
- return ElementPatcher(config = self.config[name],
469
- phases = self.phases)
470
-
471
- def wrap_namespace(self, ns):
472
- name = ns.get('__name__', None)
473
- patcher = self.element_patcher(name)
474
- print(f'wrap_namespace {name} {patcher}')
475
- return utils.InterceptDict(ns, patcher) if patcher else ns
476
-
477
- def update(self, old, new):
478
- if isinstance(new, type) and isinstance(old, type) and issubclass(new, old):
479
- for subclass in old.__subclasses__():
480
- if subclass is not new:
481
- subclass.__bases__ = tuple(replace({old: new}, subclass.__bases__))
482
-
483
- for ref in gc.get_referrers(old):
484
- container_replace(container = ref, old = old, new = new)
485
-
486
- def patch_loaded_module(self, mod_dict):
487
- modname = mod_dict.get('__name__', None)
488
-
489
- print(f'Patching loaded module: {modname}')
490
-
491
- if modname in self.config:
492
-
493
-
494
- originals = {}
495
- self.patched[modname] = originals
496
-
497
- patcher = self.element_patcher(modname)
498
-
499
- for key in list(mod_dict.keys()):
500
- original = mod_dict[key]
501
- patched = patcher(key, original)
502
-
503
- if patched is not original:
504
- self.update(old = original, new = patched)
505
- originals[key] = original
506
- assert mod_dict[key] is patched