smart_message 0.0.1

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 (53) hide show
  1. checksums.yaml +7 -0
  2. data/.envrc +3 -0
  3. data/.gitignore +8 -0
  4. data/.travis.yml +7 -0
  5. data/CHANGELOG.md +100 -0
  6. data/COMMITS.md +196 -0
  7. data/Gemfile +6 -0
  8. data/Gemfile.lock +71 -0
  9. data/README.md +303 -0
  10. data/Rakefile +10 -0
  11. data/bin/console +14 -0
  12. data/bin/setup +8 -0
  13. data/docs/README.md +52 -0
  14. data/docs/architecture.md +370 -0
  15. data/docs/dispatcher.md +593 -0
  16. data/docs/examples.md +808 -0
  17. data/docs/getting-started.md +235 -0
  18. data/docs/ideas_to_think_about.md +329 -0
  19. data/docs/serializers.md +575 -0
  20. data/docs/transports.md +501 -0
  21. data/docs/troubleshooting.md +582 -0
  22. data/examples/01_point_to_point_orders.rb +200 -0
  23. data/examples/02_publish_subscribe_events.rb +364 -0
  24. data/examples/03_many_to_many_chat.rb +608 -0
  25. data/examples/README.md +335 -0
  26. data/examples/tmux_chat/README.md +283 -0
  27. data/examples/tmux_chat/bot_agent.rb +272 -0
  28. data/examples/tmux_chat/human_agent.rb +197 -0
  29. data/examples/tmux_chat/room_monitor.rb +158 -0
  30. data/examples/tmux_chat/shared_chat_system.rb +295 -0
  31. data/examples/tmux_chat/start_chat_demo.sh +190 -0
  32. data/examples/tmux_chat/stop_chat_demo.sh +22 -0
  33. data/lib/simple_stats.rb +57 -0
  34. data/lib/smart_message/base.rb +284 -0
  35. data/lib/smart_message/dispatcher/.keep +0 -0
  36. data/lib/smart_message/dispatcher.rb +146 -0
  37. data/lib/smart_message/errors.rb +29 -0
  38. data/lib/smart_message/header.rb +20 -0
  39. data/lib/smart_message/logger/base.rb +8 -0
  40. data/lib/smart_message/logger.rb +7 -0
  41. data/lib/smart_message/serializer/base.rb +23 -0
  42. data/lib/smart_message/serializer/json.rb +22 -0
  43. data/lib/smart_message/serializer.rb +10 -0
  44. data/lib/smart_message/transport/base.rb +85 -0
  45. data/lib/smart_message/transport/memory_transport.rb +69 -0
  46. data/lib/smart_message/transport/registry.rb +59 -0
  47. data/lib/smart_message/transport/stdout_transport.rb +62 -0
  48. data/lib/smart_message/transport.rb +41 -0
  49. data/lib/smart_message/version.rb +7 -0
  50. data/lib/smart_message/wrapper.rb +43 -0
  51. data/lib/smart_message.rb +54 -0
  52. data/smart_message.gemspec +53 -0
  53. metadata +252 -0
