DefStream 0.1.18__74-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 (75) hide show
  1. DefStream/Broker/Configuration.py +18 -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 +547 -0
  8. DefStream/Broker/Implements/RabbitMQ/Consumer.py +358 -0
  9. DefStream/Broker/Implements/RabbitMQ/Event.py +127 -0
  10. DefStream/Broker/Implements/RabbitMQ/Exchange.py +278 -0
  11. DefStream/Broker/Implements/RabbitMQ/Policies.py +9 -0
  12. DefStream/Broker/Implements/RabbitMQ/Queue.py +321 -0
  13. DefStream/Broker/Implements/RabbitMQ/Serializer.py +75 -0
  14. DefStream/Broker/Implements/RabbitMQ/Stream.py +181 -0
  15. DefStream/Broker/Implements/RabbitMQ/Subscription.py +74 -0
  16. DefStream/Broker/Implements/RabbitMQ/__init__.py +47 -0
  17. DefStream/Broker/Implements/Redis/Configuration.py +59 -0
  18. DefStream/Broker/Implements/Redis/Connection.py +265 -0
  19. DefStream/Broker/Implements/Redis/Consumer.py +364 -0
  20. DefStream/Broker/Implements/Redis/Event.py +191 -0
  21. DefStream/Broker/Implements/Redis/Queue.py +284 -0
  22. DefStream/Broker/Implements/Redis/Serializer.py +48 -0
  23. DefStream/Broker/Implements/Redis/Subscription.py +46 -0
  24. DefStream/Broker/Implements/Redis/__init__.py +29 -0
  25. DefStream/Broker/Implements/__init__.py +1 -0
  26. DefStream/Broker/Policies.py +25 -0
  27. DefStream/Broker/Priority.py +26 -0
  28. DefStream/Broker/Protocol.py +45 -0
  29. DefStream/Broker/__init__.py +59 -0
  30. DefStream/Descriptor/DataObject.py +409 -0
  31. DefStream/Descriptor/Types.py +248 -0
  32. DefStream/Descriptor/Value.py +188 -0
  33. DefStream/Descriptor/__init__.py +172 -0
  34. DefStream/Inspector/Extension.py +69 -0
  35. DefStream/Inspector/Extensions/Console.html +373 -0
  36. DefStream/Inspector/Extensions/Console.py +415 -0
  37. DefStream/Inspector/Extensions/Metrics.py +316 -0
  38. DefStream/Inspector/Extensions/Ping.py +107 -0
  39. DefStream/Inspector/Extensions/Specifications.py +176 -0
  40. DefStream/Inspector/Extensions/Status.html +206 -0
  41. DefStream/Inspector/Extensions/Status.py +124 -0
  42. DefStream/Inspector/Extensions/__init__.py +13 -0
  43. DefStream/Inspector/Inspector.py +347 -0
  44. DefStream/Inspector/Response.py +14 -0
  45. DefStream/Inspector/__init__.py +9 -0
  46. DefStream/Validator/Pattern.py +36 -0
  47. DefStream/Validator/Patterns/Array.py +30 -0
  48. DefStream/Validator/Patterns/Common.py +92 -0
  49. DefStream/Validator/Patterns/Compare.py +180 -0
  50. DefStream/Validator/Patterns/Condition.py +60 -0
  51. DefStream/Validator/Patterns/DataObject.py +85 -0
  52. DefStream/Validator/Patterns/DateTime.py +111 -0
  53. DefStream/Validator/Patterns/Number.py +43 -0
  54. DefStream/Validator/Patterns/Object.py +150 -0
  55. DefStream/Validator/Patterns/Size.py +110 -0
  56. DefStream/Validator/Patterns/String.py +85 -0
  57. DefStream/Validator/Patterns/Type.py +350 -0
  58. DefStream/Validator/Patterns/__init__.py +137 -0
  59. DefStream/Validator/Validate.py +29 -0
  60. DefStream/Validator/Validator.py +30 -0
  61. DefStream/Validator/__init__.py +11 -0
  62. DefStream/Worker/Executor.py +371 -0
  63. DefStream/Worker/Message.py +180 -0
  64. DefStream/Worker/Pool.py +245 -0
  65. DefStream/Worker/Run.py +357 -0
  66. DefStream/Worker/Specification.py +87 -0
  67. DefStream/Worker/Startup.py +174 -0
  68. DefStream/Worker/Worker.py +421 -0
  69. DefStream/Worker/__init__.py +47 -0
  70. DefStream/__init__.py +0 -0
  71. defstream-0.1.18.dist-info/METADATA +92 -0
  72. defstream-0.1.18.dist-info/RECORD +75 -0
  73. defstream-0.1.18.dist-info/WHEEL +6 -0
  74. defstream-0.1.18.dist-info/licenses/LICENSE +674 -0
  75. defstream-0.1.18.dist-info/top_level.txt +1 -0
