DefStream-RabbitMQ 0.1.5__16-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.

Potentially problematic release.


This version of DefStream-RabbitMQ might be problematic. Click here for more details.

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