File size: 3,431 Bytes
82f9be0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""
通讯API路由
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List
import uuid
from datetime import datetime

from ...core import EntityInfo, Message, RedisAdapter

router = APIRouter()

# 全局存储(生产环境应使用数据库)
entities: dict[str, EntityInfo] = {}
adapters: dict[str, RedisAdapter] = {}


class EntityCreate(BaseModel):
    name: str
    redis_host: str = "localhost"
    redis_port: int = 6379
    redis_db: int = 0


class MessageSend(BaseModel):
    sender_id: str
    receiver_id: str
    content: str


class MessageResponse(BaseModel):
    sender_id: str
    receiver_id: str
    timestamp: str
    content: str


@router.post("/entities", response_model=dict)
async def create_entity(entity: EntityCreate):
    """创建新实体"""
    entity_id = str(uuid.uuid4())
    channel = entity_id
    
    entity_info = EntityInfo(
        id=entity_id,
        name=entity.name,
        redis_host=entity.redis_host,
        redis_port=entity.redis_port,
        redis_db=entity.redis_db,
        channel=channel
    )
    
    entities[entity_id] = entity_info
    
    return {
        "id": entity_id,
        "name": entity.name,
        "status": "created"
    }


@router.get("/entities", response_model=List[dict])
async def list_entities():
    """获取所有实体列表"""
    return [
        {
            "id": entity_id,
            "name": entity.name,
            "redis_host": entity.redis_host,
            "redis_port": entity.redis_port,
            "redis_db": entity.redis_db
        }
        for entity_id, entity in entities.items()
    ]


@router.post("/entities/{entity_id}/start")
async def start_entity(entity_id: str):
    """启动实体通讯"""
    if entity_id not in entities:
        raise HTTPException(status_code=404, detail="Entity not found")
    
    if entity_id in adapters:
        raise HTTPException(status_code=400, detail="Entity already started")
    
    adapter = RedisAdapter(entities[entity_id])
    if adapter.start():
        adapters[entity_id] = adapter
        return {"status": "started"}
    else:
        raise HTTPException(status_code=500, detail="Failed to start entity")


@router.post("/entities/{entity_id}/stop")
async def stop_entity(entity_id: str):
    """停止实体通讯"""
    if entity_id not in adapters:
        raise HTTPException(status_code=404, detail="Entity not started")
    
    adapters[entity_id].stop()
    del adapters[entity_id]
    
    return {"status": "stopped"}


@router.post("/messages/send")
async def send_message(message: MessageSend):
    """发送消息"""
    if message.sender_id not in adapters:
        raise HTTPException(status_code=404, detail="Sender not started")
    
    if message.receiver_id not in entities:
        raise HTTPException(status_code=404, detail="Receiver not found")
    
    adapter = adapters[message.sender_id]
    success = adapter.send_message(message.receiver_id, message.content)
    
    if success:
        return {"status": "sent"}
    else:
        raise HTTPException(status_code=500, detail="Failed to send message")


@router.get("/entities/{entity_id}/messages", response_model=List[MessageResponse])
async def get_entity_messages(entity_id: str):
    """获取实体的消息历史(临时存储,演示用)"""
    # 这里只是示例,实际应该从持久化存储获取
    return []