smart_message 0.0.10 → 0.0.12

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 (169) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/deploy-github-pages.yml +38 -0
  3. data/.gitignore +5 -0
  4. data/CHANGELOG.md +30 -0
  5. data/Gemfile.lock +35 -4
  6. data/README.md +169 -71
  7. data/Rakefile +29 -4
  8. data/docs/assets/images/ddq_architecture.svg +130 -0
  9. data/docs/assets/images/dlq_architecture.svg +115 -0
  10. data/docs/assets/images/enhanced-dual-publishing.svg +136 -0
  11. data/docs/assets/images/enhanced-fluent-api.svg +149 -0
  12. data/docs/assets/images/enhanced-microservices-routing.svg +115 -0
  13. data/docs/assets/images/enhanced-pattern-matching.svg +107 -0
  14. data/docs/assets/images/fluent-api-demo.svg +59 -0
  15. data/docs/assets/images/performance-comparison.svg +161 -0
  16. data/docs/assets/images/redis-basic-architecture.svg +53 -0
  17. data/docs/assets/images/redis-enhanced-architecture.svg +88 -0
  18. data/docs/assets/images/redis-queue-architecture.svg +101 -0
  19. data/docs/assets/images/smart_message.jpg +0 -0
  20. data/docs/assets/images/smart_message_walking.jpg +0 -0
  21. data/docs/assets/images/smartmessage_architecture_overview.svg +173 -0
  22. data/docs/assets/images/transport-comparison-matrix.svg +171 -0
  23. data/docs/assets/javascripts/mathjax.js +17 -0
  24. data/docs/assets/stylesheets/extra.css +51 -0
  25. data/docs/{addressing.md → core-concepts/addressing.md} +5 -7
  26. data/docs/{architecture.md → core-concepts/architecture.md} +78 -138
  27. data/docs/{dispatcher.md → core-concepts/dispatcher.md} +21 -21
  28. data/docs/{message_filtering.md → core-concepts/message-filtering.md} +2 -3
  29. data/docs/{message_processing.md → core-concepts/message-processing.md} +17 -17
  30. data/docs/{troubleshooting.md → development/troubleshooting.md} +7 -7
  31. data/docs/{examples.md → getting-started/examples.md} +115 -89
  32. data/docs/{getting-started.md → getting-started/quick-start.md} +47 -18
  33. data/docs/guides/redis-queue-getting-started.md +697 -0
  34. data/docs/guides/redis-queue-patterns.md +889 -0
  35. data/docs/guides/redis-queue-production.md +1091 -0
  36. data/docs/index.md +64 -0
  37. data/docs/{dead_letter_queue.md → reference/dead-letter-queue.md} +2 -3
  38. data/docs/{logging.md → reference/logging.md} +1 -1
  39. data/docs/{message_deduplication.md → reference/message-deduplication.md} +1 -0
  40. data/docs/{proc_handlers_summary.md → reference/proc-handlers.md} +7 -6
  41. data/docs/{serializers.md → reference/serializers.md} +3 -5
  42. data/docs/{transports.md → reference/transports.md} +133 -11
  43. data/docs/transports/memory-transport.md +374 -0
  44. data/docs/transports/redis-enhanced-transport.md +524 -0
  45. data/docs/transports/redis-queue-transport.md +1304 -0
  46. data/docs/transports/redis-transport-comparison.md +496 -0
  47. data/docs/transports/redis-transport.md +509 -0
  48. data/examples/README.md +98 -5
  49. data/examples/city_scenario/911_emergency_call_flow.svg +99 -0
  50. data/examples/city_scenario/README.md +515 -0
  51. data/examples/city_scenario/ai_visitor_intelligence_flow.svg +108 -0
  52. data/examples/city_scenario/citizen.rb +195 -0
  53. data/examples/city_scenario/city_diagram.svg +125 -0
  54. data/examples/city_scenario/common/health_monitor.rb +80 -0
  55. data/examples/city_scenario/common/logger.rb +30 -0
  56. data/examples/city_scenario/emergency_dispatch_center.rb +270 -0
  57. data/examples/city_scenario/fire_department.rb +446 -0
  58. data/examples/city_scenario/fire_emergency_flow.svg +95 -0
  59. data/examples/city_scenario/health_department.rb +100 -0
  60. data/examples/city_scenario/health_monitoring_system.svg +130 -0
  61. data/examples/city_scenario/house.rb +244 -0
  62. data/examples/city_scenario/local_bank.rb +217 -0
  63. data/examples/city_scenario/messages/emergency_911_message.rb +81 -0
  64. data/examples/city_scenario/messages/emergency_resolved_message.rb +43 -0
  65. data/examples/city_scenario/messages/fire_dispatch_message.rb +43 -0
  66. data/examples/city_scenario/messages/fire_emergency_message.rb +45 -0
  67. data/examples/city_scenario/messages/health_check_message.rb +22 -0
  68. data/examples/city_scenario/messages/health_status_message.rb +35 -0
  69. data/examples/city_scenario/messages/police_dispatch_message.rb +46 -0
  70. data/examples/city_scenario/messages/silent_alarm_message.rb +38 -0
  71. data/examples/city_scenario/police_department.rb +316 -0
  72. data/examples/city_scenario/redis_monitor.rb +129 -0
  73. data/examples/city_scenario/redis_stats.rb +743 -0
  74. data/examples/city_scenario/room_for_improvement.md +240 -0
  75. data/examples/city_scenario/security_emergency_flow.svg +95 -0
  76. data/examples/city_scenario/service_internal_architecture.svg +154 -0
  77. data/examples/city_scenario/smart_message_ai_agent.rb +364 -0
  78. data/examples/city_scenario/start_demo.sh +236 -0
  79. data/examples/city_scenario/stop_demo.sh +106 -0
  80. data/examples/city_scenario/visitor.rb +631 -0
  81. data/examples/{10_message_deduplication.rb → memory/01_message_deduplication_demo.rb} +1 -1
  82. data/examples/{09_dead_letter_queue_demo.rb → memory/02_dead_letter_queue_demo.rb} +13 -40
  83. data/examples/{01_point_to_point_orders.rb → memory/03_point_to_point_orders.rb} +1 -1
  84. data/examples/{02_publish_subscribe_events.rb → memory/04_publish_subscribe_events.rb} +2 -2
  85. data/examples/{03_many_to_many_chat.rb → memory/05_many_to_many_chat.rb} +4 -4
  86. data/examples/{show_me.rb → memory/06_pretty_print_demo.rb} +1 -1
  87. data/examples/{05_proc_handlers.rb → memory/07_proc_handlers_demo.rb} +2 -2
  88. data/examples/{06_custom_logger_example.rb → memory/08_custom_logger_demo.rb} +17 -14
  89. data/examples/{07_error_handling_scenarios.rb → memory/09_error_handling_demo.rb} +4 -4
  90. data/examples/{08_entity_addressing_basic.rb → memory/10_entity_addressing_basic.rb} +8 -8
  91. data/examples/{08_entity_addressing_with_filtering.rb → memory/11_entity_addressing_with_filtering.rb} +6 -6
  92. data/examples/{09_regex_filtering_microservices.rb → memory/12_regex_filtering_microservices.rb} +2 -2
  93. data/examples/{10_header_block_configuration.rb → memory/13_header_block_configuration.rb} +6 -6
  94. data/examples/{11_global_configuration_example.rb → memory/14_global_configuration_demo.rb} +19 -8
  95. data/examples/{show_logger.rb → memory/15_logger_demo.rb} +1 -1
  96. data/examples/memory/README.md +163 -0
  97. data/examples/memory/memory_transport_architecture.svg +90 -0
  98. data/examples/memory/point_to_point_pattern.svg +94 -0
  99. data/examples/memory/publish_subscribe_pattern.svg +125 -0
  100. data/examples/{04_redis_smart_home_iot.rb → redis/01_smart_home_iot_demo.rb} +5 -5
  101. data/examples/redis/README.md +230 -0
  102. data/examples/redis/alert_system_flow.svg +127 -0
  103. data/examples/redis/dashboard_status_flow.svg +107 -0
  104. data/examples/redis/device_command_flow.svg +113 -0
  105. data/examples/redis/redis_transport_architecture.svg +115 -0
  106. data/examples/{smart_home_iot_dataflow.md → redis/smart_home_iot_dataflow.md} +4 -116
  107. data/examples/redis/smart_home_system_architecture.svg +133 -0
  108. data/examples/redis_enhanced/README.md +319 -0
  109. data/examples/redis_enhanced/enhanced_01_basic_patterns.rb +233 -0
  110. data/examples/redis_enhanced/enhanced_02_fluent_api.rb +331 -0
  111. data/examples/redis_enhanced/enhanced_03_dual_publishing.rb +281 -0
  112. data/examples/redis_enhanced/enhanced_04_advanced_routing.rb +419 -0
  113. data/examples/redis_queue/01_basic_messaging.rb +221 -0
  114. data/examples/redis_queue/01_comprehensive_examples.rb +508 -0
  115. data/examples/redis_queue/02_pattern_routing.rb +405 -0
  116. data/examples/redis_queue/03_fluent_api.rb +422 -0
  117. data/examples/redis_queue/04_load_balancing.rb +486 -0
  118. data/examples/redis_queue/05_microservices.rb +735 -0
  119. data/examples/redis_queue/06_emergency_alerts.rb +777 -0
  120. data/examples/redis_queue/07_queue_management.rb +587 -0
  121. data/examples/redis_queue/README.md +366 -0
  122. data/examples/redis_queue/enhanced_01_basic_patterns.rb +233 -0
  123. data/examples/redis_queue/enhanced_02_fluent_api.rb +331 -0
  124. data/examples/redis_queue/enhanced_03_dual_publishing.rb +281 -0
  125. data/examples/redis_queue/enhanced_04_advanced_routing.rb +419 -0
  126. data/examples/redis_queue/redis_queue_architecture.svg +148 -0
  127. data/ideas/README.md +41 -0
  128. data/ideas/agents.md +1001 -0
  129. data/ideas/database_transport.md +980 -0
  130. data/ideas/improvement.md +359 -0
  131. data/ideas/meshage.md +1788 -0
  132. data/ideas/message_discovery.md +178 -0
  133. data/ideas/message_schema.md +1381 -0
  134. data/lib/smart_message/.idea/.gitignore +8 -0
  135. data/lib/smart_message/.idea/markdown.xml +6 -0
  136. data/lib/smart_message/.idea/misc.xml +4 -0
  137. data/lib/smart_message/.idea/modules.xml +8 -0
  138. data/lib/smart_message/.idea/smart_message.iml +16 -0
  139. data/lib/smart_message/.idea/vcs.xml +6 -0
  140. data/lib/smart_message/addressing.rb +15 -0
  141. data/lib/smart_message/base.rb +0 -2
  142. data/lib/smart_message/configuration.rb +1 -1
  143. data/lib/smart_message/logger.rb +15 -4
  144. data/lib/smart_message/plugins.rb +5 -2
  145. data/lib/smart_message/serializer.rb +14 -0
  146. data/lib/smart_message/transport/redis_enhanced_transport.rb +399 -0
  147. data/lib/smart_message/transport/redis_queue_transport.rb +555 -0
  148. data/lib/smart_message/transport/registry.rb +1 -0
  149. data/lib/smart_message/transport.rb +34 -1
  150. data/lib/smart_message/version.rb +1 -1
  151. data/lib/smart_message.rb +5 -52
  152. data/mkdocs.yml +184 -0
  153. data/p2p_plan.md +326 -0
  154. data/p2p_roadmap.md +287 -0
  155. data/smart_message.gemspec +2 -0
  156. data/smart_message.svg +51 -0
  157. metadata +170 -44
  158. data/docs/README.md +0 -57
  159. data/examples/dead_letters.jsonl +0 -12
  160. data/examples/temp.txt +0 -94
  161. data/examples/tmux_chat/README.md +0 -283
  162. data/examples/tmux_chat/bot_agent.rb +0 -278
  163. data/examples/tmux_chat/human_agent.rb +0 -199
  164. data/examples/tmux_chat/room_monitor.rb +0 -160
  165. data/examples/tmux_chat/shared_chat_system.rb +0 -328
  166. data/examples/tmux_chat/start_chat_demo.sh +0 -190
  167. data/examples/tmux_chat/stop_chat_demo.sh +0 -22
  168. /data/docs/{properties.md → core-concepts/properties.md} +0 -0
  169. /data/docs/{ideas_to_think_about.md → development/ideas.md} +0 -0
