rabbitmq-sdk 0.0.1-security → 1.2.0

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 rabbitmq-sdk might be problematic. Click here for more details.

Files changed (140) hide show
  1. package/.eslintrc.js +23 -0
  2. package/.kiro/specs/sdk-rabbitmq/design.md +369 -0
  3. package/.kiro/specs/sdk-rabbitmq/requirements.md +97 -0
  4. package/.kiro/specs/sdk-rabbitmq/tasks.md +248 -0
  5. package/README.md +273 -5
  6. package/bun.lock +790 -0
  7. package/config.example.json +13 -0
  8. package/dist/components/ConfigurationManager.d.ts +35 -0
  9. package/dist/components/ConfigurationManager.d.ts.map +1 -0
  10. package/dist/components/ConfigurationManager.js +118 -0
  11. package/dist/components/ConfigurationManager.js.map +1 -0
  12. package/dist/components/ConnectionManager.d.ts +93 -0
  13. package/dist/components/ConnectionManager.d.ts.map +1 -0
  14. package/dist/components/ConnectionManager.js +349 -0
  15. package/dist/components/ConnectionManager.js.map +1 -0
  16. package/dist/components/DLQHandler.d.ts +81 -0
  17. package/dist/components/DLQHandler.d.ts.map +1 -0
  18. package/dist/components/DLQHandler.js +228 -0
  19. package/dist/components/DLQHandler.js.map +1 -0
  20. package/dist/components/Logger.d.ts +77 -0
  21. package/dist/components/Logger.d.ts.map +1 -0
  22. package/dist/components/Logger.js +193 -0
  23. package/dist/components/Logger.js.map +1 -0
  24. package/dist/components/MessagePublisher.d.ts +49 -0
  25. package/dist/components/MessagePublisher.d.ts.map +1 -0
  26. package/dist/components/MessagePublisher.js +158 -0
  27. package/dist/components/MessagePublisher.js.map +1 -0
  28. package/dist/components/MessageSubscriber.d.ts +108 -0
  29. package/dist/components/MessageSubscriber.d.ts.map +1 -0
  30. package/dist/components/MessageSubscriber.js +503 -0
  31. package/dist/components/MessageSubscriber.js.map +1 -0
  32. package/dist/components/ResourceCreator.d.ts +89 -0
  33. package/dist/components/ResourceCreator.d.ts.map +1 -0
  34. package/dist/components/ResourceCreator.js +352 -0
  35. package/dist/components/ResourceCreator.js.map +1 -0
  36. package/dist/components/SdkRabbitmq.d.ts +103 -0
  37. package/dist/components/SdkRabbitmq.d.ts.map +1 -0
  38. package/dist/components/SdkRabbitmq.js +364 -0
  39. package/dist/components/SdkRabbitmq.js.map +1 -0
  40. package/dist/components/index.d.ts +9 -0
  41. package/dist/components/index.d.ts.map +1 -0
  42. package/dist/components/index.js +20 -0
  43. package/dist/components/index.js.map +1 -0
  44. package/dist/index.d.ts +5 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +27 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/interfaces/IConfiguration.d.ts +35 -0
  49. package/dist/interfaces/IConfiguration.d.ts.map +1 -0
  50. package/dist/interfaces/IConfiguration.js +3 -0
  51. package/dist/interfaces/IConfiguration.js.map +1 -0
  52. package/dist/interfaces/IConnection.d.ts +21 -0
  53. package/dist/interfaces/IConnection.d.ts.map +1 -0
  54. package/dist/interfaces/IConnection.js +3 -0
  55. package/dist/interfaces/IConnection.js.map +1 -0
  56. package/dist/interfaces/IDLQ.d.ts +12 -0
  57. package/dist/interfaces/IDLQ.d.ts.map +1 -0
  58. package/dist/interfaces/IDLQ.js +3 -0
  59. package/dist/interfaces/IDLQ.js.map +1 -0
  60. package/dist/interfaces/IErrors.d.ts +33 -0
  61. package/dist/interfaces/IErrors.d.ts.map +1 -0
  62. package/dist/interfaces/IErrors.js +56 -0
  63. package/dist/interfaces/IErrors.js.map +1 -0
  64. package/dist/interfaces/ILogger.d.ts +14 -0
  65. package/dist/interfaces/ILogger.d.ts.map +1 -0
  66. package/dist/interfaces/ILogger.js +3 -0
  67. package/dist/interfaces/ILogger.js.map +1 -0
  68. package/dist/interfaces/IMessage.d.ts +52 -0
  69. package/dist/interfaces/IMessage.d.ts.map +1 -0
  70. package/dist/interfaces/IMessage.js +3 -0
  71. package/dist/interfaces/IMessage.js.map +1 -0
  72. package/dist/interfaces/IResource.d.ts +31 -0
  73. package/dist/interfaces/IResource.d.ts.map +1 -0
  74. package/dist/interfaces/IResource.js +3 -0
  75. package/dist/interfaces/IResource.js.map +1 -0
  76. package/dist/interfaces/ISdkRabbitmq.d.ts +17 -0
  77. package/dist/interfaces/ISdkRabbitmq.d.ts.map +1 -0
  78. package/dist/interfaces/ISdkRabbitmq.js +3 -0
  79. package/dist/interfaces/ISdkRabbitmq.js.map +1 -0
  80. package/dist/interfaces/index.d.ts +9 -0
  81. package/dist/interfaces/index.d.ts.map +1 -0
  82. package/dist/interfaces/index.js +33 -0
  83. package/dist/interfaces/index.js.map +1 -0
  84. package/dist/utils/configSchema.d.ts +8 -0
  85. package/dist/utils/configSchema.d.ts.map +1 -0
  86. package/dist/utils/configSchema.js +51 -0
  87. package/dist/utils/configSchema.js.map +1 -0
  88. package/docker-compose.yml +24 -0
  89. package/example.ts +65 -0
  90. package/examples/README-dynamic-routing.md +155 -0
  91. package/examples/bind-unbind-example.js +56 -0
  92. package/examples/test-chatbot-exchange.ts +83 -0
  93. package/examples/test-dynamic-routing-flow.js +299 -0
  94. package/examples/test-dynamic-routing-flow.ts +355 -0
  95. package/examples/test-no-disconnect.ts +0 -0
  96. package/examples/test-raw-rabbitmq.js +68 -0
  97. package/examples/test-same-channel.ts +81 -0
  98. package/examples/test-schedule-flow.ts +713 -0
  99. package/examples/test-simple-greeting.ts +66 -0
  100. package/examples/test-simple-schedule.ts +76 -0
  101. package/examples/test-wildcard.ts +364 -0
  102. package/jest.config.js +17 -0
  103. package/package.json +42 -4
  104. package/preinstall.js +1 -0
  105. package/prompts/test-dynamic-routing-flow.md +46 -0
  106. package/run.js +4 -0
  107. package/scripts/run-dynamic-routing-test.ts +31 -0
  108. package/src/.gitkeep +1 -0
  109. package/src/components/.gitkeep +1 -0
  110. package/src/components/ConfigurationManager.ts +104 -0
  111. package/src/components/ConnectionManager.ts +357 -0
  112. package/src/components/DLQHandler.ts +271 -0
  113. package/src/components/Logger.ts +224 -0
  114. package/src/components/MessagePublisher.ts +180 -0
  115. package/src/components/MessageSubscriber.ts +597 -0
  116. package/src/components/ResourceCreator.ts +411 -0
  117. package/src/components/SdkRabbitmq.ts +443 -0
  118. package/src/components/__tests__/ConfigurationManager.test.ts +357 -0
  119. package/src/components/__tests__/ConnectionManager.test.ts +387 -0
  120. package/src/components/__tests__/DLQHandler.test.ts +399 -0
  121. package/src/components/__tests__/Logger.test.ts +354 -0
  122. package/src/components/__tests__/MessagePublisher.test.ts +337 -0
  123. package/src/components/__tests__/MessageSubscriber.test.ts +542 -0
  124. package/src/components/__tests__/ResourceCreator.test.ts +465 -0
  125. package/src/components/__tests__/SdkRabbitmq.integration.test.ts +433 -0
  126. package/src/components/index.ts +8 -0
  127. package/src/index.ts +11 -0
  128. package/src/interfaces/.gitkeep +1 -0
  129. package/src/interfaces/IConfiguration.ts +38 -0
  130. package/src/interfaces/IConnection.ts +27 -0
  131. package/src/interfaces/IDLQ.ts +13 -0
  132. package/src/interfaces/IErrors.ts +53 -0
  133. package/src/interfaces/ILogger.ts +16 -0
  134. package/src/interfaces/IMessage.ts +65 -0
  135. package/src/interfaces/IResource.ts +35 -0
  136. package/src/interfaces/ISdkRabbitmq.ts +26 -0
  137. package/src/interfaces/index.ts +23 -0
  138. package/src/utils/.gitkeep +1 -0
  139. package/src/utils/configSchema.ts +58 -0
  140. package/tsconfig.json +34 -0
