DefStream 0.1.12__35-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.
- DefStream/Broker/Configuration.py +18 -0
- DefStream/Broker/Connection.py +141 -0
- DefStream/Broker/Consumer.py +59 -0
- DefStream/Broker/Errors.py +14 -0
- DefStream/Broker/Event.py +35 -0
- DefStream/Broker/Implements/__init__.py +1 -0
- DefStream/Broker/Policies.py +25 -0
- DefStream/Broker/Priority.py +26 -0
- DefStream/Broker/Protocol.py +45 -0
- DefStream/Broker/__init__.py +59 -0
- DefStream/Descriptor/DataObject.py +409 -0
- DefStream/Descriptor/Types.py +248 -0
- DefStream/Descriptor/Value.py +188 -0
- DefStream/Descriptor/__init__.py +172 -0
- DefStream/Inspector/Extension.py +69 -0
- DefStream/Inspector/Extensions/Console.html +373 -0
- DefStream/Inspector/Extensions/Console.py +414 -0
- DefStream/Inspector/Extensions/Dashboard.html +206 -0
- DefStream/Inspector/Extensions/Dashboard.py +124 -0
- DefStream/Inspector/Extensions/HealthCheck.py +107 -0
- DefStream/Inspector/Extensions/Metrics.py +316 -0
- DefStream/Inspector/Extensions/Specifications.py +176 -0
- DefStream/Inspector/Extensions/__init__.py +13 -0
- DefStream/Inspector/Inspector.py +347 -0
- DefStream/Inspector/Response.py +14 -0
- DefStream/Inspector/__init__.py +9 -0
- DefStream/Validator/Pattern.py +36 -0
- DefStream/Validator/Patterns/Array.py +30 -0
- DefStream/Validator/Patterns/Common.py +93 -0
- DefStream/Validator/Patterns/Compare.py +180 -0
- DefStream/Validator/Patterns/Condition.py +60 -0
- DefStream/Validator/Patterns/DataObject.py +85 -0
- DefStream/Validator/Patterns/DateTime.py +111 -0
- DefStream/Validator/Patterns/Number.py +43 -0
- DefStream/Validator/Patterns/Object.py +150 -0
- DefStream/Validator/Patterns/Size.py +110 -0
- DefStream/Validator/Patterns/String.py +85 -0
- DefStream/Validator/Patterns/Type.py +350 -0
- DefStream/Validator/Patterns/__init__.py +137 -0
- DefStream/Validator/Validate.py +29 -0
- DefStream/Validator/Validator.py +30 -0
- DefStream/Validator/__init__.py +11 -0
- DefStream/Worker/Executor.py +371 -0
- DefStream/Worker/Message.py +180 -0
- DefStream/Worker/Pool.py +245 -0
- DefStream/Worker/Run.py +357 -0
- DefStream/Worker/Specification.py +87 -0
- DefStream/Worker/Startup.py +174 -0
- DefStream/Worker/Worker.py +421 -0
- DefStream/Worker/__init__.py +47 -0
- DefStream/__init__.py +0 -0
- defstream-0.1.12.dist-info/METADATA +679 -0
- defstream-0.1.12.dist-info/RECORD +56 -0
- defstream-0.1.12.dist-info/WHEEL +6 -0
- defstream-0.1.12.dist-info/licenses/LICENSE +674 -0
- defstream-0.1.12.dist-info/top_level.txt +1 -0
DefStream/Worker/Pool.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
from abc import (
|
|
2
|
+
ABC,
|
|
3
|
+
abstractmethod,
|
|
4
|
+
)
|
|
5
|
+
from concurrent.futures import (
|
|
6
|
+
Executor as PyExecutor,
|
|
7
|
+
Future,
|
|
8
|
+
wait,
|
|
9
|
+
)
|
|
10
|
+
from os import cpu_count
|
|
11
|
+
from logging import getLogger
|
|
12
|
+
from threading import (
|
|
13
|
+
BoundedSemaphore,
|
|
14
|
+
Lock,
|
|
15
|
+
)
|
|
16
|
+
from typing import (
|
|
17
|
+
Any,
|
|
18
|
+
Callable,
|
|
19
|
+
Dict,
|
|
20
|
+
Optional,
|
|
21
|
+
Sequence,
|
|
22
|
+
Set,
|
|
23
|
+
Tuple,
|
|
24
|
+
Type,
|
|
25
|
+
Union,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from .Run import Run
|
|
29
|
+
from .Executor import Executor
|
|
30
|
+
|
|
31
|
+
__all__ = (
|
|
32
|
+
'Pool',
|
|
33
|
+
'PoolFull',
|
|
34
|
+
'PoolSetup',
|
|
35
|
+
'PoolCleanup',
|
|
36
|
+
'ThreadPool',
|
|
37
|
+
'ProcessPool',
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PoolFull(RuntimeError):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Pool:
|
|
46
|
+
logger = getLogger('DefStream.Pool')
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
executor: PyExecutor,
|
|
51
|
+
max: int,
|
|
52
|
+
):
|
|
53
|
+
self.pool = executor
|
|
54
|
+
self.max = max
|
|
55
|
+
self.slots = BoundedSemaphore(max)
|
|
56
|
+
self.lock = Lock()
|
|
57
|
+
self.futures: Set[Future] = set()
|
|
58
|
+
self.closed = False
|
|
59
|
+
self.logger.info(
|
|
60
|
+
'Pool configured: concurrency=%s',
|
|
61
|
+
max,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def submit(
|
|
65
|
+
self,
|
|
66
|
+
run: Type[Run],
|
|
67
|
+
body: Dict[str, Any],
|
|
68
|
+
callback: Optional[Callable[[Any], None]] = None,
|
|
69
|
+
error_callback: Optional[Callable[[BaseException], None]] = None,
|
|
70
|
+
) -> Future:
|
|
71
|
+
with self.lock:
|
|
72
|
+
if self.closed:
|
|
73
|
+
raise RuntimeError('Pool is closed')
|
|
74
|
+
if not self.slots.acquire(blocking=False):
|
|
75
|
+
self.logger.debug(
|
|
76
|
+
'Pool capacity exhausted: active=%s capacity=%s',
|
|
77
|
+
len(self.futures),
|
|
78
|
+
self.max,
|
|
79
|
+
)
|
|
80
|
+
raise PoolFull('Pool capacity is exhausted')
|
|
81
|
+
try:
|
|
82
|
+
future = self.pool.submit(
|
|
83
|
+
run(),
|
|
84
|
+
**body,
|
|
85
|
+
)
|
|
86
|
+
except BaseException:
|
|
87
|
+
self.slots.release()
|
|
88
|
+
raise
|
|
89
|
+
self.futures.add(future)
|
|
90
|
+
self.logger.debug(
|
|
91
|
+
'Task submission accepted: task=%s.%s active=%s',
|
|
92
|
+
run.__module__,
|
|
93
|
+
run.__qualname__,
|
|
94
|
+
len(self.futures),
|
|
95
|
+
)
|
|
96
|
+
future.add_done_callback(lambda completed: self.complete(
|
|
97
|
+
completed,
|
|
98
|
+
callback,
|
|
99
|
+
error_callback,
|
|
100
|
+
))
|
|
101
|
+
return future
|
|
102
|
+
|
|
103
|
+
def complete(
|
|
104
|
+
self,
|
|
105
|
+
future: Future,
|
|
106
|
+
callback: Optional[Callable[[Any], None]] = None,
|
|
107
|
+
error_callback: Optional[Callable[[BaseException], None]] = None,
|
|
108
|
+
) -> None:
|
|
109
|
+
with self.lock:
|
|
110
|
+
self.futures.remove(future)
|
|
111
|
+
self.slots.release()
|
|
112
|
+
self.logger.debug(
|
|
113
|
+
'Task slot released: active=%s',
|
|
114
|
+
len(self.futures),
|
|
115
|
+
)
|
|
116
|
+
try:
|
|
117
|
+
result = future.result()
|
|
118
|
+
except BaseException as error:
|
|
119
|
+
self.logger.debug(
|
|
120
|
+
'Delivering failed result: error_type=%s',
|
|
121
|
+
type(error).__qualname__,
|
|
122
|
+
)
|
|
123
|
+
if error_callback is not None:
|
|
124
|
+
error_callback(error)
|
|
125
|
+
else:
|
|
126
|
+
self.logger.debug('Delivering successful result')
|
|
127
|
+
if callback is not None:
|
|
128
|
+
callback(result)
|
|
129
|
+
|
|
130
|
+
def waits(
|
|
131
|
+
self,
|
|
132
|
+
timeout: Optional[float] = None,
|
|
133
|
+
) -> None:
|
|
134
|
+
with self.lock:
|
|
135
|
+
tasks = tuple(self.futures)
|
|
136
|
+
self.logger.debug(
|
|
137
|
+
'Waiting for Pool tasks: active=%s timeout=%s',
|
|
138
|
+
len(tasks),
|
|
139
|
+
timeout,
|
|
140
|
+
)
|
|
141
|
+
if tasks and wait(
|
|
142
|
+
tasks,
|
|
143
|
+
timeout=timeout,
|
|
144
|
+
).not_done:
|
|
145
|
+
self.logger.warning(
|
|
146
|
+
'Pool task wait timed out: timeout=%s',
|
|
147
|
+
timeout,
|
|
148
|
+
)
|
|
149
|
+
raise TimeoutError('Pool tasks did not complete in time')
|
|
150
|
+
|
|
151
|
+
def stop(self) -> None:
|
|
152
|
+
self.logger.info('Stopping Pool')
|
|
153
|
+
with self.lock:
|
|
154
|
+
self.closed = True
|
|
155
|
+
self.pool.shutdown(wait=True)
|
|
156
|
+
self.logger.info('Pool shutdown completed')
|
|
157
|
+
|
|
158
|
+
def shutdown(self) -> None:
|
|
159
|
+
self.stop()
|
|
160
|
+
|
|
161
|
+
def size(self) -> int:
|
|
162
|
+
return self.max
|
|
163
|
+
|
|
164
|
+
def count(self) -> int:
|
|
165
|
+
with self.lock:
|
|
166
|
+
return len(self.futures)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class PoolSetup(ABC):
|
|
170
|
+
@abstractmethod
|
|
171
|
+
def __call__(self) -> None:
|
|
172
|
+
raise NotImplementedError
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class PoolCleanup(ABC):
|
|
176
|
+
@abstractmethod
|
|
177
|
+
def __call__(self) -> None:
|
|
178
|
+
raise NotImplementedError
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def pool_hooks(
|
|
182
|
+
hooks: Optional[Union[Callable[[], None], Sequence[Callable[[], None]]]],
|
|
183
|
+
) -> Tuple[Callable[[], None], ...]:
|
|
184
|
+
result = () if hooks is None else tuple(hooks) if isinstance(
|
|
185
|
+
hooks,
|
|
186
|
+
Sequence,
|
|
187
|
+
) else (hooks,)
|
|
188
|
+
if not all(callable(hook) for hook in result):
|
|
189
|
+
raise TypeError('Pool hooks must be callable')
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def pool_size(max: Optional[int]) -> int:
|
|
194
|
+
if max is None:
|
|
195
|
+
return cpu_count() or 1
|
|
196
|
+
if isinstance(
|
|
197
|
+
max,
|
|
198
|
+
bool,
|
|
199
|
+
) or not isinstance(
|
|
200
|
+
max,
|
|
201
|
+
int,
|
|
202
|
+
) or max < 1:
|
|
203
|
+
raise ValueError('Pool size must be a positive integer')
|
|
204
|
+
return max
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class ThreadPool(Pool):
|
|
208
|
+
logger = getLogger('DefStream.ThreadPool')
|
|
209
|
+
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
max: Optional[int] = None,
|
|
213
|
+
setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
|
|
214
|
+
cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
|
|
215
|
+
):
|
|
216
|
+
size = pool_size(max)
|
|
217
|
+
super().__init__(
|
|
218
|
+
Executor(
|
|
219
|
+
size,
|
|
220
|
+
pool_hooks(setups),
|
|
221
|
+
pool_hooks(cleanups),
|
|
222
|
+
),
|
|
223
|
+
size,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class ProcessPool(Pool):
|
|
228
|
+
logger = getLogger('DefStream.ProcessPool')
|
|
229
|
+
|
|
230
|
+
def __init__(
|
|
231
|
+
self,
|
|
232
|
+
max: Optional[int] = None,
|
|
233
|
+
setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
|
|
234
|
+
cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
|
|
235
|
+
):
|
|
236
|
+
size = pool_size(max)
|
|
237
|
+
super().__init__(
|
|
238
|
+
Executor(
|
|
239
|
+
size,
|
|
240
|
+
pool_hooks(setups),
|
|
241
|
+
pool_hooks(cleanups),
|
|
242
|
+
process=True,
|
|
243
|
+
),
|
|
244
|
+
size,
|
|
245
|
+
)
|
DefStream/Worker/Run.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
from abc import (
|
|
2
|
+
ABC,
|
|
3
|
+
ABCMeta,
|
|
4
|
+
abstractmethod,
|
|
5
|
+
)
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from logging import getLogger
|
|
8
|
+
from re import fullmatch
|
|
9
|
+
from time import monotonic
|
|
10
|
+
from typing import (
|
|
11
|
+
Any,
|
|
12
|
+
Dict,
|
|
13
|
+
Optional,
|
|
14
|
+
Sequence,
|
|
15
|
+
Tuple,
|
|
16
|
+
Union,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from ..Broker.Event import EventError
|
|
20
|
+
from ..Broker.Priority import validate_priority
|
|
21
|
+
from .Specification import Specification
|
|
22
|
+
|
|
23
|
+
__all__ = (
|
|
24
|
+
'Context',
|
|
25
|
+
'RunSetup',
|
|
26
|
+
'RunComplete',
|
|
27
|
+
'RunError',
|
|
28
|
+
'Run',
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def priority_setting(
|
|
33
|
+
parameters: Any,
|
|
34
|
+
name: str,
|
|
35
|
+
) -> Optional[int]:
|
|
36
|
+
if isinstance(
|
|
37
|
+
parameters,
|
|
38
|
+
Mapping,
|
|
39
|
+
):
|
|
40
|
+
return parameters.get(name)
|
|
41
|
+
return getattr(
|
|
42
|
+
parameters,
|
|
43
|
+
name,
|
|
44
|
+
None,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Context:
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*args,
|
|
52
|
+
**kwargs,
|
|
53
|
+
):
|
|
54
|
+
self.args = args
|
|
55
|
+
self.kwargs = kwargs
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class RunSetup(ABC):
|
|
59
|
+
@abstractmethod
|
|
60
|
+
def __call__(
|
|
61
|
+
self,
|
|
62
|
+
context: Context,
|
|
63
|
+
) -> None:
|
|
64
|
+
raise NotImplementedError
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RunComplete(ABC):
|
|
68
|
+
@abstractmethod
|
|
69
|
+
def __call__(
|
|
70
|
+
self,
|
|
71
|
+
context: Context,
|
|
72
|
+
completion: Any,
|
|
73
|
+
) -> None:
|
|
74
|
+
raise NotImplementedError
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class RunError(ABC):
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def __call__(
|
|
80
|
+
self,
|
|
81
|
+
context: Context,
|
|
82
|
+
error: Exception,
|
|
83
|
+
) -> None:
|
|
84
|
+
raise NotImplementedError
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class RunMeta(ABCMeta):
|
|
88
|
+
"""구버전 ABCMeta의 클래스 이름 인자와 Run의 name 키워드 충돌을 방지한다."""
|
|
89
|
+
|
|
90
|
+
def __new__(
|
|
91
|
+
mcls,
|
|
92
|
+
class_name: str,
|
|
93
|
+
bases: Tuple[type, ...],
|
|
94
|
+
namespace: Dict[str, Any],
|
|
95
|
+
/,
|
|
96
|
+
**kwargs: Any,
|
|
97
|
+
) -> 'RunMeta':
|
|
98
|
+
if 'name' in kwargs:
|
|
99
|
+
kwargs['run_name'] = kwargs.pop('name')
|
|
100
|
+
return super().__new__(
|
|
101
|
+
mcls,
|
|
102
|
+
class_name,
|
|
103
|
+
bases,
|
|
104
|
+
namespace,
|
|
105
|
+
**kwargs,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Run(ABC, metaclass=RunMeta):
|
|
110
|
+
logger = getLogger('DefStream.Run')
|
|
111
|
+
parameters: Any = None
|
|
112
|
+
name: str = __module__ + '.' + __qualname__
|
|
113
|
+
description: Optional[str] = None
|
|
114
|
+
on_error: Optional[EventError] = None
|
|
115
|
+
setups: Tuple[RunSetup, ...] = ()
|
|
116
|
+
completes: Tuple[RunComplete, ...] = ()
|
|
117
|
+
errors: Tuple[RunError, ...] = ()
|
|
118
|
+
request: Optional[Specification] = None
|
|
119
|
+
response: Optional[Specification] = None
|
|
120
|
+
|
|
121
|
+
def __init_subclass__(
|
|
122
|
+
cls,
|
|
123
|
+
*,
|
|
124
|
+
run_name: Optional[str] = None,
|
|
125
|
+
description: Optional[str] = None,
|
|
126
|
+
parameters: Any = None,
|
|
127
|
+
on_error: Optional[EventError] = None,
|
|
128
|
+
setups: Optional[Union[RunSetup, Sequence[RunSetup]]] = None,
|
|
129
|
+
completes: Optional[Union[RunComplete, Sequence[RunComplete]]] = None,
|
|
130
|
+
errors: Optional[Union[RunError, Sequence[RunError]]] = None,
|
|
131
|
+
request: Optional[Specification] = None,
|
|
132
|
+
response: Optional[Specification] = None,
|
|
133
|
+
**kwargs,
|
|
134
|
+
):
|
|
135
|
+
super().__init_subclass__(**kwargs)
|
|
136
|
+
if run_name is not None and not isinstance(
|
|
137
|
+
run_name,
|
|
138
|
+
str,
|
|
139
|
+
):
|
|
140
|
+
raise TypeError('Run name must be a string or None')
|
|
141
|
+
if run_name is not None and fullmatch(
|
|
142
|
+
r'[A-Za-z0-9_.-]+',
|
|
143
|
+
run_name,
|
|
144
|
+
) is None:
|
|
145
|
+
raise ValueError('Run name must contain only ASCII letters, digits, underscores, dots or hyphens')
|
|
146
|
+
if description is not None and not isinstance(
|
|
147
|
+
description,
|
|
148
|
+
str,
|
|
149
|
+
):
|
|
150
|
+
raise TypeError('Run description must be a string or None')
|
|
151
|
+
cls.name = run_name if run_name is not None else cls.__module__ + '.' + cls.__qualname__
|
|
152
|
+
cls.description = description
|
|
153
|
+
parents = tuple(base for base in cls.__mro__[1:] if issubclass(
|
|
154
|
+
base,
|
|
155
|
+
Run,
|
|
156
|
+
))
|
|
157
|
+
if parameters is not None:
|
|
158
|
+
cls.parameters = parameters
|
|
159
|
+
for name in (
|
|
160
|
+
'priority',
|
|
161
|
+
'max_priority',
|
|
162
|
+
):
|
|
163
|
+
if any(priority_setting(
|
|
164
|
+
base.parameters,
|
|
165
|
+
name,
|
|
166
|
+
) is not None for base in parents) and priority_setting(
|
|
167
|
+
cls.parameters,
|
|
168
|
+
name,
|
|
169
|
+
) is None:
|
|
170
|
+
raise ValueError('Inherited task ' + name + ' cannot be cleared')
|
|
171
|
+
maximum = priority_setting(
|
|
172
|
+
cls.parameters,
|
|
173
|
+
'max_priority',
|
|
174
|
+
)
|
|
175
|
+
validate_priority(
|
|
176
|
+
maximum,
|
|
177
|
+
None,
|
|
178
|
+
minimum=1,
|
|
179
|
+
name='max_priority',
|
|
180
|
+
)
|
|
181
|
+
validate_priority(
|
|
182
|
+
priority_setting(
|
|
183
|
+
cls.parameters,
|
|
184
|
+
'priority',
|
|
185
|
+
),
|
|
186
|
+
maximum,
|
|
187
|
+
)
|
|
188
|
+
for name, specification in (
|
|
189
|
+
(
|
|
190
|
+
'request',
|
|
191
|
+
request,
|
|
192
|
+
),
|
|
193
|
+
(
|
|
194
|
+
'response',
|
|
195
|
+
response,
|
|
196
|
+
),
|
|
197
|
+
):
|
|
198
|
+
if specification is not None:
|
|
199
|
+
if not isinstance(
|
|
200
|
+
specification,
|
|
201
|
+
Specification,
|
|
202
|
+
):
|
|
203
|
+
raise TypeError(name + ' must be a Specification')
|
|
204
|
+
setattr(
|
|
205
|
+
cls,
|
|
206
|
+
name,
|
|
207
|
+
specification,
|
|
208
|
+
)
|
|
209
|
+
if on_error is not None:
|
|
210
|
+
if not callable(on_error):
|
|
211
|
+
raise TypeError('on_error must be a callable event error policy')
|
|
212
|
+
cls.on_error = on_error
|
|
213
|
+
if setups is not None:
|
|
214
|
+
cls.setups = tuple(setups) if isinstance(
|
|
215
|
+
setups,
|
|
216
|
+
Sequence,
|
|
217
|
+
) else (setups,)
|
|
218
|
+
if completes is not None:
|
|
219
|
+
cls.completes = tuple(completes) if isinstance(
|
|
220
|
+
completes,
|
|
221
|
+
Sequence,
|
|
222
|
+
) else (completes,)
|
|
223
|
+
if errors is not None:
|
|
224
|
+
cls.errors = tuple(errors) if isinstance(
|
|
225
|
+
errors,
|
|
226
|
+
Sequence,
|
|
227
|
+
) else (errors,)
|
|
228
|
+
for hooks in (
|
|
229
|
+
cls.setups,
|
|
230
|
+
cls.completes,
|
|
231
|
+
cls.errors,
|
|
232
|
+
):
|
|
233
|
+
if not all(callable(hook) for hook in hooks):
|
|
234
|
+
raise TypeError('Run hooks must be callable')
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
def __call__(
|
|
238
|
+
self,
|
|
239
|
+
*args,
|
|
240
|
+
**kwargs,
|
|
241
|
+
) -> Any:
|
|
242
|
+
task = type(self).__module__ + '.' + type(self).__qualname__
|
|
243
|
+
started = monotonic()
|
|
244
|
+
self.logger.debug(
|
|
245
|
+
'Starting task execution: task=%s',
|
|
246
|
+
task,
|
|
247
|
+
)
|
|
248
|
+
context = Context(
|
|
249
|
+
*args,
|
|
250
|
+
**kwargs,
|
|
251
|
+
)
|
|
252
|
+
for setup in self.setups:
|
|
253
|
+
self.logger.debug(
|
|
254
|
+
'Starting task setup: task=%s hook=%s',
|
|
255
|
+
task,
|
|
256
|
+
type(setup).__qualname__,
|
|
257
|
+
)
|
|
258
|
+
setup(context)
|
|
259
|
+
self.logger.debug(
|
|
260
|
+
'Task setup completed: task=%s hook=%s',
|
|
261
|
+
task,
|
|
262
|
+
type(setup).__qualname__,
|
|
263
|
+
)
|
|
264
|
+
try:
|
|
265
|
+
if self.request is not None:
|
|
266
|
+
self.logger.debug(
|
|
267
|
+
'Validating task input: task=%s',
|
|
268
|
+
task,
|
|
269
|
+
)
|
|
270
|
+
if context.args:
|
|
271
|
+
raise TypeError('A specified task request requires keyword arguments')
|
|
272
|
+
body = self.request(context.kwargs)
|
|
273
|
+
if not isinstance(
|
|
274
|
+
body,
|
|
275
|
+
Mapping,
|
|
276
|
+
) or not all(isinstance(
|
|
277
|
+
key,
|
|
278
|
+
str,
|
|
279
|
+
) for key in body):
|
|
280
|
+
raise TypeError('A task request must remain a mapping with string keys')
|
|
281
|
+
context.kwargs = dict(body)
|
|
282
|
+
self.logger.debug(
|
|
283
|
+
'Task input validated: task=%s',
|
|
284
|
+
task,
|
|
285
|
+
)
|
|
286
|
+
self.logger.debug(
|
|
287
|
+
'Calling user task: task=%s',
|
|
288
|
+
task,
|
|
289
|
+
)
|
|
290
|
+
result = self.run(
|
|
291
|
+
*context.args,
|
|
292
|
+
**context.kwargs,
|
|
293
|
+
)
|
|
294
|
+
self.logger.debug(
|
|
295
|
+
'User task returned: task=%s',
|
|
296
|
+
task,
|
|
297
|
+
)
|
|
298
|
+
if self.response is not None:
|
|
299
|
+
self.logger.debug(
|
|
300
|
+
'Validating task output: task=%s',
|
|
301
|
+
task,
|
|
302
|
+
)
|
|
303
|
+
result = self.response(result)
|
|
304
|
+
self.logger.debug(
|
|
305
|
+
'Task output validated: task=%s',
|
|
306
|
+
task,
|
|
307
|
+
)
|
|
308
|
+
except Exception as error:
|
|
309
|
+
self.logger.debug(
|
|
310
|
+
'Task execution or validation failed: task=%s error_type=%s',
|
|
311
|
+
task,
|
|
312
|
+
type(error).__qualname__,
|
|
313
|
+
)
|
|
314
|
+
for handler in self.errors:
|
|
315
|
+
self.logger.debug(
|
|
316
|
+
'Starting task error hook: task=%s hook=%s',
|
|
317
|
+
task,
|
|
318
|
+
type(handler).__qualname__,
|
|
319
|
+
)
|
|
320
|
+
handler(
|
|
321
|
+
context,
|
|
322
|
+
error,
|
|
323
|
+
)
|
|
324
|
+
self.logger.debug(
|
|
325
|
+
'Task error hook completed: task=%s hook=%s',
|
|
326
|
+
task,
|
|
327
|
+
type(handler).__qualname__,
|
|
328
|
+
)
|
|
329
|
+
raise
|
|
330
|
+
for complete in self.completes:
|
|
331
|
+
self.logger.debug(
|
|
332
|
+
'Starting task completion hook: task=%s hook=%s',
|
|
333
|
+
task,
|
|
334
|
+
type(complete).__qualname__,
|
|
335
|
+
)
|
|
336
|
+
complete(
|
|
337
|
+
context,
|
|
338
|
+
result,
|
|
339
|
+
)
|
|
340
|
+
self.logger.debug(
|
|
341
|
+
'Task completion hook completed: task=%s hook=%s',
|
|
342
|
+
task,
|
|
343
|
+
type(complete).__qualname__,
|
|
344
|
+
)
|
|
345
|
+
self.logger.debug(
|
|
346
|
+
'Task execution completed: task=%s duration=%s',
|
|
347
|
+
task,
|
|
348
|
+
monotonic() - started,
|
|
349
|
+
)
|
|
350
|
+
return result
|
|
351
|
+
|
|
352
|
+
@abstractmethod
|
|
353
|
+
def run(
|
|
354
|
+
self,
|
|
355
|
+
**kwargs,
|
|
356
|
+
) -> Any:
|
|
357
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from copy import deepcopy
|
|
3
|
+
from dataclasses import is_dataclass
|
|
4
|
+
from re import fullmatch
|
|
5
|
+
from typing import (
|
|
6
|
+
Any,
|
|
7
|
+
Callable,
|
|
8
|
+
Optional,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
from ..Descriptor import (
|
|
12
|
+
DumpSchema,
|
|
13
|
+
Schema,
|
|
14
|
+
ToSchema,
|
|
15
|
+
)
|
|
16
|
+
from ..Descriptor.Value import (
|
|
17
|
+
Condition,
|
|
18
|
+
Descriptor,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = (
|
|
22
|
+
'Specification',
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Specification:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
schema: Any = None,
|
|
30
|
+
validator: Optional[Callable[[Any], Any]] = None,
|
|
31
|
+
example: Any = ...,
|
|
32
|
+
format: str = 'application/json',
|
|
33
|
+
):
|
|
34
|
+
if not isinstance(
|
|
35
|
+
format,
|
|
36
|
+
str,
|
|
37
|
+
) or fullmatch(
|
|
38
|
+
r"[!#$%&'+.^_`|~0-9A-Za-z-]+/[!#$%&'+.^_`|~0-9A-Za-z-]+(?:[ \t]*;[^\r\n]+)?",
|
|
39
|
+
format,
|
|
40
|
+
) is None:
|
|
41
|
+
raise ValueError('Specification format must be a concrete media type')
|
|
42
|
+
if validator is not None and not callable(validator):
|
|
43
|
+
raise TypeError('A Specification validator must be callable')
|
|
44
|
+
if isinstance(
|
|
45
|
+
schema,
|
|
46
|
+
type,
|
|
47
|
+
) and is_dataclass(schema):
|
|
48
|
+
schema = ToSchema(schema)
|
|
49
|
+
if schema is not None and not isinstance(
|
|
50
|
+
schema,
|
|
51
|
+
(
|
|
52
|
+
Schema,
|
|
53
|
+
Descriptor,
|
|
54
|
+
Condition,
|
|
55
|
+
Mapping,
|
|
56
|
+
),
|
|
57
|
+
):
|
|
58
|
+
raise TypeError('A Descriptor schema, schema mapping or dataclass type is required')
|
|
59
|
+
self.schema = schema
|
|
60
|
+
self.validator = validator
|
|
61
|
+
self.example = example
|
|
62
|
+
self.format = format
|
|
63
|
+
self.document()
|
|
64
|
+
|
|
65
|
+
def __call__(
|
|
66
|
+
self,
|
|
67
|
+
value: Any,
|
|
68
|
+
) -> Any:
|
|
69
|
+
return self.validator(value) if self.validator is not None else value
|
|
70
|
+
|
|
71
|
+
def document(self) -> dict:
|
|
72
|
+
payload = {} if self.schema is None else DumpSchema(
|
|
73
|
+
self.schema if isinstance(
|
|
74
|
+
self.schema,
|
|
75
|
+
Schema,
|
|
76
|
+
) else Schema(
|
|
77
|
+
'Payload',
|
|
78
|
+
self.schema,
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
message = {
|
|
82
|
+
'contentType': self.format,
|
|
83
|
+
'payload': payload,
|
|
84
|
+
}
|
|
85
|
+
if self.example is not ...:
|
|
86
|
+
message['examples'] = [{'payload': deepcopy(self.example)}]
|
|
87
|
+
return message
|