Skip to content

Commit 6afbe81

Browse files
committed
improve documents
1 parent d9042da commit 6afbe81

11 files changed

+1456
-868
lines changed
File renamed without changes.

docs/core-concepts.md

+313
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
1+
# Ceylon Framework Core Concepts Guide
2+
3+
## Agent System Architecture
4+
5+
### Admin Agent
6+
The central coordinator in a Ceylon system.
7+
8+
```python
9+
from ceylon import Admin
10+
11+
class CoordinatorAdmin(Admin):
12+
def __init__(self, name="coordinator", port=8888):
13+
super().__init__(name=name, port=port)
14+
```
15+
16+
Key characteristics:
17+
- One admin per system
18+
- Manages worker connections
19+
- Coordinates task distribution
20+
- Handles system-wide state
21+
22+
### Worker Agent
23+
Performs specific tasks within the system.
24+
25+
```python
26+
from ceylon import Worker
27+
28+
class TaskWorker(Worker):
29+
def __init__(self, name: str, role: str):
30+
super().__init__(name=name, role=role)
31+
```
32+
33+
Key characteristics:
34+
- Multiple workers per system
35+
- Specialized task execution
36+
- Reports to admin agent
37+
- Independent operation
38+
39+
## Message System
40+
41+
### Message Types
42+
```python
43+
from dataclasses import dataclass
44+
from typing import Any
45+
46+
@dataclass(frozen=True)
47+
class Message:
48+
id: str
49+
content: Any
50+
timestamp: float
51+
```
52+
53+
Core message principles:
54+
- Immutable data structures
55+
- Type-safe communication
56+
- Metadata inclusion
57+
- Serializable format
58+
59+
### Message Handlers
60+
```python
61+
from ceylon import on, on_run, on_connect
62+
63+
class MessageHandling:
64+
@on(MessageType)
65+
async def handle_specific(self, msg: MessageType):
66+
# Handle specific message type
67+
pass
68+
69+
@on_run()
70+
async def handle_run(self, inputs: bytes):
71+
# Main execution loop
72+
pass
73+
74+
@on_connect("*")
75+
async def handle_connection(self, topic: str, agent: AgentDetail):
76+
# Connection handling
77+
pass
78+
```
79+
80+
## Communication Patterns
81+
82+
### Direct Communication
83+
```python
84+
class DirectCommunication(Worker):
85+
async def send_to_peer(self, peer_id: str, data: Any):
86+
await self.send_message(peer_id, data)
87+
```
88+
89+
### Broadcast Communication
90+
```python
91+
class BroadcastCommunication(Admin):
92+
async def notify_all(self, data: Any):
93+
await self.broadcast_message(data)
94+
```
95+
96+
## State Management
97+
98+
### Agent State
99+
```python
100+
from enum import Enum
101+
102+
class AgentState(Enum):
103+
IDLE = "idle"
104+
PROCESSING = "processing"
105+
ERROR = "error"
106+
107+
class StateManagement(Worker):
108+
def __init__(self):
109+
super().__init__()
110+
self.state = AgentState.IDLE
111+
```
112+
113+
### State Transitions
114+
```python
115+
class StatefulAgent(Worker):
116+
async def transition_state(self, new_state: AgentState):
117+
old_state = self.state
118+
self.state = new_state
119+
await self.notify_state_change(old_state, new_state)
120+
```
121+
122+
## Event Processing
123+
124+
### Event Handling
125+
```python
126+
class EventProcessor(Worker):
127+
@on(Event)
128+
async def process_event(self, event: Event):
129+
if self.can_handle(event):
130+
await self.handle_event(event)
131+
else:
132+
await self.forward_event(event)
133+
```
134+
135+
### Event Flow
136+
```python
137+
class EventFlow(Admin):
138+
async def manage_event_flow(self, event: Event):
139+
# Preprocessing
140+
processed_event = await self.preprocess(event)
141+
142+
# Distribution
143+
await self.distribute_event(processed_event)
144+
145+
# Monitoring
146+
await self.monitor_event_processing(processed_event)
147+
```
148+
149+
## Resource Management
150+
151+
### Resource Lifecycle
152+
```python
153+
class ResourceManager(Worker):
154+
async def __aenter__(self):
155+
await self.acquire_resources()
156+
return self
157+
158+
async def __aexit__(self, exc_type, exc_val, exc_tb):
159+
await self.release_resources()
160+
```
161+
162+
### Resource Pooling
163+
```python
164+
class ResourcePool:
165+
def __init__(self, size: int):
166+
self.pool = asyncio.Queue(size)
167+
self.in_use = set()
168+
169+
async def acquire(self):
170+
resource = await self.pool.get()
171+
self.in_use.add(resource)
172+
return resource
173+
174+
async def release(self, resource):
175+
self.in_use.remove(resource)
176+
await self.pool.put(resource)
177+
```
178+
179+
## Error Handling
180+
181+
### Basic Error Handling
182+
```python
183+
class ErrorHandler(Worker):
184+
async def safe_execute(self, task):
185+
try:
186+
return await self.execute_task(task)
187+
except Exception as e:
188+
await self.handle_error(task, e)
189+
raise
190+
```
191+
192+
### Retry Mechanism
193+
```python
194+
class RetryMechanism(Worker):
195+
async def with_retry(self, operation, max_retries=3):
196+
for attempt in range(max_retries):
197+
try:
198+
return await operation()
199+
except Exception as e:
200+
if attempt == max_retries - 1:
201+
raise
202+
await asyncio.sleep(2 ** attempt)
203+
```
204+
205+
## System Integration
206+
207+
### External Service Integration
208+
```python
209+
class ServiceIntegrator(Worker):
210+
async def interact_with_service(self, service_request):
211+
# Convert to external format
212+
external_request = self.convert_request(service_request)
213+
214+
# Make external call
215+
response = await self.call_service(external_request)
216+
217+
# Convert response back
218+
return self.convert_response(response)
219+
```
220+
221+
### Data Flow
222+
```python
223+
class DataFlowManager(Admin):
224+
async def manage_data_flow(self, data):
225+
# Input validation
226+
validated_data = await self.validate(data)
227+
228+
# Processing
229+
processed_data = await self.process(validated_data)
230+
231+
# Distribution
232+
await self.distribute(processed_data)
233+
```
234+
235+
## Core Utilities
236+
237+
### Message Conversion
238+
```python
239+
class MessageConverter:
240+
@staticmethod
241+
def to_bytes(message: Any) -> bytes:
242+
return pickle.dumps(message)
243+
244+
@staticmethod
245+
def from_bytes(data: bytes) -> Any:
246+
return pickle.loads(data)
247+
```
248+
249+
### Agent Identification
250+
```python
251+
class AgentIdentification:
252+
@staticmethod
253+
def create_agent_id(name: str, role: str) -> str:
254+
return f"{name}_{role}_{uuid.uuid4()}"
255+
```
256+
257+
## System Lifecycle
258+
259+
### Initialization
260+
```python
261+
async def initialize_system():
262+
# Create admin
263+
admin = AdminAgent(port=8888)
264+
265+
# Create workers
266+
workers = [
267+
WorkerAgent(f"worker_{i}")
268+
for i in range(3)
269+
]
270+
271+
# Start system
272+
await admin.start_agent(b"", workers)
273+
```
274+
275+
### Shutdown
276+
```python
277+
async def shutdown_system(admin: Admin, workers: List[Worker]):
278+
# Stop workers
279+
for worker in workers:
280+
await worker.stop()
281+
282+
# Stop admin
283+
await admin.stop()
284+
```
285+
286+
## Key Concepts Summary
287+
288+
1. **Agent Hierarchy**
289+
- Admin agents coordinate
290+
- Worker agents execute
291+
- Clear responsibility separation
292+
293+
2. **Message-Based Communication**
294+
- Type-safe messages
295+
- Asynchronous processing
296+
- Event-driven architecture
297+
298+
3. **State Management**
299+
- Clear state definitions
300+
- Controlled transitions
301+
- State monitoring
302+
303+
4. **Resource Handling**
304+
- Proper initialization
305+
- Clean cleanup
306+
- Resource pooling
307+
308+
5. **Error Management**
309+
- Graceful error handling
310+
- Retry mechanisms
311+
- Error reporting
312+
313+
These core concepts provide the foundation for building robust distributed systems with Ceylon.

0 commit comments

Comments
 (0)