@@ -0,0 +1,335 @@
1
+ # SmartMessage Examples
2
+
3
+ This directory contains example applications that demonstrate different messaging patterns and topologies using the SmartMessage Ruby gem. Each example is a complete, runnable program that showcases real-world usage scenarios.
4
+
5
+ ## Quick Start
6
+
7
+ To run any example:
8
+
9
+ ```bash
10
+ cd examples
11
+ ruby 01_point_to_point_orders.rb
12
+ ruby 02_publish_subscribe_events.rb
13
+ ruby 03_many_to_many_chat.rb
14
+ ```
15
+
16
+ ## Examples Overview
17
+
18
+ ### 1. Point-to-Point Messaging (1-to-1)
19
+ **File:** `01_point_to_point_orders.rb`
20
+
21
+ **Scenario:** E-commerce order processing system with bidirectional communication between OrderService and PaymentService.
22
+
23
+ **Key Features:**
24
+ - Request-response messaging pattern
25
+ - Error handling and payment validation
26
+ - JSON serialization of complex business objects
27
+ - Service-to-service communication
28
+
29
+ **Messages Used:**
30
+ - `OrderMessage` - Represents customer orders
31
+ - `PaymentResponseMessage` - Payment processing results
32
+
33
+ **Services:**
34
+ - `OrderService` - Creates and publishes orders
35
+ - `PaymentService` - Processes payments and sends responses
36
+
37
+ **What You'll Learn:**
38
+ - How to implement point-to-point messaging
39
+ - Bidirectional communication patterns
40
+ - Message properties and validation
41
+ - Service decoupling with SmartMessage
42
+
43
+ ---
44
+
45
+ ### 2. Publish-Subscribe Messaging (1-to-Many)
46
+ **File:** `02_publish_subscribe_events.rb`
47
+
48
+ **Scenario:** User management system that broadcasts events to multiple interested services (email, SMS, audit logging).
49
+
50
+ **Key Features:**
51
+ - Event-driven architecture
52
+ - Multiple subscribers to single event stream
53
+ - Different services handling events differently
54
+ - Audit logging and compliance
55
+
56
+ **Messages Used:**
57
+ - `UserEventMessage` - User lifecycle events (registration, login, password change)
58
+
59
+ **Services:**
60
+ - `UserManager` - Event publisher for user activities
61
+ - `EmailService` - Sends email notifications
62
+ - `SMSService` - Sends SMS alerts for security events
63
+ - `AuditService` - Logs all events for compliance
64
+
65
+ **What You'll Learn:**
66
+ - Event-driven system design
67
+ - Publish-subscribe patterns
68
+ - Service autonomy and specialization
69
+ - Audit and monitoring capabilities
70
+
71
+ ---
72
+
73
+ ### 3. Many-to-Many Messaging (Service Mesh)
74
+ **File:** `03_many_to_many_chat.rb`
75
+
76
+ **Scenario:** Distributed chat system where multiple agents (humans and bots) communicate in multiple rooms with dynamic routing.
77
+
78
+ **Key Features:**
79
+ - Complex multi-agent communication
80
+ - Dynamic subscription management
81
+ - Multiple message types and routing
82
+ - Service discovery and capabilities
83
+
84
+ **Messages Used:**
85
+ - `ChatMessage` - User and bot chat messages
86
+ - `BotCommandMessage` - Commands directed to bots
87
+ - `SystemNotificationMessage` - System events and notifications
88
+
89
+ **Services:**
90
+ - `HumanChatAgent` - Represents human users
91
+ - `BotAgent` - Automated agents with capabilities
92
+ - `RoomManager` - Manages chat rooms and membership
93
+
94
+ **What You'll Learn:**
95
+ - Many-to-many communication patterns
96
+ - Dynamic message routing
97
+ - Service capabilities and discovery
98
+ - Complex subscription management
99
+
100
+ ## Message Patterns Demonstrated
101
+
102
+ ### Request-Response Pattern
103
+ ```ruby
104
+ # Publisher sends request
105
+ order = OrderMessage.new(customer_id: "123", amount: 99.99)
106
+ order.publish
107
+
108
+ # Subscriber processes and responds
109
+ PaymentResponseMessage.new(order_id: order.order_id, status: "success").publish
110
+ ```
111
+
112
+ ### Event Broadcasting Pattern
113
+ ```ruby
114
+ # Single event publisher
115
+ UserEventMessage.new(event_type: "user_registered", user_id: "123").publish
116
+
117
+ # Multiple subscribers process the same event
118
+ EmailService.handle_user_event # Sends welcome email
119
+ SMSService.handle_user_event # No action for registration
120
+ AuditService.handle_user_event # Logs the event
121
+ ```
122
+
123
+ ### Dynamic Subscription Pattern
124
+ ```ruby
125
+ # Agents can join/leave message streams dynamically
126
+ alice.join_room('general') # Start receiving messages
127
+ alice.leave_room('general') # Stop receiving messages
128
+ ```
129
+
130
+ ## Transport Configurations
131
+
132
+ All examples use `StdoutTransport` with loopback enabled for demonstration purposes:
133
+
134
+ ```ruby
135
+ config do
136
+ transport SmartMessage::Transport::StdoutTransport.new(loopback: true)
137
+ serializer SmartMessage::Serializer::JSON.new
138
+ end
139
+ ```
140
+
141
+ **For Production Use:**
142
+ - Replace `StdoutTransport` with production transports (Redis, RabbitMQ, Kafka)
143
+ - Configure appropriate serializers for your data needs
144
+ - Add proper error handling and logging
145
+ - Implement monitoring and metrics
146
+
147
+ ## Advanced Features Shown
148
+
149
+ ### Message Properties and Headers
150
+ ```ruby
151
+ property :order_id
152
+ property :amount
153
+ property :currency, default: 'USD'
154
+ property :items
155
+ ```
156
+
157
+ ### Custom Message Processing
158
+ ```ruby
159
+ def self.process(message_header, message_payload)
160
+ # Custom business logic here
161
+ data = JSON.parse(message_payload)
162
+ handle_business_logic(data)
163
+ end
164
+ ```
165
+
166
+ ### Service-Specific Subscriptions
167
+ ```ruby
168
+ # Subscribe with custom processor method
169
+ OrderMessage.subscribe('PaymentService.process_order')
170
+ ```
171
+
172
+ ### Message Metadata and Context
173
+ ```ruby
174
+ metadata: {
175
+ source: 'web_registration',
176
+ ip_address: request.ip,
177
+ user_agent: request.user_agent
178
+ }
179
+ ```
180
+
181
+ ## Common Patterns
182
+
183
+ ### Service Registration Pattern
184
+ ```ruby
185
+ class MyService
186
+ def initialize
187
+ MessageType.subscribe('MyService.handle_message')
188
+ end
189
+
190
+ def self.handle_message(header, payload)
191
+ service = new
192
+ service.process_message(header, payload)
193
+ end
194
+ end
195
+ ```
196
+
197
+ ### Message Filtering Pattern
198
+ ```ruby
199
+ def handle_message(header, payload)
200
+ data = JSON.parse(payload)
201
+
202
+ # Only process messages for rooms we're in
203
+ return unless @active_rooms.include?(data['room_id'])
204
+
205
+ # Process the message
206
+ process_filtered_message(data)
207
+ end
208
+ ```
209
+
210
+ ### Response Pattern
211
+ ```ruby
212
+ def process_request(request_data)
213
+ # Process the request
214
+ result = perform_business_logic(request_data)
215
+
216
+ # Send response
217
+ ResponseMessage.new(
218
+ request_id: request_data['id'],
219
+ status: result.success? ? 'success' : 'error',
220
+ data: result.data
221
+ ).publish
222
+ end
223
+ ```
224
+
225
+ ## Testing the Examples
226
+
227
+ Each example includes:
228
+ - Comprehensive output showing message flow
229
+ - Error scenarios and handling
230
+ - Multiple service interactions
231
+ - Clear demonstration of the messaging pattern
232
+
233
+ ### Running Examples
234
+
235
+ 1. **Install dependencies:**
236
+ ```bash
237
+ bundle install
238
+ ```
239
+
240
+ 2. **Run individual examples:**
241
+ ```bash
242
+ ruby examples/01_point_to_point_orders.rb
243
+ ruby examples/02_publish_subscribe_events.rb
244
+ ruby examples/03_many_to_many_chat.rb
245
+ ```
246
+
247
+ 3. **Expected output:**
248
+ Each example produces verbose output showing:
249
+ - Service startup messages
250
+ - Message publishing and receiving
251
+ - Business logic execution
252
+ - System notifications and responses
253
+
254
+ ## Extending the Examples
255
+
256
+ ### Adding New Services
257
+ ```ruby
258
+ class MyNewService
259
+ def initialize
260
+ MyMessageType.subscribe('MyNewService.handle_message')
261
+ end
262
+
263
+ def self.handle_message(header, payload)
264
+ # Process messages here
265
+ end
266
+ end
267
+ ```
268
+
269
+ ### Creating New Message Types
270
+ ```ruby
271
+ class MyCustomMessage < SmartMessage::Base
272
+ property :custom_field
273
+ property :another_field
274
+
275
+ config do
276
+ transport SmartMessage::Transport::StdoutTransport.new(loopback: true)
277
+ serializer SmartMessage::Serializer::JSON.new
278
+ end
279
+ end
280
+ ```
281
+
282
+ ### Implementing New Transports
283
+ ```ruby
284
+ class MyCustomTransport < SmartMessage::Transport::Base
285
+ def publish(message_header, message_payload)
286
+ # Custom transport logic
287
+ end
288
+ end
289
+ ```
290
+
291
+ ## Production Considerations
292
+
293
+ When adapting these examples for production:
294
+
295
+ 1. **Transport Selection:**
296
+ - Use production message brokers (Redis, RabbitMQ, Kafka)
297
+ - Configure connection pooling and failover
298
+ - Implement proper error handling
299
+
300
+ 2. **Serialization:**
301
+ - Choose appropriate serializers for your data
302
+ - Consider performance and compatibility requirements
303
+ - Handle schema evolution
304
+
305
+ 3. **Monitoring:**
306
+ - Add logging and metrics
307
+ - Implement health checks
308
+ - Monitor message throughput and latency
309
+
310
+ 4. **Security:**
311
+ - Implement message encryption if needed
312
+ - Add authentication and authorization
313
+ - Validate message integrity
314
+
315
+ 5. **Scaling:**
316
+ - Configure multiple service instances
317
+ - Implement load balancing
318
+ - Plan for horizontal scaling
319
+
320
+ ## Additional Resources
321
+
322
+ - [SmartMessage Documentation](../docs/README.md)
323
+ - [Transport Layer Guide](../docs/transports.md)
324
+ - [Serialization Guide](../docs/serializers.md)
325
+ - [Architecture Overview](../docs/architecture.md)
326
+
327
+ ## Questions and Contributions
328
+
329
+ If you have questions about these examples or want to contribute additional examples:
330
+
331
+ 1. Check the main project documentation
332
+ 2. Look at the test files for more usage patterns
333
+ 3. Submit issues or pull requests to the main repository
334
+
335
+ These examples are designed to be educational and demonstrate best practices. Feel free to use them as starting points for your own SmartMessage-based applications!
@@ -0,0 +1,283 @@
1
+ # SmartMessage Tmux Chat Visualization
2
+
3
+ This is an enhanced version of the many-to-many chat example that uses tmux to provide a clear, visual representation of the messaging interactions between different agents across multiple chat rooms.
4
+
5
+ ## Overview
6
+
7
+ Instead of having all output mixed together in a single terminal, this tmux version separates:
8
+
9
+ - **Room Monitors**: Visual displays showing activity in each chat room
10
+ - **Human Agents**: Interactive chat clients for simulated users
11
+ - **Bot Agents**: Automated responders with various capabilities
12
+
13
+ ## Layout
14
+
15
+ The tmux session creates three windows:
16
+
17
+ ### Window 0: Chat Control Center (2x2 grid)
18
+ ```
19
+ ┌─────────────────┬─────────────────┐
20
+ │ General Room │ Tech Room │
21
+ │ Monitor │ Monitor │
22
+ ├─────────────────┼─────────────────┤
23
+ │ Random Room │ System Info & │
24
+ │ Monitor │ Instructions │
25
+ └─────────────────┴─────────────────┘
26
+ ```
27
+
28
+ ### Window 1: Human Agents (3 panes)
29
+ ```
30
+ ┌─────────────────┬─────────────────┐
31
+ │ │ Bob │
32
+ │ Alice ├─────────────────┤
33
+ │ │ Carol │
34
+ └─────────────────┴─────────────────┘
35
+ ```
36
+
37
+ ### Window 2: Bot Agents (2 panes)
38
+ ```
39
+ ┌─────────────────┬─────────────────┐
40
+ │ HelpBot │ FunBot │
41
+ │ │ │
42
+ └─────────────────┴─────────────────┘
43
+ ```
44
+
45
+ ## Features
46
+
47
+ ### Room Monitors
48
+ Each room monitor shows:
49
+ - Real-time message activity for that specific room
50
+ - User join/leave notifications
51
+ - Command detections
52
+ - Activity status (active/quiet/inactive)
53
+ - Message count and participant statistics
54
+
55
+ ### Human Agents
56
+ Interactive chat clients with:
57
+ - Command support (`/join`, `/leave`, `/list`, `/help`, `/quit`)
58
+ - Multi-room messaging
59
+ - Auto-response to mentions
60
+ - Real-time message display
61
+
62
+ ### Bot Agents
63
+ Automated agents with capabilities like:
64
+ - **HelpBot**: `/help`, `/stats`, `/time`
65
+ - **FunBot**: `/joke`, `/weather`, `/echo`
66
+ - Keyword responses (hello, help, thank you)
67
+ - Command processing with visual feedback
68
+
69
+ ## Quick Start
70
+
71
+ ### Prerequisites
72
+ - tmux installed (`brew install tmux` on macOS)
73
+ - Ruby with SmartMessage gem
74
+ - Terminal with decent size (recommended: 120x40 or larger)
75
+
76
+ ### Running the Demo
77
+
78
+ ```bash
79
+ # Start the entire chat system
80
+ cd examples/tmux_chat
81
+ ./start_chat_demo.sh
82
+ ```
83
+
84
+ ### Navigation
85
+
86
+ Once in tmux:
87
+
88
+ **Switch Between Windows:**
89
+ - **Ctrl+b then 0**: Switch to Control Center (room monitors)
90
+ - **Ctrl+b then 1**: Switch to Human Agents (Alice, Bob, Carol)
91
+ - **Ctrl+b then 2**: Switch to Bot Agents (HelpBot, FunBot)
92
+
93
+ **Move Between Panes (within a window):**
94
+ - **Ctrl+b then o**: Cycle through all panes in current window
95
+ - **Ctrl+b then arrow keys**: Move directly to pane in that direction (↑↓←→)
96
+ - **Ctrl+b then ;**: Toggle between current and last pane
97
+
98
+ **Other Useful Commands:**
99
+ - **Ctrl+b then z**: Zoom current pane (toggle fullscreen)
100
+ - **Ctrl+b then d**: Detach from session (keeps it running)
101
+ - **Ctrl+b then ?**: Show all tmux commands
102
+
103
+ ### Getting Started Workflow
104
+
105
+ 1. **After starting the demo**, you'll be in the Human Agents window (window 1)
106
+ 2. **Look for the active pane** (has colored border) - usually Alice's pane
107
+ 3. **Start typing immediately** - you're in the chat interface, not bash
108
+ 4. **Try these first commands:**
109
+ ```
110
+ /join general
111
+ Hello everyone!
112
+ /help
113
+ ```
114
+ 5. **Switch to other agents** using `Ctrl+b then o` to see different perspectives
115
+ 6. **Watch room activity** by switching to Control Center: `Ctrl+b then 0`
116
+
117
+ ### Interacting with Agents
118
+
119
+ In any human agent pane (Alice, Bob, Carol):
120
+ ```bash
121
+ # Join rooms
122
+ /join general
123
+ /join tech
124
+ /join random
125
+
126
+ # Send messages (goes to all your active rooms)
127
+ Hello everyone!
128
+
129
+ # Use bot commands
130
+ /help
131
+ /joke
132
+ /weather Tokyo
133
+ /stats
134
+
135
+ # Mention other users
136
+ @alice how are you?
137
+
138
+ # Leave rooms
139
+ /leave tech
140
+
141
+ # Exit
142
+ /quit
143
+ ```
144
+
145
+ ### Stopping the Demo
146
+
147
+ ```bash
148
+ # From outside tmux
149
+ ./stop_chat_demo.sh
150
+
151
+ # Or from inside tmux
152
+ Ctrl+b then d # Detach
153
+ ./stop_chat_demo.sh
154
+ ```
155
+
156
+ ## Architecture
157
+
158
+ ### File-Based Transport
159
+
160
+ This example uses a custom `FileTransport` that:
161
+ - Writes messages to room-specific queue files in `/tmp/smart_message_chat/`
162
+ - Polls files for new messages
163
+ - Enables inter-process communication between tmux panes
164
+ - Cleans up automatically on shutdown
165
+
166
+ ### Message Types
167
+
168
+ Three types of messages flow through the system:
169
+
170
+ 1. **ChatMessage**: Regular chat messages
171
+ 2. **BotCommandMessage**: Commands directed to bots
172
+ 3. **SystemNotificationMessage**: Join/leave/system events
173
+
174
+ ### Agent Types
175
+
176
+ - **BaseAgent**: Common functionality for all agents
177
+ - **HumanChatAgent**: Interactive user simulation
178
+ - **BotChatAgent**: Automated response agents
179
+ - **RoomMonitor**: Display-only room activity monitors
180
+
181
+ ## Advantages Over Single-Terminal Version
182
+
183
+ ### Visual Clarity
184
+ - **Room Separation**: See each room's activity independently
185
+ - **Agent Separation**: Each agent has its own display space
186
+ - **Real-time Updates**: Monitors show live activity as it happens
187
+
188
+ ### Better Understanding
189
+ - **Message Flow**: Clearly see how messages route between rooms
190
+ - **Agent Behavior**: Watch how different agents respond to events
191
+ - **System Dynamics**: Observe the many-to-many messaging patterns
192
+
193
+ ### Interactive Experience
194
+ - **Multiple Perspectives**: Switch between different agent viewpoints
195
+ - **Live Interaction**: Type and send messages in real-time
196
+ - **System Monitoring**: Watch room activity while participating
197
+
198
+ ## Example Workflow
199
+
200
+ 1. **Start the demo**: `./start_chat_demo.sh`
201
+ 2. **Watch the Control Center**: See rooms come online and initial messages
202
+ 3. **Switch to Human Agents**: Navigate to Alice, Bob, or Carol
203
+ 4. **Join rooms**: Use `/join general` to participate
204
+ 5. **Send messages**: Type anything to chat in your active rooms
205
+ 6. **Try bot commands**: Use `/joke`, `/weather`, `/help`
206
+ 7. **Watch interactions**: Switch back to Control Center to see message flow
207
+ 8. **Monitor bots**: Check Bot Agents window to see bot responses
208
+
209
+ ## Customization
210
+
211
+ ### Adding New Rooms
212
+ Edit `start_chat_demo.sh` to add more room monitors:
213
+ ```bash
214
+ tmux new-window -t $SESSION_NAME -n "New-Room"
215
+ tmux send-keys "ruby room_monitor.rb newroom" C-m
216
+ ```
217
+
218
+ ### Adding New Agents
219
+ Create additional panes:
220
+ ```bash
221
+ tmux split-window -t $SESSION_NAME:1 -v
222
+ tmux send-keys "ruby human_agent.rb david David" C-m
223
+ ```
224
+
225
+ ### Custom Bot Capabilities
226
+ Modify `bot_agent.rb` or create new bots:
227
+ ```bash
228
+ ruby bot_agent.rb mybot MyBot "custom,commands,here"
229
+ ```
230
+
231
+ ## Troubleshooting
232
+
233
+ ### Common Issues
234
+
235
+ **Tmux not found**:
236
+ ```bash
237
+ # macOS
238
+ brew install tmux
239
+
240
+ # Ubuntu/Debian
241
+ sudo apt-get install tmux
242
+ ```
243
+
244
+ **Messages not appearing**:
245
+ - Check that `/tmp/smart_message_chat/` directory exists
246
+ - Verify agents have joined the same rooms
247
+ - Try stopping and restarting the demo
248
+
249
+ **Pane too small**:
250
+ - Resize terminal window to at least 120x40
251
+ - Use `Ctrl+b then z` to zoom a pane temporarily
252
+
253
+ **Agents not responding**:
254
+ - Check that agents are in the same rooms (`/list` command)
255
+ - Verify bot capabilities match the commands being used
256
+
257
+ **Agents crash with console errors**:
258
+ - Fixed in latest version - agents now handle missing IO.console gracefully
259
+ - If issues persist, check Ruby version and terminal compatibility
260
+
261
+ ### Manual Cleanup
262
+
263
+ If the automatic cleanup doesn't work:
264
+ ```bash
265
+ # Kill tmux session
266
+ tmux kill-session -t smart_message_chat
267
+
268
+ # Remove message queues
269
+ rm -rf /tmp/smart_message_chat
270
+ ```
271
+
272
+ ## Educational Value
273
+
274
+ This visualization helps understand:
275
+
276
+ - **Many-to-many messaging patterns**
277
+ - **Room-based routing and filtering**
278
+ - **Agent coordination and communication**
279
+ - **Event-driven architecture**
280
+ - **Real-time system monitoring**
281
+ - **Service discovery and capabilities**
282
+
283
+ Perfect for demonstrating SmartMessage's power in complex, distributed scenarios!