DefStream-RabbitMQ 0.1.4__9-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,477 @@
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
+
38
+ from typing import (
39
+ Any as AnyValue,
40
+ Iterator,
41
+ Union,
42
+ Optional,
43
+ )
44
+
45
+ __all__ = (
46
+ 'Connection',
47
+ 'ExchangeType',
48
+ 'Parameters',
49
+ 'All',
50
+ 'Any',
51
+ )
52
+
53
+
54
+ class ExchangeType(str, Enum):
55
+ Direct = 'direct'
56
+ FanOut = 'fanout'
57
+ Topic = 'topic'
58
+ Header = 'headers'
59
+ def __str__(self): return str(self.value)
60
+
61
+
62
+ class Parameters(Mapping):
63
+ """Bind Parameters Event Broker for RabbitMQ"""
64
+ def __init__(self, **kwargs):
65
+ self.args = kwargs
66
+ return
67
+
68
+ def __iter__(self) -> Iterator:
69
+ return self.args.__iter__()
70
+
71
+ def __reversed__(self) -> Iterator:
72
+ return self.args.__reversed__()
73
+
74
+ def __len__(self) -> int:
75
+ return self.args.__len__()
76
+
77
+ def __getitem__(
78
+ self,
79
+ key: AnyValue,
80
+ ) -> AnyValue:
81
+ return self.args.__getitem__(key)
82
+
83
+ def __contains__(self, key: object) -> bool:
84
+ return self.args.__contains__(key)
85
+
86
+ def __eq__(self, other) -> bool:
87
+ return eq(self.args, other)
88
+
89
+ def __ne__(self, other) -> bool:
90
+ return ne(self.args, other)
91
+
92
+ def keys(self) -> Iterator:
93
+ return self.args.keys()
94
+
95
+ def items(self):
96
+ return self.args.items()
97
+
98
+ def values(self):
99
+ return self.args.values()
100
+
101
+
102
+ class Connection(
103
+ BaseConnection,
104
+ GetExchange,
105
+ GetQueue,
106
+ GetStream,
107
+ GetConsumer,
108
+ Declarable,
109
+ PrioritySupport,
110
+ ):
111
+ """Connection of Event Broker for RabbitMQ"""
112
+ def __init__(self, conf: Configuration):
113
+ self.conf = conf
114
+ self.parameters = ConnectionParameters(
115
+ host=self.conf.host,
116
+ port=self.conf.port,
117
+ credentials=PlainCredentials(self.conf.username, self.conf.password),
118
+ virtual_host=self.conf.vhost,
119
+ ssl_options=self.conf.ssl,
120
+ blocked_connection_timeout=self.conf.timeout,
121
+ heartbeat=self.conf.heartbeat
122
+ )
123
+ self.connection = None
124
+ self.publisher = None
125
+ return
126
+
127
+ def __del__(self):
128
+ self.close()
129
+ return
130
+
131
+ def connect(self):
132
+ if self.connection and self.connection.is_open:
133
+ return
134
+ self.connection = BlockingConnection(parameters=self.parameters)
135
+ return
136
+
137
+ def connected(self):
138
+ if self.connection is None or not self.connection.is_open:
139
+ raise RuntimeError('Connect the RabbitMQ connection before use')
140
+ return self.connection
141
+
142
+ def declare(
143
+ self,
144
+ parameters: AnyValue,
145
+ ) -> None:
146
+ subscription = Subscription.parse(parameters)
147
+ channel = self.connected().channel()
148
+ try:
149
+ arguments = {}
150
+ if subscription.error is not None:
151
+ channel.queue_declare(
152
+ subscription.error,
153
+ durable=True,
154
+ )
155
+ arguments = {
156
+ 'x-dead-letter-exchange': '',
157
+ 'x-dead-letter-routing-key': subscription.error,
158
+ }
159
+ if subscription.max_priority is not None:
160
+ arguments['x-max-priority'] = subscription.max_priority
161
+ channel.queue_declare(
162
+ subscription.queue,
163
+ durable=True,
164
+ arguments=arguments,
165
+ )
166
+ finally:
167
+ if channel.is_open:
168
+ channel.close()
169
+ return
170
+
171
+ def priority_parameters(
172
+ self,
173
+ parameters: AnyValue,
174
+ ) -> Subscription:
175
+ """작업 기본값을 검증하고 선언·발행에 사용할 구독 설정을 반환한다."""
176
+ return Subscription.parse(parameters)
177
+
178
+ def emit(
179
+ self,
180
+ body: AnyValue,
181
+ parameters: AnyValue,
182
+ *,
183
+ priority: Optional[int] = None,
184
+ ) -> str:
185
+ subscription = Subscription.parse(parameters)
186
+ if priority is None:
187
+ priority = subscription.priority
188
+ subscription.validate_priority(priority)
189
+ connection = self.connected()
190
+ channel = self.publisher
191
+ if channel is None or not channel.is_open:
192
+ channel = connection.channel()
193
+ try:
194
+ channel.confirm_delivery()
195
+ except Exception:
196
+ if channel.is_open:
197
+ channel.close()
198
+ raise
199
+ self.publisher = channel
200
+ id = uuid4().hex
201
+ channel.basic_publish(
202
+ exchange='',
203
+ routing_key=subscription.queue,
204
+ body=self.conf.encode(body),
205
+ properties=BasicProperties(
206
+ message_id=id,
207
+ headers={},
208
+ content_type=self.conf.encode.format,
209
+ content_encoding=self.conf.encode.charset,
210
+ delivery_mode=2,
211
+ priority=priority,
212
+ ),
213
+ mandatory=True,
214
+ )
215
+ return id
216
+
217
+ def request(
218
+ self,
219
+ body: AnyValue,
220
+ parameters: AnyValue,
221
+ timeout: float = 5,
222
+ *,
223
+ priority: Optional[int] = None,
224
+ ) -> AnyValue:
225
+ subscription = Subscription.parse(parameters)
226
+ if priority is None:
227
+ priority = subscription.priority
228
+ subscription.validate_priority(priority)
229
+ self.connected()
230
+ queue = self.queue(subscription.queue)
231
+ try:
232
+ if priority is not None:
233
+ return queue.call(
234
+ body,
235
+ timeout=timeout,
236
+ priority=priority,
237
+ )
238
+ return queue.call(
239
+ body,
240
+ timeout=timeout,
241
+ )
242
+ finally:
243
+ if queue.channel.is_open:
244
+ queue.channel.close()
245
+
246
+ def exchange(self, exchange: str) -> Exchange:
247
+ return Exchange(
248
+ self.connection,
249
+ self.conf.encode,
250
+ exchange,
251
+ decode=self.conf.decode,
252
+ rpc_parameters=self.parameters,
253
+ )
254
+
255
+ def queue(self, queue: str) -> Queue:
256
+ return Queue(
257
+ self.connection,
258
+ self.conf.encode,
259
+ self.conf.decode,
260
+ queue,
261
+ rpc_parameters=self.parameters,
262
+ )
263
+
264
+ def stream(self, queue: str) -> Stream:
265
+ return Stream(self.connection, self.conf.encode, self.conf.decode, queue)
266
+
267
+ def consumer(
268
+ self,
269
+ handler: Optional[EventHandler] = None,
270
+ qos: int = 1,
271
+ offset: int = None,
272
+ ) -> Consumer:
273
+ return Consumer(
274
+ self.connection,
275
+ self.conf.decode,
276
+ handler,
277
+ qos=qos,
278
+ offset=offset,
279
+ encode=self.conf.encode,
280
+ )
281
+
282
+ def close(self):
283
+ if self.connection and self.connection.is_open:
284
+ self.connection.close()
285
+ self.connection = None
286
+ self.publisher = None
287
+ return
288
+
289
+ def create_exchange(
290
+ self,
291
+ name: str,
292
+ type: ExchangeType,
293
+ durable: bool = True,
294
+ autodelete: bool = False,
295
+ alter: Union[str, Exchange] = None,
296
+ ):
297
+ args = {}
298
+ if alter:
299
+ args['alternate-exchange'] = str(alter)
300
+ channel = self.connection.channel()
301
+ channel.exchange_declare(
302
+ name,
303
+ str(type),
304
+ durable=durable,
305
+ auto_delete=autodelete,
306
+ arguments=args
307
+ )
308
+ return
309
+
310
+ def delete_exchange(
311
+ self,
312
+ name: str,
313
+ ):
314
+ channel = self.connection.channel()
315
+ channel.exchange_delete(name)
316
+ return
317
+
318
+ def bind_exchange_to_exchange(
319
+ self,
320
+ src: Union[str, Exchange],
321
+ to: Union[str, Exchange],
322
+ event: str = None,
323
+ parameters: Parameters = None,
324
+ ):
325
+ channel = self.connection.channel()
326
+ channel.exchange_bind(
327
+ str(src),
328
+ str(to),
329
+ routing_key=event if event else '',
330
+ arguments=parameters
331
+ )
332
+ return
333
+
334
+ def unbind_exchange_to_exchange(
335
+ self,
336
+ src: Union[str, Exchange],
337
+ to: Union[str, Exchange],
338
+ event: str = None,
339
+ parameters: Parameters = None,
340
+ ):
341
+ channel = self.connection.channel()
342
+ channel.exchange_unbind(
343
+ str(src),
344
+ str(to),
345
+ routing_key=event if event else '',
346
+ arguments=parameters,
347
+ )
348
+ return
349
+
350
+ def create_queue(
351
+ self,
352
+ name: str,
353
+ expires: int = None,
354
+ ttl: int = None,
355
+ limit: int = None,
356
+ size: int = None,
357
+ maxPriority: int = None,
358
+ durable: bool = True,
359
+ autodelete: bool = False,
360
+ errorQueue: Union[str, Queue] = None,
361
+ errorExchange: Union[str, Exchange] = None,
362
+ ):
363
+ args = {}
364
+ if errorQueue:
365
+ args['x-dead-letter-exchange'] = ''
366
+ args['x-dead-letter-routing-key'] = str(errorQueue)
367
+ if errorExchange:
368
+ args['x-dead-letter-exchange'] = str(errorExchange)
369
+ if expires:
370
+ args['x-expires'] = expires
371
+ if ttl:
372
+ args['x-message-ttl'] = ttl
373
+ if limit:
374
+ args['x-max-length'] = limit
375
+ if size:
376
+ args['x-max-length-bytes'] = size
377
+ if maxPriority:
378
+ args['x-max-priority'] = maxPriority
379
+ channel = self.connection.channel()
380
+ channel.queue_declare(
381
+ name,
382
+ durable=durable,
383
+ auto_delete=autodelete,
384
+ arguments=args
385
+ )
386
+ return
387
+
388
+ def delete_queue(
389
+ self,
390
+ queue: str,
391
+ ):
392
+ channel = self.connection.channel()
393
+ channel.queue_delete(queue)
394
+ return
395
+
396
+ def bind_exchange_to_queue(
397
+ self,
398
+ src: Union[str, Exchange],
399
+ to: Union[str, Queue],
400
+ event: str = None,
401
+ parameters: Parameters = None,
402
+ ):
403
+ channel = self.connection.channel()
404
+ channel.queue_bind(
405
+ str(to),
406
+ str(src),
407
+ routing_key=event if event else '',
408
+ arguments=parameters
409
+ )
410
+ return
411
+
412
+ def unbind_exchange_to_queue(
413
+ self,
414
+ src: Union[str, Exchange],
415
+ to: Union[str, Queue],
416
+ event: str = None,
417
+ parameters: Parameters = None,
418
+ ):
419
+ channel = self.connection.channel()
420
+ channel.queue_unbind(
421
+ str(to),
422
+ str(src),
423
+ routing_key=event if event else '',
424
+ arguments=parameters,
425
+ )
426
+ return
427
+
428
+ def create_stream(
429
+ self,
430
+ name: str,
431
+ size: int = None,
432
+ durable: bool = True,
433
+ autodelete: bool = False,
434
+ ):
435
+ channel = self.connection.channel()
436
+ args = {
437
+ 'x-queue-type': 'stream',
438
+ }
439
+ if size:
440
+ args['x-max-length-bytes'] = size
441
+ channel.queue_declare(
442
+ name,
443
+ durable=durable,
444
+ auto_delete=autodelete,
445
+ arguments=args
446
+ )
447
+ return
448
+
449
+ def delete_stream(
450
+ self,
451
+ queue: str,
452
+ ):
453
+ channel = self.connection.channel()
454
+ channel.queue_delete(queue)
455
+ return
456
+
457
+
458
+ class All(Parameters):
459
+ """All Bind Parameters Event Broker for RabbitMQ"""
460
+ def __init__(self, **kwargs):
461
+ headers = {
462
+ 'x-match': 'all-with-x'
463
+ }
464
+ headers.update(kwargs)
465
+ super().__init__(**headers)
466
+ return
467
+
468
+
469
+ class Any(Parameters):
470
+ """Any Bind Parameters Event Broker for RabbitMQ"""
471
+ def __init__(self, **kwargs):
472
+ headers = {
473
+ 'x-match': 'any-with-x'
474
+ }
475
+ headers.update(kwargs)
476
+ super().__init__(**headers)
477
+ return