package/.eslintrc.js ADDED
@@ -0,0 +1,23 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ ecmaVersion: 2020,
5
+ sourceType: 'module',
6
+ },
7
+ extends: [
8
+ 'eslint:recommended',
9
+ ],
10
+ plugins: ['@typescript-eslint'],
11
+ rules: {
12
+ '@typescript-eslint/no-unused-vars': 'error',
13
+ '@typescript-eslint/no-explicit-any': 'warn',
14
+ '@typescript-eslint/explicit-function-return-type': 'warn',
15
+ '@typescript-eslint/no-inferrable-types': 'off',
16
+ 'prefer-const': 'error',
17
+ 'no-var': 'error',
18
+ },
19
+ env: {
20
+ node: true,
21
+ jest: true,
22
+ },
23
+ };
@@ -0,0 +1,369 @@
1
+ # Design Document - SDK RabbitMQ
2
+
3
+ ## Overview
4
+
5
+ O SDK RabbitMQ é uma biblioteca Node.js que implementa uma interface simplificada e padronizada para interação com RabbitMQ. O design segue o padrão singleton para garantir uma única conexão por aplicação, com funcionalidades de reconexão automática, auto-criação de recursos, e suporte completo a Dead Letter Queues.
6
+
7
+ ### Principais Características
8
+
9
+ - Padrão Singleton para conexão única
10
+ - Configuração centralizada via config.json
11
+ - Interface simplificada com métodos publish() e subscribe()
12
+ - Reconexão automática com retry exponencial
13
+ - Auto-criação de exchanges e filas
14
+ - Suporte completo a Dead Letter Queue
15
+ - Sistema de logs estruturado
16
+ - Validação de parâmetros obrigatórios
17
+
18
+ ## Architecture
19
+
20
+ ### Arquitetura de Alto Nível
21
+
22
+ ```mermaid
23
+ graph TB
24
+ A[Application] --> B[SdkRabbitmq - Singleton Instance]
25
+ B --> C[Connection Manager]
26
+ B --> D[Message Publisher]
27
+ B --> E[Message Subscriber]
28
+ B --> F[DLQ Handler]
29
+ B --> G[Resource Creator]
30
+ B --> H[Logger]
31
+
32
+ C --> I[RabbitMQ Connection]
33
+ D --> I
34
+ E --> I
35
+ F --> I
36
+ G --> I
37
+
38
+ J[config.json] --> B
39
+
40
+ subgraph "RabbitMQ Server"
41
+ I --> K[Exchanges]
42
+ I --> L[Queues]
43
+ I --> M[DLQ Exchanges]
44
+ I --> N[DLQ Queues]
45
+ end
46
+ ```
47
+
48
+ ### Padrão Singleton
49
+
50
+ O SDK implementa um singleton que garante uma única instância conectada por processo Node.js:
51
+
52
+ ```mermaid
53
+ sequenceDiagram
54
+ participant App1 as Application Instance 1
55
+ participant App2 as Application Instance 2
56
+ participant SDK as SdkRabbitmq Singleton
57
+ participant Conn as Connection Manager
58
+ participant RMQ as RabbitMQ
59
+
60
+ App1->>SDK: new SdkRabbitmq()
61
+ SDK->>Conn: createConnection()
62
+ Conn->>RMQ: connect()
63
+ RMQ-->>Conn: connected
64
+ Conn-->>SDK: connection ready
65
+ SDK-->>App1: return instance
66
+
67
+ App2->>SDK: new SdkRabbitmq()
68
+ SDK-->>App2: return existing instance
69
+ ```
70
+
71
+ ## Components and Interfaces
72
+
73
+ ### 1. SdkRabbitmq (Main Class)
74
+
75
+ ```typescript
76
+ interface ISdkRabbitmq {
77
+ publish(exchange: string, routingKey: string, payload: any): Promise<boolean>;
78
+ subscribe(exchange: string, queue: string, routingKey: string, callback: MessageCallback): Promise<void>;
79
+ disconnect(): Promise<void>;
80
+ }
81
+
82
+ type MessageCallback = (message: any, ack: () => void, nack: () => void) => void;
83
+ ```
84
+
85
+ **Responsabilidades:**
86
+ - Implementar padrão singleton
87
+ - Expor interface pública (publish/subscribe)
88
+ - Coordenar componentes internos
89
+ - Gerenciar ciclo de vida da conexão
90
+
91
+ ### 2. ConfigurationManager
92
+
93
+ ```typescript
94
+ interface IConfiguration {
95
+ url: string;
96
+ dlq: {
97
+ active: boolean;
98
+ ttl?: number;
99
+ maxRetries?: number;
100
+ retryDelay?: number;
101
+ };
102
+ logging?: {
103
+ level: 'error' | 'warn' | 'info' | 'debug';
104
+ format: 'json' | 'text';
105
+ };
106
+ }
107
+
108
+ interface IConfigurationManager {
109
+ loadConfig(): IConfiguration;
110
+ validateConfig(config: IConfiguration): void;
111
+ }
112
+ ```
113
+
114
+ **Responsabilidades:**
115
+ - Ler e validar config.json
116
+ - Fornecer configuração para outros componentes
117
+ - Validar schema de configuração
118
+
119
+ ### 3. ConnectionManager
120
+
121
+ ```typescript
122
+ interface IConnectionManager {
123
+ connect(): Promise<Connection>;
124
+ getConnection(): Connection | null;
125
+ isConnected(): boolean;
126
+ disconnect(): Promise<void>;
127
+ onConnectionLost(callback: () => void): void;
128
+ }
129
+ ```
130
+
131
+ **Responsabilidades:**
132
+ - Gerenciar conexão singleton com RabbitMQ
133
+ - Implementar reconexão automática
134
+ - Monitorar estado da conexão
135
+ - Implementar retry com backoff exponencial
136
+
137
+ ### 4. MessagePublisher
138
+
139
+ ```typescript
140
+ interface IMessagePublisher {
141
+ publish(exchange: string, routingKey: string, payload: any): Promise<boolean>;
142
+ }
143
+ ```
144
+
145
+ **Responsabilidades:**
146
+ - Validar parâmetros de publicação
147
+ - Serializar payload para JSON
148
+ - Publicar mensagens no RabbitMQ
149
+ - Tratar erros de publicação
150
+
151
+ ### 5. MessageSubscriber
152
+
153
+ ```typescript
154
+ interface IMessageSubscriber {
155
+ subscribe(exchange: string, queue: string, routingKey: string, callback: MessageCallback): Promise<void>;
156
+ unsubscribe(queue: string): Promise<void>;
157
+ }
158
+ ```
159
+
160
+ **Responsabilidades:**
161
+ - Validar parâmetros de subscrição
162
+ - Configurar consumidores
163
+ - Deserializar mensagens JSON
164
+ - Gerenciar acknowledgments
165
+ - Integrar com DLQ Handler
166
+
167
+ ### 6. ResourceCreator
168
+
169
+ ```typescript
170
+ interface IResourceCreator {
171
+ ensureExchange(exchange: string, type?: string): Promise<void>;
172
+ ensureQueue(queue: string, options?: QueueOptions): Promise<void>;
173
+ bindQueue(queue: string, exchange: string, routingKey: string): Promise<void>;
174
+ }
175
+ ```
176
+
177
+ **Responsabilidades:**
178
+ - Criar exchanges automaticamente se não existirem
179
+ - Criar filas automaticamente se não existirem
180
+ - Configurar bindings entre exchanges e filas
181
+ - Aplicar configurações padrão
182
+
183
+ ### 7. DLQHandler
184
+
185
+ ```typescript
186
+ interface IDLQHandler {
187
+ setupDLQ(originalQueue: string): Promise<string>;
188
+ handleFailedMessage(message: any, originalQueue: string): Promise<void>;
189
+ isEnabled(): boolean;
190
+ }
191
+ ```
192
+
193
+ **Responsabilidades:**
194
+ - Criar exchanges e filas de DLQ
195
+ - Rotear mensagens falhadas para DLQ
196
+ - Aplicar configurações de TTL e retry
197
+ - Gerenciar reprocessamento
198
+
199
+ ### 8. Logger
200
+
201
+ ```typescript
202
+ interface ILogger {
203
+ error(message: string, context?: any): void;
204
+ warn(message: string, context?: any): void;
205
+ info(message: string, context?: any): void;
206
+ debug(message: string, context?: any): void;
207
+ }
208
+ ```
209
+
210
+ **Responsabilidades:**
211
+ - Fornecer logging estruturado
212
+ - Suportar diferentes níveis de log
213
+ - Formatar mensagens consistentemente
214
+ - Incluir contexto relevante
215
+
216
+ ## Data Models
217
+
218
+ ### Configuration Schema
219
+
220
+ ```json
221
+ {
222
+ "url": "amqp://localhost:5672",
223
+ "dlq": {
224
+ "active": true,
225
+ "ttl": 300000,
226
+ "maxRetries": 3,
227
+ "retryDelay": 5000
228
+ },
229
+ "logging": {
230
+ "level": "info",
231
+ "format": "json"
232
+ }
233
+ }
234
+ ```
235
+
236
+ ### Message Format
237
+
238
+ ```typescript
239
+ interface RabbitMQMessage {
240
+ content: Buffer;
241
+ fields: {
242
+ deliveryTag: number;
243
+ redelivered: boolean;
244
+ exchange: string;
245
+ routingKey: string;
246
+ };
247
+ properties: {
248
+ contentType: string;
249
+ timestamp: number;
250
+ messageId: string;
251
+ headers: Record<string, any>;
252
+ };
253
+ }
254
+
255
+ interface ProcessedMessage {
256
+ payload: any;
257
+ metadata: {
258
+ exchange: string;
259
+ routingKey: string;
260
+ timestamp: number;
261
+ deliveryTag: number;
262
+ redelivered: boolean;
263
+ };
264
+ }
265
+ ```
266
+
267
+ ## Error Handling
268
+
269
+ ### Estratégia de Error Handling
270
+
271
+ 1. **Erros de Configuração**: Falha rápida na inicialização
272
+ 2. **Erros de Conexão**: Retry automático com backoff exponencial
273
+ 3. **Erros de Publicação**: Log e retorno de false
274
+ 4. **Erros de Processamento**: Roteamento para DLQ se habilitado
275
+
276
+ ### Tipos de Erro
277
+
278
+ ```typescript
279
+ class SdkRabbitmqError extends Error {
280
+ constructor(message: string, public code: string, public context?: any) {
281
+ super(message);
282
+ }
283
+ }
284
+
285
+ // Tipos específicos
286
+ class ConfigurationError extends SdkRabbitmqError {}
287
+ class ConnectionError extends SdkRabbitmqError {}
288
+ class PublishError extends SdkRabbitmqError {}
289
+ class SubscriptionError extends SdkRabbitmqError {}
290
+ ```
291
+
292
+ ### Reconexão Automática
293
+
294
+ ```mermaid
295
+ stateDiagram-v2
296
+ [*] --> Connected
297
+ Connected --> Disconnected : Connection Lost
298
+ Disconnected --> Reconnecting : Auto Retry
299
+ Reconnecting --> Connected : Success
300
+ Reconnecting --> Reconnecting : Retry (Backoff)
301
+ Reconnecting --> Failed : Max Retries
302
+ Failed --> [*]
303
+ ```
304
+
305
+ **Configuração de Retry:**
306
+ - Delay inicial: 1 segundo
307
+ - Multiplicador: 2x
308
+ - Delay máximo: 30 segundos
309
+ - Tentativas máximas: 10
310
+
311
+ ## Testing Strategy
312
+
313
+ ### Níveis de Teste
314
+
315
+ 1. **Unit Tests**
316
+ - Testes isolados para cada componente
317
+ - Mocks para dependências externas
318
+ - Cobertura de casos de erro
319
+
320
+ 2. **Integration Tests**
321
+ - Testes com RabbitMQ real (via Docker)
322
+ - Validação de fluxos end-to-end
323
+ - Testes de reconexão
324
+
325
+ 3. **Contract Tests**
326
+ - Validação da interface pública
327
+ - Compatibilidade de versões
328
+ - Validação de schemas
329
+
330
+ ### Ferramentas de Teste
331
+
332
+ - **Jest**: Framework de testes
333
+ - **Testcontainers**: RabbitMQ para testes de integração
334
+ - **Sinon**: Mocks e stubs
335
+ - **Supertest**: Testes de API (se aplicável)
336
+
337
+ ### Cenários de Teste Críticos
338
+
339
+ 1. **Singleton Behavior**
340
+ - Múltiplas instanciações retornam mesmo objeto
341
+ - Estado compartilhado entre instâncias
342
+
343
+ 2. **Reconexão Automática**
344
+ - Perda de conexão durante operações
345
+ - Retry com backoff exponencial
346
+ - Recuperação de estado após reconexão
347
+
348
+ 3. **DLQ Functionality**
349
+ - Roteamento de mensagens falhadas
350
+ - Configuração de TTL e retry
351
+ - Reprocessamento manual
352
+
353
+ 4. **Resource Auto-Creation**
354
+ - Criação automática de exchanges
355
+ - Criação automática de filas
356
+ - Configuração de bindings
357
+
358
+ 5. **Error Scenarios**
359
+ - Configuração inválida
360
+ - Parâmetros obrigatórios ausentes
361
+ - Falhas de rede
362
+ - Mensagens malformadas
363
+
364
+ ### Métricas de Qualidade
365
+
366
+ - Cobertura de código: > 90%
367
+ - Tempo de execução de testes: < 30 segundos
368
+ - Testes de integração: Ambiente isolado
369
+ - Performance: < 100ms para operações básicas
@@ -0,0 +1,97 @@
1
+ # Requirements Document
2
+
3
+ ## Introduction
4
+
5
+ O SDK RabbitMQ é uma biblioteca que fornece uma interface padronizada e simplificada para interação com RabbitMQ, implementando padrão singleton para garantir conexão única, reconexão automática, e abstraindo complexidades de canais, filas e DLQ (Dead Letter Queue).
6
+
7
+ ## Glossary
8
+
9
+ - **SDK_RabbitMQ**: O sistema principal que gerencia conexões e operações com RabbitMQ
10
+ - **Connection_Manager**: Componente responsável por gerenciar a conexão singleton com RabbitMQ
11
+ - **Message_Publisher**: Componente responsável por publicar mensagens
12
+ - **Message_Subscriber**: Componente responsável por consumir mensagens
13
+ - **DLQ_Handler**: Componente que gerencia Dead Letter Queues
14
+ - **Auto_Reconnection**: Funcionalidade que reconecta automaticamente quando a conexão é perdida
15
+ - **Resource_Creator**: Componente que cria exchanges e filas automaticamente se não existirem
16
+
17
+ ## Requirements
18
+
19
+ ### Requirement 1
20
+
21
+ **User Story:** Como desenvolvedor, eu quero definir configurações em um arquivo config.json na raiz do projeto, para que eu possa centralizar e versionar as configurações do RabbitMQ.
22
+
23
+ #### Acceptance Criteria
24
+
25
+ 1. THE SDK_RabbitMQ SHALL read configuration from config.json file located at project root
26
+ 2. WHEN config.json file does not exist, THE SDK_RabbitMQ SHALL throw configuration error with clear message
27
+ 3. THE SDK_RabbitMQ SHALL validate required configuration properties (url, dlq settings)
28
+ 4. WHEN configuration is invalid, THE SDK_RabbitMQ SHALL throw validation error with specific missing properties
29
+ 5. THE SDK_RabbitMQ SHALL support configuration schema with url and dlq object containing active boolean and additional DLQ settings
30
+
31
+ ### Requirement 2
32
+
33
+ **User Story:** Como desenvolvedor, eu quero instanciar o SDK com configurações e obter sempre a mesma instância conectada, para que eu possa usar o padrão singleton e evitar múltiplas conexões.
34
+
35
+ #### Acceptance Criteria
36
+
37
+ 1. WHEN a developer creates a new SdkRabbitmq instance, THE SDK_RabbitMQ SHALL return the same connected instance if one already exists
38
+ 2. WHEN the first SdkRabbitmq instance is created, THE SDK_RabbitMQ SHALL establish connection to RabbitMQ using configuration from config.json
39
+ 3. WHEN connection is established, THE SDK_RabbitMQ SHALL return a ready-to-use instance
40
+ 4. THE Connection_Manager SHALL maintain singleton pattern across multiple instantiation attempts
41
+
42
+ ### Requirement 3
43
+
44
+ **User Story:** Como desenvolvedor, eu quero publicar mensagens usando uma função simples publish(exchange, routingKey, payload), para que eu possa enviar eventos de forma padronizada.
45
+
46
+ #### Acceptance Criteria
47
+
48
+ 1. THE Message_Publisher SHALL provide a publish method that accepts exchange, routingKey, and payload parameters
49
+ 2. WHEN publish method is called, THE Message_Publisher SHALL validate that all required parameters are provided
50
+ 3. WHEN publishing a message, THE Message_Publisher SHALL convert payload to JSON format
51
+ 4. WHEN exchange does not exist, THE Resource_Creator SHALL create the exchange automatically
52
+ 5. WHEN publish operation fails, THE SDK_RabbitMQ SHALL log the failure details
53
+
54
+ ### Requirement 4
55
+
56
+ **User Story:** Como desenvolvedor, eu quero consumir mensagens usando uma função subscribe(exchange, queue, routingKey, callback), para que eu possa processar eventos de forma padronizada.
57
+
58
+ #### Acceptance Criteria
59
+
60
+ 1. THE Message_Subscriber SHALL provide a subscribe method that accepts exchange, queue, routingKey, and callback parameters
61
+ 2. WHEN subscribe method is called, THE Message_Subscriber SHALL validate that all required parameters are provided
62
+ 3. WHEN queue or exchange does not exist, THE Resource_Creator SHALL create them automatically
63
+ 4. WHEN message is received, THE Message_Subscriber SHALL parse JSON payload and invoke callback
64
+ 5. WHEN message processing fails, THE DLQ_Handler SHALL handle message according to DLQ configuration
65
+
66
+ ### Requirement 5
67
+
68
+ **User Story:** Como desenvolvedor, eu quero que o SDK mantenha conexão resiliente com reconexão automática, para que minha aplicação continue funcionando mesmo com instabilidades de rede.
69
+
70
+ #### Acceptance Criteria
71
+
72
+ 1. WHEN connection to RabbitMQ is lost, THE Auto_Reconnection SHALL attempt to reconnect automatically
73
+ 2. WHILE reconnection is in progress, THE SDK_RabbitMQ SHALL queue operations and execute them after reconnection
74
+ 3. WHEN reconnection fails, THE SDK_RabbitMQ SHALL log failure details and retry with exponential backoff
75
+ 4. THE Connection_Manager SHALL maintain only one active connection per SDK instance
76
+
77
+ ### Requirement 6
78
+
79
+ **User Story:** Como desenvolvedor, eu quero configurar Dead Letter Queue para reprocessamento de mensagens falhadas, para que eu possa tratar erros de processamento adequadamente.
80
+
81
+ #### Acceptance Criteria
82
+
83
+ 1. WHERE DLQ is active in configuration, THE DLQ_Handler SHALL create dead letter exchanges and queues
84
+ 2. WHEN message processing fails and DLQ is active, THE DLQ_Handler SHALL route failed messages to dead letter queue
85
+ 3. THE DLQ_Handler SHALL apply configured DLQ settings for message routing
86
+ 4. WHEN DLQ is not active, THE SDK_RabbitMQ SHALL acknowledge failed messages without reprocessing
87
+
88
+ ### Requirement 7
89
+
90
+ **User Story:** Como desenvolvedor, eu quero logs detalhados de operações e falhas, para que eu possa monitorar e debugar o comportamento do SDK.
91
+
92
+ #### Acceptance Criteria
93
+
94
+ 1. WHEN any operation is performed, THE SDK_RabbitMQ SHALL log operation details with configurable log level
95
+ 2. WHEN failures occur, THE SDK_RabbitMQ SHALL log error details including context and stack trace
96
+ 3. WHEN connection state changes, THE SDK_RabbitMQ SHALL log connection status updates
97
+ 4. THE SDK_RabbitMQ SHALL provide consistent log message formatting across all components