-
Notifications
You must be signed in to change notification settings - Fork 617
/
base_context.py
130 lines (102 loc) · 4.03 KB
/
base_context.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
# Copyright 2019, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
import typing
from contextlib import contextmanager
def wrap_callable(target: "object") -> typing.Callable[[], object]:
if callable(target):
return target
return lambda: target
class BaseRuntimeContext:
class Slot:
def __init__(self, name: str, default: "object"):
raise NotImplementedError
def clear(self) -> None:
raise NotImplementedError
def get(self) -> "object":
raise NotImplementedError
def set(self, value: "object") -> None:
raise NotImplementedError
_lock = threading.Lock()
_slots = {} # type: typing.Dict[str, 'BaseRuntimeContext.Slot']
@classmethod
def clear(cls) -> None:
"""Clear all slots to their default value."""
keys = cls._slots.keys()
for name in keys:
slot = cls._slots[name]
slot.clear()
@classmethod
def register_slot(
cls, name: str, default: "object" = None
) -> "BaseRuntimeContext.Slot":
"""Register a context slot with an optional default value.
:type name: str
:param name: The name of the context slot.
:type default: object
:param name: The default value of the slot, can be a value or lambda.
:returns: The registered slot.
"""
with cls._lock:
if name not in cls._slots:
cls._slots[name] = cls.Slot(name, default)
return cls._slots[name]
def apply(self, snapshot: typing.Dict[str, "object"]) -> None:
"""Set the current context from a given snapshot dictionary"""
for name in snapshot:
setattr(self, name, snapshot[name])
def snapshot(self) -> typing.Dict[str, "object"]:
"""Return a dictionary of current slots by reference."""
keys = self._slots.keys()
return dict((n, self._slots[n].get()) for n in keys)
def __repr__(self) -> str:
return "{}({})".format(type(self).__name__, self.snapshot())
def __getattr__(self, name: str) -> "object":
if name not in self._slots:
self.register_slot(name, None)
slot = self._slots[name]
return slot.get()
def __setattr__(self, name: str, value: "object") -> None:
if name not in self._slots:
self.register_slot(name, None)
slot = self._slots[name]
slot.set(value)
def __getitem__(self, name: str) -> "object":
return self.__getattr__(name)
def __setitem__(self, name: str, value: "object") -> None:
self.__setattr__(name, value)
@contextmanager # type: ignore
def use(self, **kwargs: typing.Dict[str, object]) -> typing.Iterator[None]:
snapshot = {key: self[key] for key in kwargs}
for key in kwargs:
self[key] = kwargs[key]
yield
for key in kwargs:
self[key] = snapshot[key]
def with_current_context(
self, func: typing.Callable[..., "object"]
) -> typing.Callable[..., "object"]:
"""Capture the current context and apply it to the provided func.
"""
caller_context = self.snapshot()
def call_with_current_context(
*args: "object", **kwargs: "object"
) -> "object":
try:
backup_context = self.snapshot()
self.apply(caller_context)
return func(*args, **kwargs)
finally:
self.apply(backup_context)
return call_with_current_context