@@ -0,0 +1,366 @@
1
+ # Redis Queue Transport Examples
2
+
3
+ This directory contains comprehensive examples demonstrating all capabilities of the Redis Queue Transport for SmartMessage. Each example builds upon the previous ones, showcasing different aspects of the transport's functionality.
4
+
5
+ ## 🚀 Quick Start
6
+
7
+ Before running the examples, ensure you have:
8
+
9
+ 1. **Redis server running** on localhost:6379
10
+ 2. **SmartMessage gem** installed with Redis Queue Transport
11
+ 3. **Ruby 2.7+** installed
12
+
13
+ ```bash
14
+ # Start Redis (if not already running)
15
+ redis-server
16
+
17
+ # Run any example
18
+ ruby 01_basic_messaging.rb
19
+ ```
20
+
21
+ ## 📚 Examples Overview
22
+
23
+ ### 1. Basic Messaging (`01_basic_messaging.rb`)
24
+ **Duration: ~30 seconds**
25
+
26
+ Demonstrates fundamental Redis Queue Transport operations:
27
+ - Simple message publishing and subscription
28
+ - Multiple message types (Welcome, Order, Alert)
29
+ - Basic queue-based reliable delivery
30
+ - Performance testing with rapid message publishing
31
+ - Message processing with timestamps
32
+
33
+ **Key Concepts:**
34
+ - Queue-based messaging vs traditional pub/sub
35
+ - Automatic message serialization
36
+ - Reliable message delivery
37
+ - High-throughput publishing
38
+
39
+ ### 2. Pattern Routing (`02_pattern_routing.rb`)
40
+ **Duration: ~45 seconds**
41
+
42
+ Advanced pattern-based message routing capabilities:
43
+ - RabbitMQ-style wildcard patterns (`#`, `*`)
44
+ - FROM/TO-based message routing
45
+ - Message type filtering
46
+ - Broadcast and targeted messaging
47
+ - Complex multi-pattern subscriptions
48
+
49
+ **Key Concepts:**
50
+ - Enhanced routing keys: `namespace.message_type.from_uuid.to_uuid`
51
+ - Pattern matching with `#.*.service_name`
52
+ - Multi-service message coordination
53
+ - Surgical message precision
54
+
55
+ ### 3. Fluent API (`03_fluent_api.rb`)
56
+ **Duration: ~40 seconds**
57
+
58
+ Fluent interface for building complex subscriptions:
59
+ - Chainable subscription builders
60
+ - Dynamic pattern construction
61
+ - Runtime subscription modification
62
+ - Complex criteria combinations
63
+ - Pattern inspection and debugging
64
+
65
+ **Key Concepts:**
66
+ - Fluent API: `transport.where.from().to().subscribe`
67
+ - Dynamic subscription building
68
+ - Type-safe subscription construction
69
+ - Pattern generation and analysis
70
+
71
+ ### 4. Load Balancing (`04_load_balancing.rb`)
72
+ **Duration: ~60 seconds**
73
+
74
+ Consumer groups and load distribution:
75
+ - Multiple workers sharing queues
76
+ - Consumer group management
77
+ - High-volume load testing
78
+ - Priority-based routing
79
+ - Mixed-performance worker handling
80
+
81
+ **Key Concepts:**
82
+ - Consumer groups for work distribution
83
+ - Redis BRPOP for automatic load balancing
84
+ - Round-robin task distribution
85
+ - Fault-tolerant worker coordination
86
+
87
+ ### 5. Microservices Architecture (`05_microservices.rb`)
88
+ **Duration: ~75 seconds**
89
+
90
+ Complete microservices communication patterns:
91
+ - Service-to-service messaging
92
+ - Request/response patterns
93
+ - Event-driven architecture
94
+ - API Gateway coordination
95
+ - Multi-service workflows
96
+
97
+ **Key Concepts:**
98
+ - Microservice message patterns
99
+ - Asynchronous service communication
100
+ - Event bus implementation
101
+ - Service isolation and independence
102
+ - End-to-end workflow orchestration
103
+
104
+ ### 6. Emergency Alert System (`06_emergency_alerts.rb`)
105
+ **Duration: ~90 seconds**
106
+
107
+ Real-world emergency response coordination:
108
+ - Multi-agency alert distribution
109
+ - Severity-based routing
110
+ - Citizen reporting integration
111
+ - Real-time response tracking
112
+ - Mass casualty incident handling
113
+
114
+ **Key Concepts:**
115
+ - Critical system reliability
116
+ - Multi-stakeholder coordination
117
+ - Geographic-based routing
118
+ - Priority escalation systems
119
+ - Real-time status tracking
120
+
121
+ ### 7. Queue Management (`07_queue_management.rb`)
122
+ **Duration: ~60 seconds**
123
+
124
+ Administrative and monitoring capabilities:
125
+ - Real-time queue statistics
126
+ - Health monitoring and alerting
127
+ - Performance metrics analysis
128
+ - Administrative operations
129
+ - System optimization recommendations
130
+
131
+ **Key Concepts:**
132
+ - Queue monitoring and administration
133
+ - Performance optimization
134
+ - System health analysis
135
+ - Resource utilization tracking
136
+ - Automated recommendations
137
+
138
+ ## 🎯 Running Examples
139
+
140
+ ### Run Individual Examples
141
+ ```bash
142
+ # Basic functionality
143
+ ruby 01_basic_messaging.rb
144
+
145
+ # Advanced routing
146
+ ruby 02_pattern_routing.rb
147
+
148
+ # Fluent API usage
149
+ ruby 03_fluent_api.rb
150
+
151
+ # Load balancing demo
152
+ ruby 04_load_balancing.rb
153
+
154
+ # Microservices architecture
155
+ ruby 05_microservices.rb
156
+
157
+ # Emergency alert system
158
+ ruby 06_emergency_alerts.rb
159
+
160
+ # Queue management
161
+ ruby 07_queue_management.rb
162
+ ```
163
+
164
+ ### Run All Examples Sequentially
165
+ ```bash
166
+ # Run all examples with delays
167
+ for file in 0{1..7}_*.rb; do
168
+ echo "Running $file..."
169
+ ruby "$file"
170
+ echo "Completed $file. Press Enter to continue..."
171
+ read
172
+ done
173
+ ```
174
+
175
+ ### Clean Redis Between Examples
176
+ Each example uses a different Redis database (1-7) to avoid conflicts, but you can clean up:
177
+
178
+ ```bash
179
+ # Clean all example databases
180
+ redis-cli FLUSHALL
181
+
182
+ # Or clean specific database
183
+ redis-cli -n 1 FLUSHDB # Clean database 1
184
+ ```
185
+
186
+ ## 📊 Example Comparison Matrix
187
+
188
+ | Feature | Example | Database | Duration | Complexity | Prerequisites |
189
+ |---------|---------|----------|----------|------------|---------------|
190
+ | **Basic Messaging** | 01 | 1 | 30s | Beginner | None |
191
+ | **Pattern Routing** | 02 | 2 | 45s | Intermediate | Understand basic messaging |
192
+ | **Fluent API** | 03 | 3 | 40s | Intermediate | Pattern routing knowledge |
193
+ | **Load Balancing** | 04 | 4 | 60s | Advanced | Multi-threading concepts |
194
+ | **Microservices** | 05 | 5 | 75s | Advanced | Service architecture |
195
+ | **Emergency Alerts** | 06 | 6 | 90s | Expert | Complex systems |
196
+ | **Queue Management** | 07 | 7 | 60s | Expert | All previous examples |
197
+
198
+ ## 🔧 Configuration Examples
199
+
200
+ ### Transport Configuration Patterns
201
+
202
+ ```ruby
203
+ # Basic configuration
204
+ SmartMessage.configure do |config|
205
+ config.transport = :redis_queue
206
+ config.transport_options = {
207
+ url: 'redis://localhost:6379',
208
+ db: 1,
209
+ queue_prefix: 'my_app',
210
+ consumer_group: 'workers'
211
+ }
212
+ end
213
+
214
+ # High-performance configuration
215
+ transport = SmartMessage::Transport::RedisQueueTransport.new(
216
+ url: 'redis://localhost:6379',
217
+ db: 0,
218
+ queue_prefix: 'high_perf',
219
+ consumer_group: 'fast_workers',
220
+ block_time: 100, # Fast polling
221
+ max_queue_length: 50000 # Large queues
222
+ )
223
+
224
+ # Development configuration
225
+ transport = SmartMessage::Transport::RedisQueueTransport.new(
226
+ url: 'redis://localhost:6379',
227
+ db: 15, # Test database
228
+ queue_prefix: 'dev',
229
+ consumer_group: 'dev_workers',
230
+ block_time: 1000, # Slower polling for debugging
231
+ max_retries: 1 # Quick failure for development
232
+ )
233
+ ```
234
+
235
+ ### Message Class Patterns
236
+
237
+ ```ruby
238
+ # Basic message
239
+ class SimpleMessage < SmartMessage::Base
240
+ transport :redis_queue
241
+ property :content, required: true
242
+ end
243
+
244
+ # Enhanced message with routing
245
+ class RoutedMessage < SmartMessage::Base
246
+ transport :redis_queue, {
247
+ queue_prefix: 'routed_msgs',
248
+ consumer_group: 'routed_workers'
249
+ }
250
+
251
+ property :data, required: true
252
+ property :priority, default: 'normal'
253
+
254
+ def process
255
+ puts "Processing: #{data} [#{priority}]"
256
+ end
257
+ end
258
+
259
+ # Service message with validation
260
+ class ServiceMessage < SmartMessage::Base
261
+ transport :redis_queue
262
+
263
+ property :service_name, required: true
264
+ property :operation, required: true
265
+ property :payload, default: {}
266
+
267
+ validate :service_name, inclusion: ['user_service', 'order_service']
268
+ validate :operation, format: /\A[a-z_]+\z/
269
+
270
+ def process
271
+ # Service-specific processing
272
+ send("handle_#{operation}")
273
+ end
274
+ end
275
+ ```
276
+
277
+ ## 🚨 Troubleshooting
278
+
279
+ ### Common Issues
280
+
281
+ 1. **Redis Connection Failed**
282
+ ```
283
+ Error: Redis::CannotConnectError
284
+ Solution: Ensure Redis is running on localhost:6379
285
+ ```
286
+
287
+ 2. **Queue Not Processing Messages**
288
+ ```
289
+ Problem: Messages published but not processed
290
+ Solution: Check that subscribers are properly set up with matching patterns
291
+ ```
292
+
293
+ 3. **Pattern Not Matching**
294
+ ```
295
+ Problem: Subscription pattern doesn't match published messages
296
+ Solution: Verify routing key format and wildcard usage
297
+ ```
298
+
299
+ ### Debugging Tips
300
+
301
+ ```ruby
302
+ # Enable debug logging
303
+ transport = SmartMessage::Transport::RedisQueueTransport.new(
304
+ url: 'redis://localhost:6379',
305
+ debug: true # Enable debug output
306
+ )
307
+
308
+ # Check queue statistics
309
+ stats = transport.queue_stats
310
+ puts "Queue stats: #{stats}"
311
+
312
+ # Inspect routing table
313
+ routing_table = transport.routing_table
314
+ puts "Routing: #{routing_table}"
315
+
316
+ # Monitor Redis directly
317
+ # redis-cli MONITOR # Shows all Redis commands
318
+ ```
319
+
320
+ ## 📈 Performance Guidelines
321
+
322
+ ### Message Publishing
323
+ - **High throughput**: Batch publish multiple messages
324
+ - **Low latency**: Use smaller queue prefixes
325
+ - **Reliability**: Enable persistence in Redis configuration
326
+
327
+ ### Consumer Configuration
328
+ - **CPU intensive**: Fewer consumers per core
329
+ - **I/O intensive**: More consumers per core
330
+ - **Memory intensive**: Monitor queue lengths
331
+
332
+ ### Queue Management
333
+ - **Monitor queue lengths**: Set up alerts for queue buildup
334
+ - **Consumer scaling**: Add/remove consumers based on load
335
+ - **Pattern optimization**: Use specific patterns when possible
336
+
337
+ ## 🔗 Related Documentation
338
+
339
+ - [Redis Queue Transport API Documentation](../REDIS_QUEUE_TRANSPORT.md)
340
+ - [Redis Queue Architecture](../REDIS_QUEUE_ARCHITECTURE.md)
341
+ - [SmartMessage Core Documentation](../README.md)
342
+ - [Transport Comparison Guide](../REDIS_VS_RABBITMQ_COMPARISON.md)
343
+
344
+ ## 💡 Best Practices
345
+
346
+ 1. **Start with basic examples** and progress to advanced ones
347
+ 2. **Use different Redis databases** for different environments
348
+ 3. **Monitor queue health** regularly in production
349
+ 4. **Test failure scenarios** with your message handlers
350
+ 5. **Implement proper error handling** in message processors
351
+ 6. **Use meaningful queue prefixes** for organization
352
+ 7. **Document your routing patterns** for team members
353
+
354
+ ## 🎓 Learning Path
355
+
356
+ For best understanding, run examples in this order:
357
+
358
+ 1. **Foundations**: 01_basic_messaging.rb
359
+ 2. **Routing**: 02_pattern_routing.rb
360
+ 3. **API Design**: 03_fluent_api.rb
361
+ 4. **Scalability**: 04_load_balancing.rb
362
+ 5. **Architecture**: 05_microservices.rb
363
+ 6. **Real-world Application**: 06_emergency_alerts.rb
364
+ 7. **Operations**: 07_queue_management.rb
365
+
366
+ Each example builds upon concepts from previous ones, providing a comprehensive learning experience for Redis Queue Transport mastery.
@@ -0,0 +1,233 @@
1
+ #!/usr/bin/env ruby
2
+ # examples/redis_queue/enhanced_01_basic_patterns.rb
3
+ # Redis Enhanced Transport - Basic Pattern Subscriptions Demo
4
+
5
+ require_relative '../../lib/smart_message'
6
+ require 'smart_message/transport/redis_enhanced_transport'
7
+
8
+ puts "🚀 Redis Enhanced Transport - Basic Pattern Subscriptions Demo"
9
+ puts "=" * 60
10
+
11
+ # Create enhanced Redis transport instance
12
+ transport = SmartMessage::Transport::RedisEnhancedTransport.new(
13
+ url: 'redis://localhost:6379',
14
+ db: 2, # Use database 2 for enhanced transport examples
15
+ auto_subscribe: true
16
+ )
17
+
18
+ #==============================================================================
19
+ # Define Message Classes
20
+ #==============================================================================
21
+
22
+ class OrderMessage < SmartMessage::Base
23
+ from 'e-commerce-api'
24
+ to 'order-processor'
25
+
26
+ transport transport
27
+ serializer SmartMessage::Serializer::Json.new
28
+
29
+ property :order_id, required: true
30
+ property :customer_id, required: true
31
+ property :amount, required: true
32
+ property :items, default: []
33
+
34
+ def self.process(wrapper)
35
+ header, payload = wrapper.split
36
+ data = JSON.parse(payload)
37
+
38
+ puts "📦 [OrderMessage] Processing order #{data['order_id']}"
39
+ puts " Customer: #{data['customer_id']}, Amount: $#{data['amount']}"
40
+ puts " From: #{header.from} → To: #{header.to}"
41
+ puts " Enhanced Channel: ordermessage.#{header.from.gsub('-', '_')}.#{header.to.gsub('-', '_')}"
42
+ puts
43
+ end
44
+ end
45
+
46
+ class PaymentMessage < SmartMessage::Base
47
+ from 'payment-gateway'
48
+ to 'bank-service'
49
+
50
+ transport transport
51
+ serializer SmartMessage::Serializer::Json.new
52
+
53
+ property :payment_id, required: true
54
+ property :amount, required: true
55
+ property :currency, default: 'USD'
56
+
57
+ def self.process(wrapper)
58
+ header, payload = wrapper.split
59
+ data = JSON.parse(payload)
60
+
61
+ puts "💳 [PaymentMessage] Processing payment #{data['payment_id']}"
62
+ puts " Amount: #{data['amount']} #{data['currency']}"
63
+ puts " From: #{header.from} → To: #{header.to}"
64
+ puts " Enhanced Channel: paymentmessage.#{header.from.gsub('-', '_')}.#{header.to.gsub('-', '_')}"
65
+ puts
66
+ end
67
+ end
68
+
69
+ class AlertMessage < SmartMessage::Base
70
+ from 'monitoring-service'
71
+
72
+ transport transport
73
+ serializer SmartMessage::Serializer::Json.new
74
+
75
+ property :alert_type, required: true
76
+ property :severity, required: true
77
+ property :message, required: true
78
+
79
+ def self.process(wrapper)
80
+ header, payload = wrapper.split
81
+ data = JSON.parse(payload)
82
+
83
+ puts "🚨 [AlertMessage] #{data['severity'].upcase} ALERT: #{data['alert_type']}"
84
+ puts " Message: #{data['message']}"
85
+ puts " From: #{header.from} → To: #{header.to || 'broadcast'}"
86
+ puts " Enhanced Channel: alertmessage.#{header.from.gsub('-', '_')}.#{(header.to || 'broadcast').gsub('-', '_')}"
87
+ puts
88
+ end
89
+ end
90
+
91
+ #==============================================================================
92
+ # Demonstration Functions
93
+ #==============================================================================
94
+
95
+ def demo_basic_pattern_subscriptions(transport)
96
+ puts "🔍 Setting up basic pattern subscriptions..."
97
+ puts
98
+
99
+ # Subscribe to specific message patterns
100
+ transport.subscribe_pattern("ordermessage.*.*") # All order messages
101
+ transport.subscribe_pattern("*.payment_gateway.*") # All messages from payment gateway
102
+ transport.subscribe_pattern("*.*.bank_service") # All messages to bank service
103
+ transport.subscribe_pattern("alertmessage.*.*") # All alert messages
104
+
105
+ puts "✅ Subscribed to patterns:"
106
+ puts " • ordermessage.*.* (all order messages)"
107
+ puts " • *.payment_gateway.* (all from payment gateway)"
108
+ puts " • *.*.bank_service (all to bank service)"
109
+ puts " • alertmessage.*.* (all alert messages)"
110
+ puts
111
+ end
112
+
113
+ def demo_convenience_subscriptions(transport)
114
+ puts "🎯 Setting up convenience method subscriptions..."
115
+ puts
116
+
117
+ # Use convenience methods
118
+ transport.subscribe_to_recipient('order-processor')
119
+ transport.subscribe_from_sender('monitoring-service')
120
+ transport.subscribe_to_type('PaymentMessage')
121
+ transport.subscribe_to_alerts # Subscribes to emergency/alert/alarm/critical patterns
122
+ transport.subscribe_to_broadcasts
123
+
124
+ puts "✅ Convenience subscriptions added:"
125
+ puts " • subscribe_to_recipient('order-processor')"
126
+ puts " • subscribe_from_sender('monitoring-service')"
127
+ puts " • subscribe_to_type('PaymentMessage')"
128
+ puts " • subscribe_to_alerts (emergency/alert/alarm/critical patterns)"
129
+ puts " • subscribe_to_broadcasts"
130
+ puts
131
+ end
132
+
133
+ def publish_sample_messages
134
+ puts "📤 Publishing sample messages..."
135
+ puts
136
+
137
+ # Publish order message
138
+ order = OrderMessage.new(
139
+ order_id: 'ORD-001',
140
+ customer_id: 'CUST-123',
141
+ amount: 99.99,
142
+ items: ['Widget A', 'Widget B']
143
+ )
144
+ order.publish
145
+
146
+ # Publish payment message
147
+ payment = PaymentMessage.new(
148
+ payment_id: 'PAY-001',
149
+ amount: 99.99,
150
+ currency: 'USD'
151
+ )
152
+ payment.publish
153
+
154
+ # Publish alert message (broadcast)
155
+ alert = AlertMessage.new(
156
+ alert_type: 'system_overload',
157
+ severity: 'warning',
158
+ message: 'CPU usage exceeding 80%'
159
+ )
160
+ alert.to(nil) # Make it a broadcast
161
+ alert.publish
162
+
163
+ # Publish targeted alert
164
+ critical_alert = AlertMessage.new(
165
+ alert_type: 'database_connection_lost',
166
+ severity: 'critical',
167
+ message: 'Primary database connection failed'
168
+ )
169
+ critical_alert.to('ops-team')
170
+ critical_alert.publish
171
+
172
+ puts "✅ Published 4 sample messages"
173
+ puts
174
+ end
175
+
176
+ #==============================================================================
177
+ # Main Demonstration
178
+ #==============================================================================
179
+
180
+ begin
181
+ puts "🔧 Checking Redis connection..."
182
+ unless transport.connected?
183
+ puts "❌ Redis not available. Please start Redis server:"
184
+ puts " brew services start redis # macOS"
185
+ puts " sudo service redis start # Linux"
186
+ exit 1
187
+ end
188
+ puts "✅ Connected to Redis"
189
+ puts
190
+
191
+ # Set up subscriptions
192
+ demo_basic_pattern_subscriptions(transport)
193
+ demo_convenience_subscriptions(transport)
194
+
195
+ # Subscribe message classes to their handlers
196
+ OrderMessage.subscribe
197
+ PaymentMessage.subscribe
198
+ AlertMessage.subscribe
199
+
200
+ puts "⏳ Waiting for subscriptions to be established..."
201
+ sleep 1
202
+
203
+ # Publish sample messages
204
+ publish_sample_messages
205
+
206
+ puts "⏳ Processing messages (waiting 3 seconds)..."
207
+ sleep 3
208
+
209
+ puts "📊 Pattern Subscription Status:"
210
+ pattern_subscriptions = transport.instance_variable_get(:@pattern_subscriptions)
211
+ if pattern_subscriptions
212
+ pattern_subscriptions.each do |pattern|
213
+ puts " • #{pattern}"
214
+ end
215
+ else
216
+ puts " No pattern subscriptions found"
217
+ end
218
+ puts
219
+
220
+ puts "🎉 Demo completed! Check the output above to see how messages were routed."
221
+ puts "💡 Notice how messages are published to both original channels (OrderMessage)"
222
+ puts " and enhanced channels (ordermessage.e_commerce_api.order_processor)"
223
+
224
+ rescue Interrupt
225
+ puts "\n👋 Demo interrupted by user"
226
+ rescue => e
227
+ puts "💥 Error: #{e.message}"
228
+ puts e.backtrace[0..3]
229
+ ensure
230
+ puts "\n🧹 Cleaning up..."
231
+ transport&.disconnect
232
+ puts "✅ Disconnected from Redis"
233
+ end