DefStream 0.1.20__81-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 +549 -0
  8. DefStream/Broker/Implements/RabbitMQ/Consumer.py +360 -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 +45 -0
  27. DefStream/Broker/__init__.py +53 -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 +371 -0
  61. DefStream/Worker/Message.py +180 -0
  62. DefStream/Worker/Pool.py +245 -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 +421 -0
  67. DefStream/Worker/__init__.py +47 -0
  68. DefStream/__init__.py +0 -0
  69. defstream-0.1.20.dist-info/METADATA +92 -0
  70. defstream-0.1.20.dist-info/RECORD +73 -0
  71. defstream-0.1.20.dist-info/WHEEL +6 -0
  72. defstream-0.1.20.dist-info/licenses/LICENSE +674 -0
  73. defstream-0.1.20.dist-info/top_level.txt +1 -0
@@ -0,0 +1,549 @@
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('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 = 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
+ if subscription.timeout is not None:
194
+ arguments['x-consumer-timeout'] = subscription.timeout
195
+ channel.queue_declare(
196
+ subscription.queue,
197
+ durable=True,
198
+ arguments=arguments,
199
+ )
200
+ finally:
201
+ if channel.is_open:
202
+ channel.close()
203
+ return
204
+
205
+ def priority_parameters(
206
+ self,
207
+ parameters: AnyValue,
208
+ ) -> Subscription:
209
+ """작업 기본값을 검증하고 선언·발행에 사용할 구독 설정을 반환한다."""
210
+ return Subscription.parse(parameters)
211
+
212
+ def emit(
213
+ self,
214
+ body: AnyValue,
215
+ parameters: AnyValue,
216
+ *,
217
+ priority: Optional[int] = None,
218
+ ) -> str:
219
+ subscription = Subscription.parse(parameters)
220
+ if priority is None:
221
+ priority = subscription.priority
222
+ subscription.validate_priority(priority)
223
+ connection = self.connected()
224
+ channel = self.publisher
225
+ if channel is None or not channel.is_open:
226
+ try:
227
+ channel = connection.channel()
228
+ channel.confirm_delivery()
229
+ self.logger.debug('Publisher channel created: publisher_confirm=True')
230
+ except Exception as error:
231
+ self.logger.error('Publisher channel creation failed: queue=%s error_type=%s', subscription.queue, type(error).__name__)
232
+ if channel is not None and channel.is_open:
233
+ channel.close()
234
+ raise
235
+ self.publisher = channel
236
+ else:
237
+ self.logger.debug('Reusing publisher channel: publisher_confirm=True')
238
+ id = uuid4().hex
239
+ self.logger.debug('Publishing directly: queue=%s message_id=%s priority=%s publisher_confirm=True', subscription.queue, id, priority)
240
+ try:
241
+ channel.basic_publish(
242
+ exchange='',
243
+ routing_key=subscription.queue,
244
+ body=self.conf.encode(body),
245
+ properties=BasicProperties(
246
+ message_id=id,
247
+ headers={},
248
+ content_type=self.conf.encode.format,
249
+ content_encoding=self.conf.encode.charset,
250
+ delivery_mode=2,
251
+ priority=priority,
252
+ ),
253
+ mandatory=True,
254
+ )
255
+ except Exception as error:
256
+ self.logger.error('Direct publication failed: queue=%s message_id=%s error_type=%s', subscription.queue, id, type(error).__name__)
257
+ raise
258
+ self.logger.debug('Direct publication confirmed: queue=%s message_id=%s', subscription.queue, id)
259
+ return id
260
+
261
+ def request(
262
+ self,
263
+ body: AnyValue,
264
+ parameters: AnyValue,
265
+ timeout: float = 5,
266
+ *,
267
+ priority: Optional[int] = None,
268
+ ) -> AnyValue:
269
+ subscription = Subscription.parse(parameters)
270
+ if priority is None:
271
+ priority = subscription.priority
272
+ subscription.validate_priority(priority)
273
+ self.connected()
274
+ queue = self.queue(subscription.queue)
275
+ self.logger.debug('Delegating RPC to Queue: queue=%s timeout=%s priority=%s', subscription.queue, timeout, priority)
276
+ try:
277
+ if priority is not None:
278
+ return queue.call(
279
+ body,
280
+ timeout=timeout,
281
+ priority=priority,
282
+ )
283
+ return queue.call(
284
+ body,
285
+ timeout=timeout,
286
+ )
287
+ finally:
288
+ try:
289
+ if queue.channel.is_open:
290
+ queue.channel.close()
291
+ self.logger.debug('RPC delegated channel cleanup completed: queue=%s', subscription.queue)
292
+ except Exception as error:
293
+ self.logger.error('RPC delegated channel cleanup failed: queue=%s error_type=%s', subscription.queue, type(error).__name__)
294
+ raise
295
+
296
+ def exchange(self, exchange: str) -> Exchange:
297
+ self.logger.debug('Creating Exchange: exchange=%s', exchange)
298
+ return Exchange(
299
+ self.connected(),
300
+ self.conf.encode,
301
+ exchange,
302
+ decode=self.conf.decode,
303
+ rpc_parameters=self.parameters,
304
+ )
305
+
306
+ def queue(self, queue: str) -> Queue:
307
+ self.logger.debug('Creating Queue: queue=%s', queue)
308
+ return Queue(
309
+ self.connected(),
310
+ self.conf.encode,
311
+ self.conf.decode,
312
+ queue,
313
+ rpc_parameters=self.parameters,
314
+ )
315
+
316
+ def stream(self, queue: str) -> Stream:
317
+ self.logger.debug('Creating Stream: queue=%s', queue)
318
+ return Stream(self.connected(), self.conf.encode, self.conf.decode, queue)
319
+
320
+ def consumer(
321
+ self,
322
+ handler: Optional[EventHandler] = None,
323
+ qos: int = 1,
324
+ offset: Optional[int] = None,
325
+ ) -> Consumer:
326
+ self.logger.debug('Creating Consumer: qos=%s offset=%s', qos, offset)
327
+ return Consumer(
328
+ self.connected(),
329
+ self.conf.decode,
330
+ handler,
331
+ qos=qos,
332
+ offset=offset,
333
+ encode=self.conf.encode,
334
+ )
335
+
336
+ def close(self):
337
+ if self.connection and self.connection.is_open:
338
+ with self.observe('RabbitMQ connection close'):
339
+ self.connection.close()
340
+ self.connection = None
341
+ self.publisher = None
342
+ return
343
+
344
+ def create_exchange(
345
+ self,
346
+ name: str,
347
+ type: ExchangeType,
348
+ durable: bool = True,
349
+ autodelete: bool = False,
350
+ alter: Optional[Union[str, Exchange]] = None,
351
+ ):
352
+ args: Dict[str, AnyValue] = {}
353
+ if alter:
354
+ args['alternate-exchange'] = str(alter)
355
+ 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)
356
+ with self.observe('Exchange declaration: exchange=%s', name):
357
+ channel = self.connected().channel()
358
+ try:
359
+ channel.exchange_declare(
360
+ name,
361
+ str(type),
362
+ durable=durable,
363
+ auto_delete=autodelete,
364
+ arguments=args
365
+ )
366
+ finally:
367
+ if channel.is_open:
368
+ channel.close()
369
+ return
370
+
371
+ def delete_exchange(
372
+ self,
373
+ name: str,
374
+ ):
375
+ with self.observe('Exchange deletion: exchange=%s', name):
376
+ channel = self.connected().channel()
377
+ channel.exchange_delete(name)
378
+ return
379
+
380
+ def bind_exchange_to_exchange(
381
+ self,
382
+ src: Union[str, Exchange],
383
+ to: Union[str, Exchange],
384
+ event: Optional[str] = None,
385
+ parameters: Optional[Parameters] = None,
386
+ ):
387
+ with self.observe('Exchange binding: src=%s to=%s routing_key=%s', str(src), str(to), event):
388
+ channel = self.connected().channel()
389
+ channel.exchange_bind(
390
+ str(src),
391
+ str(to),
392
+ routing_key=event if event else '',
393
+ arguments=dict(parameters) if parameters is not None else None
394
+ )
395
+ return
396
+
397
+ def unbind_exchange_to_exchange(
398
+ self,
399
+ src: Union[str, Exchange],
400
+ to: Union[str, Exchange],
401
+ event: Optional[str] = None,
402
+ parameters: Optional[Parameters] = None,
403
+ ):
404
+ with self.observe('Exchange unbinding: src=%s to=%s routing_key=%s', str(src), str(to), event):
405
+ channel = self.connected().channel()
406
+ channel.exchange_unbind(
407
+ str(src),
408
+ str(to),
409
+ routing_key=event if event else '',
410
+ arguments=dict(parameters) if parameters is not None else None,
411
+ )
412
+ return
413
+
414
+ def create_queue(
415
+ self,
416
+ name: str,
417
+ expires: Optional[int] = None,
418
+ ttl: Optional[int] = None,
419
+ limit: Optional[int] = None,
420
+ size: Optional[int] = None,
421
+ maxPriority: Optional[int] = None,
422
+ durable: bool = True,
423
+ autodelete: bool = False,
424
+ errorQueue: Optional[Union[str, Queue]] = None,
425
+ errorExchange: Optional[Union[str, Exchange]] = None,
426
+ ):
427
+ args: Dict[str, AnyValue] = {}
428
+ if errorQueue:
429
+ args['x-dead-letter-exchange'] = ''
430
+ args['x-dead-letter-routing-key'] = str(errorQueue)
431
+ if errorExchange:
432
+ args['x-dead-letter-exchange'] = str(errorExchange)
433
+ if expires:
434
+ args['x-expires'] = expires
435
+ if ttl:
436
+ args['x-message-ttl'] = ttl
437
+ if limit:
438
+ args['x-max-length'] = limit
439
+ if size:
440
+ args['x-max-length-bytes'] = size
441
+ if maxPriority:
442
+ args['x-max-priority'] = maxPriority
443
+ 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)
444
+ with self.observe('Queue declaration: queue=%s', name):
445
+ channel = self.connected().channel()
446
+ channel.queue_declare(
447
+ name,
448
+ durable=durable,
449
+ auto_delete=autodelete,
450
+ arguments=args
451
+ )
452
+ return
453
+
454
+ def delete_queue(
455
+ self,
456
+ queue: str,
457
+ ):
458
+ with self.observe('Queue deletion: queue=%s', queue):
459
+ channel = self.connected().channel()
460
+ channel.queue_delete(queue)
461
+ return
462
+
463
+ def bind_exchange_to_queue(
464
+ self,
465
+ src: Union[str, Exchange],
466
+ to: Union[str, Queue],
467
+ event: Optional[str] = None,
468
+ parameters: Optional[Parameters] = None,
469
+ ):
470
+ with self.observe('Queue binding: exchange=%s queue=%s routing_key=%s', str(src), str(to), event):
471
+ channel = self.connected().channel()
472
+ channel.queue_bind(
473
+ str(to),
474
+ str(src),
475
+ routing_key=event if event else '',
476
+ arguments=dict(parameters) if parameters is not None else None
477
+ )
478
+ return
479
+
480
+ def unbind_exchange_to_queue(
481
+ self,
482
+ src: Union[str, Exchange],
483
+ to: Union[str, Queue],
484
+ event: Optional[str] = None,
485
+ parameters: Optional[Parameters] = None,
486
+ ):
487
+ with self.observe('Queue unbinding: exchange=%s queue=%s routing_key=%s', str(src), str(to), event):
488
+ channel = self.connected().channel()
489
+ channel.queue_unbind(
490
+ str(to),
491
+ str(src),
492
+ routing_key=event if event else '',
493
+ arguments=dict(parameters) if parameters is not None else None,
494
+ )
495
+ return
496
+
497
+ def create_stream(
498
+ self,
499
+ name: str,
500
+ size: Optional[int] = None,
501
+ durable: bool = True,
502
+ autodelete: bool = False,
503
+ ):
504
+ args: Dict[str, AnyValue] = {
505
+ 'x-queue-type': 'stream',
506
+ }
507
+ if size:
508
+ args['x-max-length-bytes'] = size
509
+ self.logger.debug('Stream declaration options: queue=%s durable=%s auto_delete=%s size=%s', name, durable, autodelete, size)
510
+ with self.observe('Stream declaration: queue=%s', name):
511
+ channel = self.connected().channel()
512
+ channel.queue_declare(
513
+ name,
514
+ durable=durable,
515
+ auto_delete=autodelete,
516
+ arguments=args
517
+ )
518
+ return
519
+
520
+ def delete_stream(
521
+ self,
522
+ queue: str,
523
+ ):
524
+ with self.observe('Stream deletion: queue=%s', queue):
525
+ channel = self.connected().channel()
526
+ channel.queue_delete(queue)
527
+ return
528
+
529
+
530
+ class All(Parameters):
531
+ """All Bind Parameters Event Broker for RabbitMQ"""
532
+ def __init__(self, **kwargs):
533
+ headers = {
534
+ 'x-match': 'all-with-x'
535
+ }
536
+ headers.update(kwargs)
537
+ super().__init__(**headers)
538
+ return
539
+
540
+
541
+ class Any(Parameters):
542
+ """Any Bind Parameters Event Broker for RabbitMQ"""
543
+ def __init__(self, **kwargs):
544
+ headers = {
545
+ 'x-match': 'any-with-x'
546
+ }
547
+ headers.update(kwargs)
548
+ super().__init__(**headers)
549
+ return