DefStream 0.1.22__90-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.
Files changed (73) hide show
  1. DefStream/Broker/Configuration.py +17 -0
  2. DefStream/Broker/Connection.py +141 -0
  3. DefStream/Broker/Consumer.py +59 -0
  4. DefStream/Broker/Errors.py +14 -0
  5. DefStream/Broker/Event.py +35 -0
  6. DefStream/Broker/Implements/RabbitMQ/Configuration.py +49 -0
  7. DefStream/Broker/Implements/RabbitMQ/Connection.py +550 -0
  8. DefStream/Broker/Implements/RabbitMQ/Consumer.py +416 -0
  9. DefStream/Broker/Implements/RabbitMQ/Event.py +146 -0
  10. DefStream/Broker/Implements/RabbitMQ/Exchange.py +277 -0
  11. DefStream/Broker/Implements/RabbitMQ/Queue.py +321 -0
  12. DefStream/Broker/Implements/RabbitMQ/Serializer.py +75 -0
  13. DefStream/Broker/Implements/RabbitMQ/Stream.py +181 -0
  14. DefStream/Broker/Implements/RabbitMQ/Subscription.py +90 -0
  15. DefStream/Broker/Implements/RabbitMQ/__init__.py +45 -0
  16. DefStream/Broker/Implements/Redis/Configuration.py +59 -0
  17. DefStream/Broker/Implements/Redis/Connection.py +265 -0
  18. DefStream/Broker/Implements/Redis/Consumer.py +368 -0
  19. DefStream/Broker/Implements/Redis/Event.py +212 -0
  20. DefStream/Broker/Implements/Redis/Queue.py +284 -0
  21. DefStream/Broker/Implements/Redis/Serializer.py +48 -0
  22. DefStream/Broker/Implements/Redis/Subscription.py +46 -0
  23. DefStream/Broker/Implements/Redis/__init__.py +29 -0
  24. DefStream/Broker/Implements/__init__.py +1 -0
  25. DefStream/Broker/Priority.py +26 -0
  26. DefStream/Broker/Protocol.py +54 -0
  27. DefStream/Broker/__init__.py +55 -0
  28. DefStream/Descriptor/DataObject.py +409 -0
  29. DefStream/Descriptor/Types.py +248 -0
  30. DefStream/Descriptor/Value.py +188 -0
  31. DefStream/Descriptor/__init__.py +172 -0
  32. DefStream/Inspector/Extension.py +69 -0
  33. DefStream/Inspector/Extensions/Metrics.py +316 -0
  34. DefStream/Inspector/Extensions/Ping.py +107 -0
  35. DefStream/Inspector/Extensions/Play.html +373 -0
  36. DefStream/Inspector/Extensions/Play.py +415 -0
  37. DefStream/Inspector/Extensions/Specifications.py +176 -0
  38. DefStream/Inspector/Extensions/Status.html +206 -0
  39. DefStream/Inspector/Extensions/Status.py +124 -0
  40. DefStream/Inspector/Extensions/__init__.py +13 -0
  41. DefStream/Inspector/Inspector.py +354 -0
  42. DefStream/Inspector/Response.py +14 -0
  43. DefStream/Inspector/__init__.py +9 -0
  44. DefStream/Validator/Pattern.py +36 -0
  45. DefStream/Validator/Patterns/Array.py +30 -0
  46. DefStream/Validator/Patterns/Common.py +92 -0
  47. DefStream/Validator/Patterns/Compare.py +180 -0
  48. DefStream/Validator/Patterns/Condition.py +60 -0
  49. DefStream/Validator/Patterns/DataObject.py +93 -0
  50. DefStream/Validator/Patterns/DateTime.py +111 -0
  51. DefStream/Validator/Patterns/Number.py +43 -0
  52. DefStream/Validator/Patterns/Object.py +158 -0
  53. DefStream/Validator/Patterns/Size.py +110 -0
  54. DefStream/Validator/Patterns/String.py +92 -0
  55. DefStream/Validator/Patterns/Type.py +355 -0
  56. DefStream/Validator/Patterns/__init__.py +137 -0
  57. DefStream/Validator/Validate.py +29 -0
  58. DefStream/Validator/Validator.py +30 -0
  59. DefStream/Validator/__init__.py +11 -0
  60. DefStream/Worker/Executor.py +525 -0
  61. DefStream/Worker/Message.py +180 -0
  62. DefStream/Worker/Pool.py +282 -0
  63. DefStream/Worker/Run.py +357 -0
  64. DefStream/Worker/Specification.py +87 -0
  65. DefStream/Worker/Startup.py +174 -0
  66. DefStream/Worker/Worker.py +571 -0
  67. DefStream/Worker/__init__.py +47 -0
  68. DefStream/__init__.py +0 -0
  69. defstream-0.1.22.dist-info/METADATA +92 -0
  70. defstream-0.1.22.dist-info/RECORD +73 -0
  71. defstream-0.1.22.dist-info/WHEEL +6 -0
  72. defstream-0.1.22.dist-info/licenses/LICENSE +674 -0
  73. defstream-0.1.22.dist-info/top_level.txt +1 -0
