DefStream-RabbitMQ 0.1.1.2__tar.gz → 0.1.1.3__tar.gz

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 (35) hide show
  1. defstream_rabbitmq-0.1.1.3/DefStream_RabbitMQ.egg-info/PKG-INFO +239 -0
  2. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/DefStream_RabbitMQ.egg-info/SOURCES.txt +1 -0
  3. defstream_rabbitmq-0.1.1.3/PKG-INFO +239 -0
  4. defstream_rabbitmq-0.1.1.3/README.en.md +210 -0
  5. defstream_rabbitmq-0.1.1.3/README.md +208 -0
  6. defstream_rabbitmq-0.1.1.2/DefStream_RabbitMQ.egg-info/PKG-INFO +0 -191
  7. defstream_rabbitmq-0.1.1.2/PKG-INFO +0 -191
  8. defstream_rabbitmq-0.1.1.2/README.md +0 -160
  9. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/.github/workflows/ci.yml +0 -0
  10. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/.gitignore +0 -0
  11. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/DefStream_RabbitMQ.egg-info/dependency_links.txt +0 -0
  12. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/DefStream_RabbitMQ.egg-info/requires.txt +0 -0
  13. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/DefStream_RabbitMQ.egg-info/top_level.txt +0 -0
  14. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/LICENSE +0 -0
  15. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/sample/Sample.RPC.py +0 -0
  16. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/sample/Sample.Stream.py +0 -0
  17. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/sample/Sample.py +0 -0
  18. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/setup.cfg +0 -0
  19. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/setup.py +0 -0
  20. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Configuration.py +0 -0
  21. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Connection.py +0 -0
  22. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Consumer.py +0 -0
  23. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Event.py +0 -0
  24. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Exchange.py +0 -0
  25. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Policies.py +0 -0
  26. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Queue.py +0 -0
  27. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Serializer.py +0 -0
  28. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Stream.py +0 -0
  29. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/Subscription.py +0 -0
  30. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/src/__init__.py +0 -0
  31. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/test/test_broker_methods.py +0 -0
  32. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/test/test_rabbitmq_integration.py +0 -0
  33. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/test/test_rabbitmq_worker.py +0 -0
  34. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/test/test_rpc.py +0 -0
  35. {defstream_rabbitmq-0.1.1.2 → defstream_rabbitmq-0.1.1.3}/test/test_rpc_integration.py +0 -0
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: DefStream-RabbitMQ
3
+ Version: 0.1.1.3
4
+ Summary: RabbitMQ broker adapter for DefStream
5
+ Home-page: https://github.com/yong5eon/DefStream-RabbitMQ
6
+ Author: Heo Yongseon
7
+ Project-URL: Source, https://github.com/yong5eon/DefStream-RabbitMQ
8
+ Project-URL: Issues, https://github.com/yong5eon/DefStream-RabbitMQ/issues
9
+ Project-URL: Releases, https://github.com/yong5eon/DefStream-RabbitMQ/releases
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: DefStream>=0.1.0
20
+ Requires-Dist: pika>=1.3.2
21
+ Dynamic: author
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license-file
27
+ Dynamic: project-url
28
+ Dynamic: requires-dist
29
+ Dynamic: requires-python
30
+ Dynamic: summary
31
+
32
+ # DefStream-RabbitMQ
33
+
34
+ **한국어** | [English](./README.en.md)
35
+
36
+ DefStream에서 RabbitMQ를 사용할 수 있게 해주는 브로커 어댑터입니다.
37
+ 일반 큐, Exchange 라우팅, 스트림 이력 읽기, 동기 RPC를 제공하며,
38
+ DefStream Worker에 연결해 작업을 스레드·프로세스 풀에서 실행할 수 있습니다.
39
+ 내부 클라이언트로 Pika를 사용합니다.
40
+
41
+ ## 설치
42
+
43
+ Python **3.9 이상**과 접속 가능한 RabbitMQ 서버가 필요합니다.
44
+
45
+ ```shell
46
+ python -m pip install DefStream-RabbitMQ
47
+ ```
48
+
49
+ `DefStream>=0.1.0`과 `pika>=1.3.2`도 함께 설치됩니다.
50
+ 배포 패키지 이름은 `DefStream-RabbitMQ`이고 import 경로는
51
+ `DefStream.Broker.Implements.RabbitMQ`입니다.
52
+
53
+ ## 큐에 보내고 받기
54
+
55
+ 로컬 RabbitMQ의 `guest` 계정을 사용하는 예제입니다.
56
+ 운영에서는 별도 계정과 환경변수·비밀 저장소를 사용하세요.
57
+ 예제는 `defstream.example.rabbitmq` 큐를 만들며 실행 후에도 큐를 유지합니다.
58
+
59
+ ```python
60
+ from DefStream.Broker.Implements.RabbitMQ import Configuration, Connection
61
+
62
+
63
+ connection = Connection(Configuration(
64
+ host='127.0.0.1',
65
+ port=5672,
66
+ username='guest',
67
+ password='guest',
68
+ ))
69
+ try:
70
+ connection.connect()
71
+ connection.create_queue('defstream.example.rabbitmq')
72
+ queue = connection.queue('defstream.example.rabbitmq')
73
+ queue.send({'message': 'Hello, DefStream!'})
74
+ event = queue.pop(timeout=1000)
75
+ if event is not None:
76
+ print(event.body)
77
+ event.ack()
78
+ finally:
79
+ connection.close()
80
+ ```
81
+
82
+ 메시지는 기본 JSON 코덱으로 직렬화됩니다.
83
+ `pop()` 제한 시간은 **밀리초**이며, 양수 제한 시간에 메시지가 없으면 `None`을 반환합니다.
84
+ `None` 또는 `0`은 무기한 대기입니다.
85
+ 처리가 성공하면 `ack()`, 재전달하려면 `nack()`, 거부하려면 `reject()`를 호출하세요.
86
+ 거부한 메시지는 브로커의 dead-letter 설정이 있으면 해당 목적지로, 없으면 폐기됩니다.
87
+
88
+ ## 연결 설정
89
+
90
+ | 옵션 | 의미 |
91
+ | --- | --- |
92
+ | `host`, `port` | RabbitMQ 주소와 AMQP 포트 |
93
+ | `username`, `password` | 인증 정보 |
94
+ | `vhost` | 가상 호스트, 기본값 `/` |
95
+ | `ssl` | TLS 사용 여부, 기본값 `False` |
96
+ | `timeout` | blocked-connection 제한 시간, 밀리초 |
97
+ | `heartbeat` | 현재 구현은 `int(heartbeat * 2 / 1000)`초로 변환하여 Pika에 전달 |
98
+ | `encode`, `decode` | 메시지 코덱, 기본값 JSON |
99
+
100
+ `timeout`은 모든 작업에 대한 전체 실행 제한 시간이 아닙니다.
101
+ 일반 연결의 heartbeat는 애플리케이션 작업·유휴 시간에 맞게 설정하고 처리되도록 관리하세요.
102
+ 연결과 그 리소스는 **소유 스레드에서만 사용**해야 하며, 스레드·프로세스 사이에 공유하지 마세요.
103
+
104
+ ## Worker로 작업 처리하기
105
+
106
+ 다음은 큐와 오류 큐를 준비한 후 작업을 소비하는 실행 파일입니다.
107
+
108
+ ```python
109
+ from signal import SIGINT, signal
110
+
111
+ from DefStream.Broker.Implements.RabbitMQ import (
112
+ Configuration,
113
+ Connection,
114
+ Reject,
115
+ Subscription,
116
+ )
117
+ from DefStream.Worker import Run, ThreadPool, Worker, WorkerSetup, declare
118
+
119
+
120
+ class Add(
121
+ Run,
122
+ parameters=Subscription(
123
+ queue='defstream.example.rabbitmq.add',
124
+ qos=4,
125
+ error='defstream.example.rabbitmq.add.error',
126
+ ),
127
+ on_error=Reject(),
128
+ ):
129
+ def run(
130
+ self,
131
+ a: int,
132
+ b: int,
133
+ ):
134
+ return a + b
135
+
136
+
137
+ class Prepare(WorkerSetup):
138
+ def __call__(
139
+ self,
140
+ worker: Worker,
141
+ ) -> None:
142
+ for task in worker.tasks:
143
+ declare(
144
+ task=task,
145
+ broker=worker.broker,
146
+ )
147
+
148
+
149
+ if __name__ == '__main__':
150
+ worker = Worker(
151
+ Connection(Configuration(
152
+ host='127.0.0.1',
153
+ port=5672,
154
+ username='guest',
155
+ password='guest',
156
+ )),
157
+ ThreadPool(4),
158
+ setups=Prepare(),
159
+ )
160
+ worker.add(Add)
161
+ signal(
162
+ SIGINT,
163
+ lambda *_: worker.stop(),
164
+ )
165
+ worker.run()
166
+ ```
167
+
168
+ 다른 프로세스에서 같은 큐에 `{'a': 10, 'b': 20}`을 보내면 처리됩니다.
169
+ Worker는 실행과 완료 훅이 끝난 뒤 ACK하고, 실패하면 지정한 정책을 적용합니다.
170
+ `on_error`를 생략하면 기본값은 `Requeue()`입니다.
171
+
172
+ `Subscription` 옵션:
173
+
174
+ - `queue`: 작업 큐 이름.
175
+ - `qos`: 이 구독의 미확인 메시지 수 제한. 기본 소비자 값은 1이며, 0은 무제한입니다.
176
+ Worker의 공유 풀 크기와 별개입니다.
177
+ - `error`: `declare()`가 생성하고 연결할 오류 큐 이름. 거부된 메시지의 DLQ입니다.
178
+ - `offset`: RabbitMQ 스트림 구독에 사용할 정수 오프셋.
179
+
180
+ `Subscription` 객체 생성이나 `consumer.subs()`는 큐를 선언하지 않습니다.
181
+ 작업용 `declare()`는 일반 durable 큐와 선택적 DLQ를 준비하며,
182
+ 스트림 큐나 Exchange 바인딩을 자동 생성하지 않습니다.
183
+ 기존 큐의 선언 옵션이 다르면 실패하며 자동 삭제·재생성하지 않습니다.
184
+
185
+ ## 동기 RPC
186
+
187
+ 실행 중인 Worker가 있는 큐에 `call()`을 사용하면 `Run.run()`의 반환값을 받습니다.
188
+ 아래 코드는 앞의 직접 연결 예제에서 `connect()`와 `close()` 사이에 사용하세요.
189
+
190
+ ```python
191
+ result = connection.queue('defstream.example.rabbitmq.add').call(
192
+ {'a': 10, 'b': 20},
193
+ timeout=5,
194
+ )
195
+ print(result)
196
+ ```
197
+
198
+ - `timeout`은 **초** 단위이며 응답이 없으면 `TimeoutError`가 발생합니다.
199
+ 이미 전달된 서버 작업을 취소하거나 전체 연결·정리 시간을 엄격히 제한하는 값은 아닙니다.
200
+ - 각 호출은 전용 연결과 임시 응답 큐를 사용하고 종료 시 정리합니다.
201
+ - 서버가 요청을 거부하면 `DefStream.Broker.RemoteError`가 발생합니다.
202
+ 재큐잉은 최종 오류 응답 없이 재시도할 수 있습니다.
203
+ - 응답 발행과 요청 ACK는 원자적이지 않습니다. RPC에서도 중복 실행에 대비하세요.
204
+
205
+ 공유 `Run` 클래스를 사용하는 애플리케이션은 코어의
206
+ `request(body, task=Add, broker=connection, timeout=5)`도 사용할 수 있습니다.
207
+
208
+ ## Exchange와 스트림
209
+
210
+ - `connection.exchange(name)`은 `send()`와 `call()`을 제공합니다.
211
+ `event=`가 라우팅 키입니다. Exchange와 큐·바인딩을 먼저 선언하세요.
212
+ - Exchange RPC가 여러 큐로 라우팅되면 여러 곳에서 실행될 수 있으며,
213
+ 클라이언트는 첫 일치 응답만 받습니다. 일반 RPC에는 단일 목적지를 사용하세요.
214
+ - `create_exchange()`, `bind_exchange_to_queue()`, `bind_exchange_to_exchange()`로 라우팅을 구성합니다.
215
+ 각각에 대응하는 `delete_...` 또는 `unbind_...` 메서드도 있습니다.
216
+ - `create_stream()`으로 스트림 큐를 만든 뒤 `connection.stream(name)`의
217
+ `send()`와 `read(offset=0, timeout=1000)`을 사용합니다. 읽기 제한 시간은 밀리초입니다.
218
+ 읽은 이벤트는 이터레이터가 다음 단계로 진행될 때 자동 ACK합니다.
219
+ - `delete_queue()`, `delete_stream()`, `delete_exchange()`는 리소스를 삭제하므로
220
+ 애플리케이션 소유 리소스에만 사용하세요.
221
+
222
+ ## 운영 시 주의사항
223
+
224
+ - 최소 한 번(at-least-once) 전달을 전제로 멱등 작업을 작성하세요.
225
+ - 무제한 재큐잉은 영구 오류 메시지의 반복 실행을 만들 수 있습니다. DLQ와 재시도 정책을 설계하세요.
226
+ - 소비자 연결에서 긴 작업을 직접 실행하지 말고 Worker의 풀을 사용하세요.
227
+ - 작업 훅에서 발행하려면 훅이 실행되는 스레드·프로세스 안에 별도 생산자 연결을 만드세요.
228
+ - `worker.stop()`은 처리 중인 작업과 ACK를 기다린 뒤 연결과 풀을 닫습니다.
229
+ 강제 종료 또는 종료 대기 시간 제한은 제공하지 않습니다.
230
+
231
+ ## 더 알아보기
232
+
233
+ - [DefStream 사용 설명서](https://github.com/yong5eon/DefStream#readme): 작업, 풀, 훅, 검증, Inspector, 대시보드·콘솔
234
+ - [큐·Exchange 예제](./sample/Sample.py)
235
+ - [독립 실행 RPC 예제](./sample/Sample.RPC.py)
236
+ - [스트림 예제](./sample/Sample.Stream.py)
237
+ - [릴리즈와 변경 내역](https://github.com/yong5eon/DefStream-RabbitMQ/releases)
238
+
239
+ GNU GPL v3 라이선스를 사용합니다. 자세한 조건은 [LICENSE](./LICENSE)를 확인하세요.
@@ -1,5 +1,6 @@
1
1
  .gitignore
2
2
  LICENSE
3
+ README.en.md
3
4
  README.md
4
5
  setup.py
5
6
  .github/workflows/ci.yml
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: DefStream-RabbitMQ
3
+ Version: 0.1.1.3
4
+ Summary: RabbitMQ broker adapter for DefStream
5
+ Home-page: https://github.com/yong5eon/DefStream-RabbitMQ
6
+ Author: Heo Yongseon
7
+ Project-URL: Source, https://github.com/yong5eon/DefStream-RabbitMQ
8
+ Project-URL: Issues, https://github.com/yong5eon/DefStream-RabbitMQ/issues
9
+ Project-URL: Releases, https://github.com/yong5eon/DefStream-RabbitMQ/releases
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: DefStream>=0.1.0
20
+ Requires-Dist: pika>=1.3.2
21
+ Dynamic: author
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license-file
27
+ Dynamic: project-url
28
+ Dynamic: requires-dist
29
+ Dynamic: requires-python
30
+ Dynamic: summary
31
+
32
+ # DefStream-RabbitMQ
33
+
34
+ **한국어** | [English](./README.en.md)
35
+
36
+ DefStream에서 RabbitMQ를 사용할 수 있게 해주는 브로커 어댑터입니다.
37
+ 일반 큐, Exchange 라우팅, 스트림 이력 읽기, 동기 RPC를 제공하며,
38
+ DefStream Worker에 연결해 작업을 스레드·프로세스 풀에서 실행할 수 있습니다.
39
+ 내부 클라이언트로 Pika를 사용합니다.
40
+
41
+ ## 설치
42
+
43
+ Python **3.9 이상**과 접속 가능한 RabbitMQ 서버가 필요합니다.
44
+
45
+ ```shell
46
+ python -m pip install DefStream-RabbitMQ
47
+ ```
48
+
49
+ `DefStream>=0.1.0`과 `pika>=1.3.2`도 함께 설치됩니다.
50
+ 배포 패키지 이름은 `DefStream-RabbitMQ`이고 import 경로는
51
+ `DefStream.Broker.Implements.RabbitMQ`입니다.
52
+
53
+ ## 큐에 보내고 받기
54
+
55
+ 로컬 RabbitMQ의 `guest` 계정을 사용하는 예제입니다.
56
+ 운영에서는 별도 계정과 환경변수·비밀 저장소를 사용하세요.
57
+ 예제는 `defstream.example.rabbitmq` 큐를 만들며 실행 후에도 큐를 유지합니다.
58
+
59
+ ```python
60
+ from DefStream.Broker.Implements.RabbitMQ import Configuration, Connection
61
+
62
+
63
+ connection = Connection(Configuration(
64
+ host='127.0.0.1',
65
+ port=5672,
66
+ username='guest',
67
+ password='guest',
68
+ ))
69
+ try:
70
+ connection.connect()
71
+ connection.create_queue('defstream.example.rabbitmq')
72
+ queue = connection.queue('defstream.example.rabbitmq')
73
+ queue.send({'message': 'Hello, DefStream!'})
74
+ event = queue.pop(timeout=1000)
75
+ if event is not None:
76
+ print(event.body)
77
+ event.ack()
78
+ finally:
79
+ connection.close()
80
+ ```
81
+
82
+ 메시지는 기본 JSON 코덱으로 직렬화됩니다.
83
+ `pop()` 제한 시간은 **밀리초**이며, 양수 제한 시간에 메시지가 없으면 `None`을 반환합니다.
84
+ `None` 또는 `0`은 무기한 대기입니다.
85
+ 처리가 성공하면 `ack()`, 재전달하려면 `nack()`, 거부하려면 `reject()`를 호출하세요.
86
+ 거부한 메시지는 브로커의 dead-letter 설정이 있으면 해당 목적지로, 없으면 폐기됩니다.
87
+
88
+ ## 연결 설정
89
+
90
+ | 옵션 | 의미 |
91
+ | --- | --- |
92
+ | `host`, `port` | RabbitMQ 주소와 AMQP 포트 |
93
+ | `username`, `password` | 인증 정보 |
94
+ | `vhost` | 가상 호스트, 기본값 `/` |
95
+ | `ssl` | TLS 사용 여부, 기본값 `False` |
96
+ | `timeout` | blocked-connection 제한 시간, 밀리초 |
97
+ | `heartbeat` | 현재 구현은 `int(heartbeat * 2 / 1000)`초로 변환하여 Pika에 전달 |
98
+ | `encode`, `decode` | 메시지 코덱, 기본값 JSON |
99
+
100
+ `timeout`은 모든 작업에 대한 전체 실행 제한 시간이 아닙니다.
101
+ 일반 연결의 heartbeat는 애플리케이션 작업·유휴 시간에 맞게 설정하고 처리되도록 관리하세요.
102
+ 연결과 그 리소스는 **소유 스레드에서만 사용**해야 하며, 스레드·프로세스 사이에 공유하지 마세요.
103
+
104
+ ## Worker로 작업 처리하기
105
+
106
+ 다음은 큐와 오류 큐를 준비한 후 작업을 소비하는 실행 파일입니다.
107
+
108
+ ```python
109
+ from signal import SIGINT, signal
110
+
111
+ from DefStream.Broker.Implements.RabbitMQ import (
112
+ Configuration,
113
+ Connection,
114
+ Reject,
115
+ Subscription,
116
+ )
117
+ from DefStream.Worker import Run, ThreadPool, Worker, WorkerSetup, declare
118
+
119
+
120
+ class Add(
121
+ Run,
122
+ parameters=Subscription(
123
+ queue='defstream.example.rabbitmq.add',
124
+ qos=4,
125
+ error='defstream.example.rabbitmq.add.error',
126
+ ),
127
+ on_error=Reject(),
128
+ ):
129
+ def run(
130
+ self,
131
+ a: int,
132
+ b: int,
133
+ ):
134
+ return a + b
135
+
136
+
137
+ class Prepare(WorkerSetup):
138
+ def __call__(
139
+ self,
140
+ worker: Worker,
141
+ ) -> None:
142
+ for task in worker.tasks:
143
+ declare(
144
+ task=task,
145
+ broker=worker.broker,
146
+ )
147
+
148
+
149
+ if __name__ == '__main__':
150
+ worker = Worker(
151
+ Connection(Configuration(
152
+ host='127.0.0.1',
153
+ port=5672,
154
+ username='guest',
155
+ password='guest',
156
+ )),
157
+ ThreadPool(4),
158
+ setups=Prepare(),
159
+ )
160
+ worker.add(Add)
161
+ signal(
162
+ SIGINT,
163
+ lambda *_: worker.stop(),
164
+ )
165
+ worker.run()
166
+ ```
167
+
168
+ 다른 프로세스에서 같은 큐에 `{'a': 10, 'b': 20}`을 보내면 처리됩니다.
169
+ Worker는 실행과 완료 훅이 끝난 뒤 ACK하고, 실패하면 지정한 정책을 적용합니다.
170
+ `on_error`를 생략하면 기본값은 `Requeue()`입니다.
171
+
172
+ `Subscription` 옵션:
173
+
174
+ - `queue`: 작업 큐 이름.
175
+ - `qos`: 이 구독의 미확인 메시지 수 제한. 기본 소비자 값은 1이며, 0은 무제한입니다.
176
+ Worker의 공유 풀 크기와 별개입니다.
177
+ - `error`: `declare()`가 생성하고 연결할 오류 큐 이름. 거부된 메시지의 DLQ입니다.
178
+ - `offset`: RabbitMQ 스트림 구독에 사용할 정수 오프셋.
179
+
180
+ `Subscription` 객체 생성이나 `consumer.subs()`는 큐를 선언하지 않습니다.
181
+ 작업용 `declare()`는 일반 durable 큐와 선택적 DLQ를 준비하며,
182
+ 스트림 큐나 Exchange 바인딩을 자동 생성하지 않습니다.
183
+ 기존 큐의 선언 옵션이 다르면 실패하며 자동 삭제·재생성하지 않습니다.
184
+
185
+ ## 동기 RPC
186
+
187
+ 실행 중인 Worker가 있는 큐에 `call()`을 사용하면 `Run.run()`의 반환값을 받습니다.
188
+ 아래 코드는 앞의 직접 연결 예제에서 `connect()`와 `close()` 사이에 사용하세요.
189
+
190
+ ```python
191
+ result = connection.queue('defstream.example.rabbitmq.add').call(
192
+ {'a': 10, 'b': 20},
193
+ timeout=5,
194
+ )
195
+ print(result)
196
+ ```
197
+
198
+ - `timeout`은 **초** 단위이며 응답이 없으면 `TimeoutError`가 발생합니다.
199
+ 이미 전달된 서버 작업을 취소하거나 전체 연결·정리 시간을 엄격히 제한하는 값은 아닙니다.
200
+ - 각 호출은 전용 연결과 임시 응답 큐를 사용하고 종료 시 정리합니다.
201
+ - 서버가 요청을 거부하면 `DefStream.Broker.RemoteError`가 발생합니다.
202
+ 재큐잉은 최종 오류 응답 없이 재시도할 수 있습니다.
203
+ - 응답 발행과 요청 ACK는 원자적이지 않습니다. RPC에서도 중복 실행에 대비하세요.
204
+
205
+ 공유 `Run` 클래스를 사용하는 애플리케이션은 코어의
206
+ `request(body, task=Add, broker=connection, timeout=5)`도 사용할 수 있습니다.
207
+
208
+ ## Exchange와 스트림
209
+
210
+ - `connection.exchange(name)`은 `send()`와 `call()`을 제공합니다.
211
+ `event=`가 라우팅 키입니다. Exchange와 큐·바인딩을 먼저 선언하세요.
212
+ - Exchange RPC가 여러 큐로 라우팅되면 여러 곳에서 실행될 수 있으며,
213
+ 클라이언트는 첫 일치 응답만 받습니다. 일반 RPC에는 단일 목적지를 사용하세요.
214
+ - `create_exchange()`, `bind_exchange_to_queue()`, `bind_exchange_to_exchange()`로 라우팅을 구성합니다.
215
+ 각각에 대응하는 `delete_...` 또는 `unbind_...` 메서드도 있습니다.
216
+ - `create_stream()`으로 스트림 큐를 만든 뒤 `connection.stream(name)`의
217
+ `send()`와 `read(offset=0, timeout=1000)`을 사용합니다. 읽기 제한 시간은 밀리초입니다.
218
+ 읽은 이벤트는 이터레이터가 다음 단계로 진행될 때 자동 ACK합니다.
219
+ - `delete_queue()`, `delete_stream()`, `delete_exchange()`는 리소스를 삭제하므로
220
+ 애플리케이션 소유 리소스에만 사용하세요.
221
+
222
+ ## 운영 시 주의사항
223
+
224
+ - 최소 한 번(at-least-once) 전달을 전제로 멱등 작업을 작성하세요.
225
+ - 무제한 재큐잉은 영구 오류 메시지의 반복 실행을 만들 수 있습니다. DLQ와 재시도 정책을 설계하세요.
226
+ - 소비자 연결에서 긴 작업을 직접 실행하지 말고 Worker의 풀을 사용하세요.
227
+ - 작업 훅에서 발행하려면 훅이 실행되는 스레드·프로세스 안에 별도 생산자 연결을 만드세요.
228
+ - `worker.stop()`은 처리 중인 작업과 ACK를 기다린 뒤 연결과 풀을 닫습니다.
229
+ 강제 종료 또는 종료 대기 시간 제한은 제공하지 않습니다.
230
+
231
+ ## 더 알아보기
232
+
233
+ - [DefStream 사용 설명서](https://github.com/yong5eon/DefStream#readme): 작업, 풀, 훅, 검증, Inspector, 대시보드·콘솔
234
+ - [큐·Exchange 예제](./sample/Sample.py)
235
+ - [독립 실행 RPC 예제](./sample/Sample.RPC.py)
236
+ - [스트림 예제](./sample/Sample.Stream.py)
237
+ - [릴리즈와 변경 내역](https://github.com/yong5eon/DefStream-RabbitMQ/releases)
238
+
239
+ GNU GPL v3 라이선스를 사용합니다. 자세한 조건은 [LICENSE](./LICENSE)를 확인하세요.
@@ -0,0 +1,210 @@
1
+ # DefStream-RabbitMQ
2
+
3
+ [한국어](./README.md) | **English**
4
+
5
+ The RabbitMQ broker adapter for DefStream provides ordinary queues, Exchange
6
+ routing, stream history reads, and synchronous RPC. Connect it to a DefStream
7
+ Worker to execute tasks in a thread or process pool. It uses Pika internally.
8
+
9
+ ## Installation
10
+
11
+ Requires Python **3.9 or newer** and a reachable RabbitMQ server.
12
+
13
+ ```shell
14
+ python -m pip install DefStream-RabbitMQ
15
+ ```
16
+
17
+ This also installs `DefStream>=0.1.0` and `pika>=1.3.2`.
18
+ The distribution name is `DefStream-RabbitMQ`; its Python import path is
19
+ `DefStream.Broker.Implements.RabbitMQ`.
20
+
21
+ ## Send and receive queue messages
22
+
23
+ This example uses a local RabbitMQ server's `guest` account. Use a dedicated
24
+ account and environment variables or a secret store in production.
25
+ It creates `defstream.example.rabbitmq` and leaves the queue in place.
26
+
27
+ ```python
28
+ from DefStream.Broker.Implements.RabbitMQ import Configuration, Connection
29
+
30
+
31
+ connection = Connection(Configuration(
32
+ host='127.0.0.1',
33
+ port=5672,
34
+ username='guest',
35
+ password='guest',
36
+ ))
37
+ try:
38
+ connection.connect()
39
+ connection.create_queue('defstream.example.rabbitmq')
40
+ queue = connection.queue('defstream.example.rabbitmq')
41
+ queue.send({'message': 'Hello, DefStream!'})
42
+ event = queue.pop(timeout=1000)
43
+ if event is not None:
44
+ print(event.body)
45
+ event.ack()
46
+ finally:
47
+ connection.close()
48
+ ```
49
+
50
+ The default codec serializes messages as JSON.
51
+ The `pop()` timeout is in **milliseconds**; a positive timeout returns `None`
52
+ if no delivery arrives. `None` or `0` waits indefinitely.
53
+ Call `ack()` on success, `nack()` for redelivery, or `reject()` to reject.
54
+ Rejected messages go to the broker-configured dead-letter destination or are
55
+ discarded when none is configured.
56
+
57
+ ## Connection configuration
58
+
59
+ | Option | Meaning |
60
+ | --- | --- |
61
+ | `host`, `port` | RabbitMQ address and AMQP port |
62
+ | `username`, `password` | Credentials |
63
+ | `vhost` | Virtual host; defaults to `/` |
64
+ | `ssl` | Enable TLS; defaults to `False` |
65
+ | `timeout` | Blocked-connection timeout, in milliseconds |
66
+ | `heartbeat` | The current implementation passes `int(heartbeat * 2 / 1000)` seconds to Pika |
67
+ | `encode`, `decode` | Message codecs; JSON by default |
68
+
69
+ `timeout` is not a whole-operation deadline.
70
+ Configure and service connection heartbeats appropriately for task and idle periods.
71
+ Use connections and their resources **only on the owning thread**; do not
72
+ share them across threads or processes.
73
+
74
+ ## Process tasks with a Worker
75
+
76
+ This executable example provisions a task queue and error queue, then consumes tasks.
77
+
78
+ ```python
79
+ from signal import SIGINT, signal
80
+
81
+ from DefStream.Broker.Implements.RabbitMQ import (
82
+ Configuration,
83
+ Connection,
84
+ Reject,
85
+ Subscription,
86
+ )
87
+ from DefStream.Worker import Run, ThreadPool, Worker, WorkerSetup, declare
88
+
89
+
90
+ class Add(
91
+ Run,
92
+ parameters=Subscription(
93
+ queue='defstream.example.rabbitmq.add',
94
+ qos=4,
95
+ error='defstream.example.rabbitmq.add.error',
96
+ ),
97
+ on_error=Reject(),
98
+ ):
99
+ def run(
100
+ self,
101
+ a: int,
102
+ b: int,
103
+ ):
104
+ return a + b
105
+
106
+
107
+ class Prepare(WorkerSetup):
108
+ def __call__(
109
+ self,
110
+ worker: Worker,
111
+ ) -> None:
112
+ for task in worker.tasks:
113
+ declare(
114
+ task=task,
115
+ broker=worker.broker,
116
+ )
117
+
118
+
119
+ if __name__ == '__main__':
120
+ worker = Worker(
121
+ Connection(Configuration(
122
+ host='127.0.0.1',
123
+ port=5672,
124
+ username='guest',
125
+ password='guest',
126
+ )),
127
+ ThreadPool(4),
128
+ setups=Prepare(),
129
+ )
130
+ worker.add(Add)
131
+ signal(
132
+ SIGINT,
133
+ lambda *_: worker.stop(),
134
+ )
135
+ worker.run()
136
+ ```
137
+
138
+ Send `{'a': 10, 'b': 20}` to the same queue from another process.
139
+ The Worker ACKs after execution and completion hooks finish, and applies
140
+ the selected failure policy on error. Omitting `on_error` defaults to `Requeue()`.
141
+
142
+ `Subscription` options:
143
+
144
+ - `queue`: task queue name.
145
+ - `qos`: this subscription's unacknowledged-delivery limit. The consumer default
146
+ is 1; 0 means unlimited. This is separate from shared Worker pool capacity.
147
+ - `error`: error queue to create and bind through `declare()`; a DLQ for rejected messages.
148
+ - `offset`: integer offset for RabbitMQ stream subscriptions.
149
+
150
+ Constructing a `Subscription` or calling `consumer.subs()` does not declare queues.
151
+ Task `declare()` provisions ordinary durable queues and an optional DLQ,
152
+ not stream queues or Exchange bindings. Incompatible existing queue options
153
+ fail explicitly; queues are not automatically deleted and recreated.
154
+
155
+ ## Synchronous RPC
156
+
157
+ Call a queue served by a running Worker to receive the result of `Run.run()`.
158
+ Use the following between `connect()` and `close()` in the direct-connection example.
159
+
160
+ ```python
161
+ result = connection.queue('defstream.example.rabbitmq.add').call(
162
+ {'a': 10, 'b': 20},
163
+ timeout=5,
164
+ )
165
+ print(result)
166
+ ```
167
+
168
+ - `timeout` is in **seconds**. Missing replies raise `TimeoutError`.
169
+ This does not cancel delivered work or strictly bound total connection and cleanup time.
170
+ - Each call owns a dedicated connection and temporary reply queue, cleaned up on exit.
171
+ - Server rejection raises `DefStream.Broker.RemoteError`.
172
+ Requeue can retry without sending a final error response.
173
+ - Reply publication and request ACK are not atomic. Handle duplicate execution with RPC too.
174
+
175
+ Applications sharing a `Run` class can also use the core helper
176
+ `request(body, task=Add, broker=connection, timeout=5)`.
177
+
178
+ ## Exchanges and streams
179
+
180
+ - `connection.exchange(name)` provides `send()` and `call()`.
181
+ `event=` selects the routing key. Declare the Exchange, queues, and bindings first.
182
+ - Exchange RPC routed to several queues can execute at every destination and
183
+ returns only the first matching reply. Use a single destination for ordinary RPC.
184
+ - Configure routing with `create_exchange()`, `bind_exchange_to_queue()`, and
185
+ `bind_exchange_to_exchange()`. Corresponding `delete_...` or `unbind_...` methods are available.
186
+ - Use `create_stream()` to provision a stream queue, then access
187
+ `connection.stream(name)` with `send()` and `read(offset=0, timeout=1000)`.
188
+ The read timeout is in milliseconds.
189
+ Read events are ACKed automatically when iteration advances.
190
+ - `delete_queue()`, `delete_stream()`, and `delete_exchange()` remove resources;
191
+ use them only for resources owned by your application.
192
+
193
+ ## Operational considerations
194
+
195
+ - Design idempotent tasks for at-least-once delivery.
196
+ - Unlimited requeue can repeatedly execute permanently invalid messages. Plan DLQ and retry policies.
197
+ - Execute long tasks in the Worker's pool rather than on the consumer connection.
198
+ - When publishing from task hooks, create a separate producer connection inside the hook's thread/process.
199
+ - `worker.stop()` waits for in-flight tasks and ACKs before closing the connection and pool.
200
+ There is no forced termination or shutdown timeout.
201
+
202
+ ## Further reading
203
+
204
+ - [DefStream user guide](https://github.com/yong5eon/DefStream/blob/master/README.en.md): tasks, pools, hooks, validation, Inspector, dashboard, and console
205
+ - [Queue and Exchange example](./sample/Sample.py)
206
+ - [Standalone RPC example](./sample/Sample.RPC.py)
207
+ - [Stream example](./sample/Sample.Stream.py)
208
+ - [Releases and change history](https://github.com/yong5eon/DefStream-RabbitMQ/releases)
209
+
210
+ Licensed under GNU GPL v3. See [LICENSE](./LICENSE) for the terms.