@@ -0,0 +1,547 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from DefStream.Broker import (
4
+ Connection as BaseConnection,
5
+ GetExchange,
6
+ GetQueue,
7
+ GetStream,
8
+ GetConsumer,
9
+ Declarable,
10
+ PrioritySupport,
11
+ EventHandler,
12
+ )
13
+
14
+ from .Configuration import Configuration
15
+
16
+ from .Exchange import Exchange
17
+ from .Queue import Queue
18
+ from .Stream import Stream
19
+ from .Consumer import Consumer
20
+ from .Subscription import Subscription
21
+
22
+ from pika import (
23
+ BlockingConnection,
24
+ ConnectionParameters,
25
+ PlainCredentials,
26
+ BasicProperties,
27
+ )
28
+
29
+ from collections.abc import (
30
+ Mapping,
31
+ KeysView,
32
+ ItemsView,
33
+ ValuesView,
34
+ )
35
+ from operator import (
36
+ eq,
37
+ ne,
38
+ )
39
+ from enum import Enum
40
+ from uuid import uuid4
41
+ from contextlib import contextmanager
42
+ from logging import getLogger
43
+
44
+ from typing import (
45
+ Any as AnyValue,
46
+ Dict,
47
+ Iterator,
48
+ Union,
49
+ Optional,
50
+ )
51
+
52
+ __all__ = (
53
+ 'Connection',
54
+ 'ExchangeType',
55
+ 'Parameters',
56
+ 'All',
57
+ 'Any',
58
+ )
59
+
60
+
61
+ class ExchangeType(str, Enum):
62
+ Direct = 'direct'
63
+ FanOut = 'fanout'
64
+ Topic = 'topic'
65
+ Header = 'headers'
66
+ def __str__(self): return str(self.value)
67
+
68
+
69
+ class Parameters(Mapping):
70
+ """Bind Parameters Event Broker for RabbitMQ"""
71
+ def __init__(self, **kwargs):
72
+ self.args = kwargs
73
+ return
74
+
75
+ def __iter__(self) -> Iterator:
76
+ return self.args.__iter__()
77
+
78
+ def __reversed__(self) -> Iterator:
79
+ return self.args.__reversed__()
80
+
81
+ def __len__(self) -> int:
82
+ return self.args.__len__()
83
+
84
+ def __getitem__(
85
+ self,
86
+ key: AnyValue,
87
+ ) -> AnyValue:
88
+ return self.args.__getitem__(key)
89
+
90
+ def __contains__(self, key: object) -> bool:
91
+ return self.args.__contains__(key)
92
+
93
+ def __eq__(self, other) -> bool:
94
+ return eq(self.args, other)
95
+
96
+ def __ne__(self, other) -> bool:
97
+ return ne(self.args, other)
98
+
99
+ def keys(self) -> KeysView:
100
+ return self.args.keys()
101
+
102
+ def items(self) -> ItemsView:
103
+ return self.args.items()
104
+
105
+ def values(self) -> ValuesView:
106
+ return self.args.values()
107
+
108
+
109
+ class Connection(
110
+ BaseConnection,
111
+ GetExchange,
112
+ GetQueue,
113
+ GetStream,
114
+ GetConsumer,
115
+ Declarable,
116
+ PrioritySupport,
117
+ ):
118
+ """Connection of Event Broker for RabbitMQ"""
119
+ logger = getLogger('DefStream.Broker.RabbitMQ.Connection')
120
+
121
+ def __init__(self, conf: Configuration):
122
+ self.conf = conf
123
+ self.parameters = ConnectionParameters(
124
+ host=self.conf.host,
125
+ port=self.conf.port,
126
+ credentials=PlainCredentials(self.conf.username, self.conf.password),
127
+ virtual_host=self.conf.vhost,
128
+ ssl_options=self.conf.ssl,
129
+ blocked_connection_timeout=self.conf.timeout,
130
+ heartbeat=self.conf.heartbeat
131
+ )
132
+ self.connection = None
133
+ self.publisher = None
134
+ return
135
+
136
+ def __del__(self):
137
+ self.close()
138
+ return
139
+
140
+ def connect(self):
141
+ if self.connection and self.connection.is_open:
142
+ self.logger.debug('Reusing open connection')
143
+ return
144
+ self.logger.debug('Connecting to RabbitMQ: host=%s port=%s vhost=%s', self.conf.host, self.conf.port, self.conf.vhost)
145
+ with self.observe('RabbitMQ connection'):
146
+ self.connection = BlockingConnection(parameters=self.parameters)
147
+ return
148
+
149
+ @contextmanager
150
+ def observe(
151
+ self,
152
+ operation: str,
153
+ *context,
154
+ ):
155
+ """Log failures only at I/O boundaries owned by this class, without exposing exception details."""
156
+ try:
157
+ yield
158
+ except Exception as error:
159
+ self.logger.error(operation + ' failed: error_type=%s', *context, type(error).__name__)
160
+ raise
161
+ else:
162
+ self.logger.debug(operation + ' completed', *context)
163
+ return
164
+
165
+ def connected(self):
166
+ if self.connection is None or not self.connection.is_open:
167
+ self.logger.error('RabbitMQ connection is not open')
168
+ raise RuntimeError('Connect the RabbitMQ connection before use')
169
+ return self.connection
170
+
171
+ def declare(
172
+ self,
173
+ parameters: AnyValue,
174
+ ) -> None:
175
+ subscription = Subscription.parse(parameters)
176
+ self.logger.debug('Task queue declaration: queue=%s error_queue=%s max_priority=%s durable=True', subscription.queue, subscription.error, subscription.max_priority)
177
+ connection = self.connected()
178
+ with self.observe('Task queue declaration'):
179
+ channel = connection.channel()
180
+ try:
181
+ arguments: Dict[str, AnyValue] = {}
182
+ if subscription.error is not None:
183
+ channel.queue_declare(
184
+ subscription.error,
185
+ durable=True,
186
+ )
187
+ arguments = {
188
+ 'x-dead-letter-exchange': '',
189
+ 'x-dead-letter-routing-key': subscription.error,
190
+ }
191
+ if subscription.max_priority is not None:
192
+ arguments['x-max-priority'] = subscription.max_priority
193
+ channel.queue_declare(
194
+ subscription.queue,
195
+ durable=True,
196
+ arguments=arguments,
197
+ )
198
+ finally:
199
+ if channel.is_open:
200
+ channel.close()
201
+ return
202
+
203
+ def priority_parameters(
204
+ self,
205
+ parameters: AnyValue,
206
+ ) -> Subscription:
207
+ """작업 기본값을 검증하고 선언·발행에 사용할 구독 설정을 반환한다."""
208
+ return Subscription.parse(parameters)
209
+
210
+ def emit(
211
+ self,
212
+ body: AnyValue,
213
+ parameters: AnyValue,
214
+ *,
215
+ priority: Optional[int] = None,
216
+ ) -> str:
217
+ subscription = Subscription.parse(parameters)
218
+ if priority is None:
219
+ priority = subscription.priority
220
+ subscription.validate_priority(priority)
221
+ connection = self.connected()
222
+ channel = self.publisher
223
+ if channel is None or not channel.is_open:
224
+ try:
225
+ channel = connection.channel()
226
+ channel.confirm_delivery()
227
+ self.logger.debug('Publisher channel created: publisher_confirm=True')
228
+ except Exception as error:
229
+ self.logger.error('Publisher channel creation failed: queue=%s error_type=%s', subscription.queue, type(error).__name__)
230
+ if channel is not None and channel.is_open:
231
+ channel.close()
232
+ raise
233
+ self.publisher = channel
234
+ else:
235
+ self.logger.debug('Reusing publisher channel: publisher_confirm=True')
236
+ id = uuid4().hex
237
+ self.logger.debug('Publishing directly: queue=%s message_id=%s priority=%s publisher_confirm=True', subscription.queue, id, priority)
238
+ try:
239
+ channel.basic_publish(
240
+ exchange='',
241
+ routing_key=subscription.queue,
242
+ body=self.conf.encode(body),
243
+ properties=BasicProperties(
244
+ message_id=id,
245
+ headers={},
246
+ content_type=self.conf.encode.format,
247
+ content_encoding=self.conf.encode.charset,
248
+ delivery_mode=2,
249
+ priority=priority,
250
+ ),
251
+ mandatory=True,
252
+ )
253
+ except Exception as error:
254
+ self.logger.error('Direct publication failed: queue=%s message_id=%s error_type=%s', subscription.queue, id, type(error).__name__)
255
+ raise
256
+ self.logger.debug('Direct publication confirmed: queue=%s message_id=%s', subscription.queue, id)
257
+ return id
258
+
259
+ def request(
260
+ self,
261
+ body: AnyValue,
262
+ parameters: AnyValue,
263
+ timeout: float = 5,
264
+ *,
265
+ priority: Optional[int] = None,
266
+ ) -> AnyValue:
267
+ subscription = Subscription.parse(parameters)
268
+ if priority is None:
269
+ priority = subscription.priority
270
+ subscription.validate_priority(priority)
271
+ self.connected()
272
+ queue = self.queue(subscription.queue)
273
+ self.logger.debug('Delegating RPC to Queue: queue=%s timeout=%s priority=%s', subscription.queue, timeout, priority)
274
+ try:
275
+ if priority is not None:
276
+ return queue.call(
277
+ body,
278
+ timeout=timeout,
279
+ priority=priority,
280
+ )
281
+ return queue.call(
282
+ body,
283
+ timeout=timeout,
284
+ )
285
+ finally:
286
+ try:
287
+ if queue.channel.is_open:
288
+ queue.channel.close()
289
+ self.logger.debug('RPC delegated channel cleanup completed: queue=%s', subscription.queue)
290
+ except Exception as error:
291
+ self.logger.error('RPC delegated channel cleanup failed: queue=%s error_type=%s', subscription.queue, type(error).__name__)
292
+ raise
293
+
294
+ def exchange(self, exchange: str) -> Exchange:
295
+ self.logger.debug('Creating Exchange: exchange=%s', exchange)
296
+ return Exchange(
297
+ self.connected(),
298
+ self.conf.encode,
299
+ exchange,
300
+ decode=self.conf.decode,
301
+ rpc_parameters=self.parameters,
302
+ )
303
+
304
+ def queue(self, queue: str) -> Queue:
305
+ self.logger.debug('Creating Queue: queue=%s', queue)
306
+ return Queue(
307
+ self.connected(),
308
+ self.conf.encode,
309
+ self.conf.decode,
310
+ queue,
311
+ rpc_parameters=self.parameters,
312
+ )
313
+
314
+ def stream(self, queue: str) -> Stream:
315
+ self.logger.debug('Creating Stream: queue=%s', queue)
316
+ return Stream(self.connected(), self.conf.encode, self.conf.decode, queue)
317
+
318
+ def consumer(
319
+ self,
320
+ handler: Optional[EventHandler] = None,
321
+ qos: int = 1,
322
+ offset: Optional[int] = None,
323
+ ) -> Consumer:
324
+ self.logger.debug('Creating Consumer: qos=%s offset=%s', qos, offset)
325
+ return Consumer(
326
+ self.connected(),
327
+ self.conf.decode,
328
+ handler,
329
+ qos=qos,
330
+ offset=offset,
331
+ encode=self.conf.encode,
332
+ )
333
+
334
+ def close(self):
335
+ if self.connection and self.connection.is_open:
336
+ with self.observe('RabbitMQ connection close'):
337
+ self.connection.close()
338
+ self.connection = None
339
+ self.publisher = None
340
+ return
341
+
342
+ def create_exchange(
343
+ self,
344
+ name: str,
345
+ type: ExchangeType,
346
+ durable: bool = True,
347
+ autodelete: bool = False,
348
+ alter: Optional[Union[str, Exchange]] = None,
349
+ ):
350
+ args: Dict[str, AnyValue] = {}
351
+ if alter:
352
+ args['alternate-exchange'] = str(alter)
353
+ self.logger.debug('Exchange declaration: exchange=%s type=%s durable=%s auto_delete=%s alternate_exchange=%s', name, type, durable, autodelete, str(alter) if alter else None)
354
+ with self.observe('Exchange declaration: exchange=%s', name):
355
+ channel = self.connected().channel()
356
+ try:
357
+ channel.exchange_declare(
358
+ name,
359
+ str(type),
360
+ durable=durable,
361
+ auto_delete=autodelete,
362
+ arguments=args
363
+ )
364
+ finally:
365
+ if channel.is_open:
366
+ channel.close()
367
+ return
368
+
369
+ def delete_exchange(
370
+ self,
371
+ name: str,
372
+ ):
373
+ with self.observe('Exchange deletion: exchange=%s', name):
374
+ channel = self.connected().channel()
375
+ channel.exchange_delete(name)
376
+ return
377
+
378
+ def bind_exchange_to_exchange(
379
+ self,
380
+ src: Union[str, Exchange],
381
+ to: Union[str, Exchange],
382
+ event: Optional[str] = None,
383
+ parameters: Optional[Parameters] = None,
384
+ ):
385
+ with self.observe('Exchange binding: src=%s to=%s routing_key=%s', str(src), str(to), event):
386
+ channel = self.connected().channel()
387
+ channel.exchange_bind(
388
+ str(src),
389
+ str(to),
390
+ routing_key=event if event else '',
391
+ arguments=dict(parameters) if parameters is not None else None
392
+ )
393
+ return
394
+
395
+ def unbind_exchange_to_exchange(
396
+ self,
397
+ src: Union[str, Exchange],
398
+ to: Union[str, Exchange],
399
+ event: Optional[str] = None,
400
+ parameters: Optional[Parameters] = None,
401
+ ):
402
+ with self.observe('Exchange unbinding: src=%s to=%s routing_key=%s', str(src), str(to), event):
403
+ channel = self.connected().channel()
404
+ channel.exchange_unbind(
405
+ str(src),
406
+ str(to),
407
+ routing_key=event if event else '',
408
+ arguments=dict(parameters) if parameters is not None else None,
409
+ )
410
+ return
411
+
412
+ def create_queue(
413
+ self,
414
+ name: str,
415
+ expires: Optional[int] = None,
416
+ ttl: Optional[int] = None,
417
+ limit: Optional[int] = None,
418
+ size: Optional[int] = None,
419
+ maxPriority: Optional[int] = None,
420
+ durable: bool = True,
421
+ autodelete: bool = False,
422
+ errorQueue: Optional[Union[str, Queue]] = None,
423
+ errorExchange: Optional[Union[str, Exchange]] = None,
424
+ ):
425
+ args: Dict[str, AnyValue] = {}
426
+ if errorQueue:
427
+ args['x-dead-letter-exchange'] = ''
428
+ args['x-dead-letter-routing-key'] = str(errorQueue)
429
+ if errorExchange:
430
+ args['x-dead-letter-exchange'] = str(errorExchange)
431
+ if expires:
432
+ args['x-expires'] = expires
433
+ if ttl:
434
+ args['x-message-ttl'] = ttl
435
+ if limit:
436
+ args['x-max-length'] = limit
437
+ if size:
438
+ args['x-max-length-bytes'] = size
439
+ if maxPriority:
440
+ args['x-max-priority'] = maxPriority
441
+ self.logger.debug('Queue declaration options: queue=%s durable=%s auto_delete=%s expires=%s ttl=%s limit=%s size=%s max_priority=%s error_queue=%s error_exchange=%s', name, durable, autodelete, expires, ttl, limit, size, maxPriority, str(errorQueue) if errorQueue else None, str(errorExchange) if errorExchange else None)
442
+ with self.observe('Queue declaration: queue=%s', name):
443
+ channel = self.connected().channel()
444
+ channel.queue_declare(
445
+ name,
446
+ durable=durable,
447
+ auto_delete=autodelete,
448
+ arguments=args
449
+ )
450
+ return
451
+
452
+ def delete_queue(
453
+ self,
454
+ queue: str,
455
+ ):
456
+ with self.observe('Queue deletion: queue=%s', queue):
457
+ channel = self.connected().channel()
458
+ channel.queue_delete(queue)
459
+ return
460
+
461
+ def bind_exchange_to_queue(
462
+ self,
463
+ src: Union[str, Exchange],
464
+ to: Union[str, Queue],
465
+ event: Optional[str] = None,
466
+ parameters: Optional[Parameters] = None,
467
+ ):
468
+ with self.observe('Queue binding: exchange=%s queue=%s routing_key=%s', str(src), str(to), event):
469
+ channel = self.connected().channel()
470
+ channel.queue_bind(
471
+ str(to),
472
+ str(src),
473
+ routing_key=event if event else '',
474
+ arguments=dict(parameters) if parameters is not None else None
475
+ )
476
+ return
477
+
478
+ def unbind_exchange_to_queue(
479
+ self,
480
+ src: Union[str, Exchange],
481
+ to: Union[str, Queue],
482
+ event: Optional[str] = None,
483
+ parameters: Optional[Parameters] = None,
484
+ ):
485
+ with self.observe('Queue unbinding: exchange=%s queue=%s routing_key=%s', str(src), str(to), event):
486
+ channel = self.connected().channel()
487
+ channel.queue_unbind(
488
+ str(to),
489
+ str(src),
490
+ routing_key=event if event else '',
491
+ arguments=dict(parameters) if parameters is not None else None,
492
+ )
493
+ return
494
+
495
+ def create_stream(
496
+ self,
497
+ name: str,
498
+ size: Optional[int] = None,
499
+ durable: bool = True,
500
+ autodelete: bool = False,
501
+ ):
502
+ args: Dict[str, AnyValue] = {
503
+ 'x-queue-type': 'stream',
504
+ }
505
+ if size:
506
+ args['x-max-length-bytes'] = size
507
+ self.logger.debug('Stream declaration options: queue=%s durable=%s auto_delete=%s size=%s', name, durable, autodelete, size)
508
+ with self.observe('Stream declaration: queue=%s', name):
509
+ channel = self.connected().channel()
510
+ channel.queue_declare(
511
+ name,
512
+ durable=durable,
513
+ auto_delete=autodelete,
514
+ arguments=args
515
+ )
516
+ return
517
+
518
+ def delete_stream(
519
+ self,
520
+ queue: str,
521
+ ):
522
+ with self.observe('Stream deletion: queue=%s', queue):
523
+ channel = self.connected().channel()
524
+ channel.queue_delete(queue)
525
+ return
526
+
527
+
528
+ class All(Parameters):
529
+ """All Bind Parameters Event Broker for RabbitMQ"""
530
+ def __init__(self, **kwargs):
531
+ headers = {
532
+ 'x-match': 'all-with-x'
533
+ }
534
+ headers.update(kwargs)
535
+ super().__init__(**headers)
536
+ return
537
+
538
+
539
+ class Any(Parameters):
540
+ """Any Bind Parameters Event Broker for RabbitMQ"""
541
+ def __init__(self, **kwargs):
542
+ headers = {
543
+ 'x-match': 'any-with-x'
544
+ }
545
+ headers.update(kwargs)
546
+ super().__init__(**headers)
547
+ return