@@ -0,0 +1,180 @@
1
+ from collections.abc import Mapping
2
+ from inspect import isabstract
3
+ from typing import (
4
+ Any,
5
+ Optional,
6
+ Type,
7
+ )
8
+
9
+ from ..Broker.Connection import (
10
+ Connection,
11
+ Declarable,
12
+ Emittable,
13
+ Requestable,
14
+ PrioritySupport,
15
+ )
16
+ from .Run import (
17
+ Run,
18
+ priority_setting,
19
+ )
20
+
21
+ __all__ = (
22
+ 'declare',
23
+ 'emit',
24
+ 'request',
25
+ )
26
+
27
+
28
+ def task_parameters(
29
+ task: Type[Run],
30
+ ) -> Any:
31
+ if not isinstance(
32
+ task,
33
+ type,
34
+ ) or not issubclass(
35
+ task,
36
+ Run,
37
+ ) or isabstract(task):
38
+ raise TypeError('A concrete Run class is required')
39
+ if task.parameters is None:
40
+ raise ValueError('Run subscription parameters are required')
41
+ return task.parameters
42
+
43
+
44
+ def message_body(
45
+ body: Mapping,
46
+ ) -> dict:
47
+ if not isinstance(
48
+ body,
49
+ Mapping,
50
+ ) or not all(isinstance(
51
+ key,
52
+ str,
53
+ ) for key in body):
54
+ raise TypeError('Task body must be a mapping with string keys')
55
+ return dict(body)
56
+
57
+
58
+ def priority_parameters(
59
+ broker: Connection,
60
+ parameters: Any,
61
+ priority: Optional[int],
62
+ ) -> Any:
63
+ if priority_setting(
64
+ parameters,
65
+ 'priority',
66
+ ) is None and priority_setting(
67
+ parameters,
68
+ 'max_priority',
69
+ ) is None and priority is None:
70
+ return parameters
71
+ if not isinstance(
72
+ broker,
73
+ PrioritySupport,
74
+ ):
75
+ raise NotImplementedError('This connection does not support task priorities')
76
+ return broker.priority_parameters(
77
+ parameters,
78
+ )
79
+
80
+
81
+ def declare(
82
+ *,
83
+ task: Type[Run],
84
+ broker: Connection,
85
+ ) -> None:
86
+ parameters = task_parameters(task)
87
+ if not isinstance(
88
+ broker,
89
+ Declarable,
90
+ ):
91
+ raise NotImplementedError('This connection does not support task declarations')
92
+ broker.declare(priority_parameters(
93
+ broker,
94
+ parameters,
95
+ None,
96
+ ))
97
+ return
98
+
99
+
100
+ def emit(
101
+ body: Mapping,
102
+ *,
103
+ task: Type[Run],
104
+ broker: Connection,
105
+ priority: Optional[int] = None,
106
+ ) -> Any:
107
+ parameters = task_parameters(task)
108
+ payload = message_body(body)
109
+ if not isinstance(
110
+ broker,
111
+ Emittable,
112
+ ):
113
+ raise NotImplementedError('This connection does not support task emission')
114
+ parameters = priority_parameters(
115
+ broker,
116
+ parameters,
117
+ priority,
118
+ )
119
+ effective = priority_setting(
120
+ parameters,
121
+ 'priority',
122
+ ) if priority is None else priority
123
+ if effective is not None:
124
+ if not isinstance(
125
+ broker,
126
+ PrioritySupport,
127
+ ):
128
+ raise NotImplementedError('This connection does not support task priorities')
129
+ return broker.emit(
130
+ payload,
131
+ parameters,
132
+ priority=effective,
133
+ )
134
+ return broker.emit(
135
+ payload,
136
+ parameters,
137
+ )
138
+
139
+
140
+ def request(
141
+ body: Mapping,
142
+ *,
143
+ task: Type[Run],
144
+ broker: Connection,
145
+ timeout: float = 5,
146
+ priority: Optional[int] = None,
147
+ ) -> Any:
148
+ parameters = task_parameters(task)
149
+ payload = message_body(body)
150
+ if not isinstance(
151
+ broker,
152
+ Requestable,
153
+ ):
154
+ raise NotImplementedError('This connection does not support task RPC requests')
155
+ parameters = priority_parameters(
156
+ broker,
157
+ parameters,
158
+ priority,
159
+ )
160
+ effective = priority_setting(
161
+ parameters,
162
+ 'priority',
163
+ ) if priority is None else priority
164
+ if effective is not None:
165
+ if not isinstance(
166
+ broker,
167
+ PrioritySupport,
168
+ ):
169
+ raise NotImplementedError('This connection does not support task priorities')
170
+ return broker.request(
171
+ payload,
172
+ parameters,
173
+ timeout=timeout,
174
+ priority=effective,
175
+ )
176
+ return broker.request(
177
+ payload,
178
+ parameters,
179
+ timeout=timeout,
180
+ )
@@ -0,0 +1,282 @@
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('Worker.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.stopped = False
60
+ self.logger.info(
61
+ 'Pool configured: concurrency=%s',
62
+ max,
63
+ )
64
+
65
+ def submit(
66
+ self,
67
+ run: Type[Run],
68
+ body: Dict[str, Any],
69
+ callback: Optional[Callable[[Any], None]] = None,
70
+ error_callback: Optional[Callable[[BaseException], None]] = None,
71
+ ) -> Future:
72
+ with self.lock:
73
+ if self.closed:
74
+ raise RuntimeError('Pool is closed')
75
+ if not self.slots.acquire(blocking=False):
76
+ self.logger.debug(
77
+ 'Pool capacity exhausted: active=%s capacity=%s',
78
+ len(self.futures),
79
+ self.max,
80
+ )
81
+ raise PoolFull('Pool capacity is exhausted')
82
+ try:
83
+ future = self.pool.submit(
84
+ run(),
85
+ **body,
86
+ )
87
+ except BaseException:
88
+ self.slots.release()
89
+ raise
90
+ self.futures.add(future)
91
+ futures = self.futures
92
+ slots = self.slots
93
+ self.logger.debug(
94
+ 'Task submission accepted: task=%s.%s active=%s',
95
+ run.__module__,
96
+ run.__qualname__,
97
+ len(self.futures),
98
+ )
99
+ future.add_done_callback(lambda completed: self.complete(
100
+ completed,
101
+ callback,
102
+ error_callback,
103
+ futures,
104
+ slots,
105
+ ))
106
+ return future
107
+
108
+ def complete(
109
+ self,
110
+ future: Future,
111
+ callback: Optional[Callable[[Any], None]] = None,
112
+ error_callback: Optional[Callable[[BaseException], None]] = None,
113
+ futures: Optional[Set[Future]] = None,
114
+ slots: Optional[BoundedSemaphore] = None,
115
+ ) -> None:
116
+ with self.lock:
117
+ active = self.futures if futures is None else futures
118
+ capacity = self.slots if slots is None else slots
119
+ active.remove(future)
120
+ capacity.release()
121
+ self.logger.debug(
122
+ 'Task slot released: active=%s',
123
+ len(self.futures),
124
+ )
125
+ try:
126
+ result = future.result()
127
+ except BaseException as error:
128
+ self.logger.debug(
129
+ 'Delivering failed result: error_type=%s',
130
+ type(error).__qualname__,
131
+ )
132
+ if error_callback is not None:
133
+ error_callback(error)
134
+ else:
135
+ self.logger.debug('Delivering successful result')
136
+ if callback is not None:
137
+ callback(result)
138
+
139
+ def waits(
140
+ self,
141
+ timeout: Optional[float] = None,
142
+ ) -> None:
143
+ with self.lock:
144
+ tasks = tuple(self.futures)
145
+ self.logger.debug(
146
+ 'Waiting for Pool tasks: active=%s timeout=%s',
147
+ len(tasks),
148
+ timeout,
149
+ )
150
+ if tasks and wait(
151
+ tasks,
152
+ timeout=timeout,
153
+ ).not_done:
154
+ self.logger.warning(
155
+ 'Pool task wait timed out: timeout=%s',
156
+ timeout,
157
+ )
158
+ raise TimeoutError('Pool tasks did not complete in time')
159
+
160
+ def stop(self, *, abort: bool = False) -> None:
161
+ self.logger.info('Stopping Pool')
162
+ with self.lock:
163
+ self.closed = True
164
+ self.stopped = True
165
+ if abort:
166
+ if isinstance(self.pool, Executor):
167
+ self.pool.abort()
168
+ else:
169
+ self.logger.warning('Custom executor shutdown cannot terminate running tasks')
170
+ self.pool.shutdown(wait=False)
171
+ else:
172
+ self.pool.shutdown(wait=True)
173
+ self.logger.info('Pool shutdown completed')
174
+ return
175
+
176
+ def restart(self) -> None:
177
+ """Replace the internal executor while preserving this Pool object."""
178
+ with self.lock:
179
+ if self.closed:
180
+ raise RuntimeError('Pool is closed')
181
+ previous = self.pool
182
+ if not isinstance(previous, Executor):
183
+ raise TypeError('Pool recovery requires a DefStream Executor')
184
+ self.closed = True
185
+ previous.abort()
186
+ with self.lock:
187
+ if self.stopped:
188
+ return
189
+ self.pool = previous.replacement()
190
+ self.futures = set()
191
+ self.slots = BoundedSemaphore(self.max)
192
+ self.closed = False
193
+ return
194
+
195
+ def shutdown(self) -> None:
196
+ self.stop()
197
+
198
+ def size(self) -> int:
199
+ return self.max
200
+
201
+ def count(self) -> int:
202
+ with self.lock:
203
+ return len(self.futures)
204
+
205
+
206
+ class PoolSetup(ABC):
207
+ @abstractmethod
208
+ def __call__(self) -> None:
209
+ raise NotImplementedError
210
+
211
+
212
+ class PoolCleanup(ABC):
213
+ @abstractmethod
214
+ def __call__(self) -> None:
215
+ raise NotImplementedError
216
+
217
+
218
+ def pool_hooks(
219
+ hooks: Optional[Union[Callable[[], None], Sequence[Callable[[], None]]]],
220
+ ) -> Tuple[Callable[[], None], ...]:
221
+ result = () if hooks is None else tuple(hooks) if isinstance(
222
+ hooks,
223
+ Sequence,
224
+ ) else (hooks,)
225
+ if not all(callable(hook) for hook in result):
226
+ raise TypeError('Pool hooks must be callable')
227
+ return result
228
+
229
+
230
+ def pool_size(max: Optional[int]) -> int:
231
+ if max is None:
232
+ return cpu_count() or 1
233
+ if isinstance(
234
+ max,
235
+ bool,
236
+ ) or not isinstance(
237
+ max,
238
+ int,
239
+ ) or max < 1:
240
+ raise ValueError('Pool size must be a positive integer')
241
+ return max
242
+
243
+
244
+ class ThreadPool(Pool):
245
+ logger = getLogger('Worker.ThreadPool')
246
+
247
+ def __init__(
248
+ self,
249
+ max: Optional[int] = None,
250
+ setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
251
+ cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
252
+ ):
253
+ size = pool_size(max)
254
+ super().__init__(
255
+ Executor(
256
+ size,
257
+ pool_hooks(setups),
258
+ pool_hooks(cleanups),
259
+ ),
260
+ size,
261
+ )
262
+
263
+
264
+ class ProcessPool(Pool):
265
+ logger = getLogger('Worker.ProcessPool')
266
+
267
+ def __init__(
268
+ self,
269
+ max: Optional[int] = None,
270
+ setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
271
+ cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
272
+ ):
273
+ size = pool_size(max)
274
+ super().__init__(
275
+ Executor(
276
+ size,
277
+ pool_hooks(setups),
278
+ pool_hooks(cleanups),
279
+ process=True,
280
+ ),
281
+ size,
282
+ )