415 lines
11 KiB
Go
415 lines
11 KiB
Go
package main
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"net/http"
|
||
"time"
|
||
|
||
"synapse/sdk/group"
|
||
"synapse/types"
|
||
)
|
||
|
||
// =============================================================================
|
||
// Group 群组测试 - 三个 Agent 之间的群组协作
|
||
// =============================================================================
|
||
|
||
func main() {
|
||
fmt.Println("=== 灵隙(Synapse)Group 群组测试 ===")
|
||
fmt.Println("启动三个 Agent,进行群组协作验证...")
|
||
fmt.Println()
|
||
|
||
// 创建群组客户端(简化版,直接在主程序模拟)
|
||
groupClient := &simpleGroupClient{
|
||
groups: make(map[string]*group.GroupState),
|
||
}
|
||
|
||
// 启动 Agent 1 (Coordinator) - 监听 9091 端口
|
||
go runCoordinatorAgent(groupClient)
|
||
|
||
// 等待 Agent 1 启动
|
||
time.Sleep(1 * time.Second)
|
||
|
||
// 启动 Agent 2 (Worker1) - 监听 9092 端口
|
||
go runWorkerAgent(groupClient, "worker-1", 9092)
|
||
|
||
// 等待 Agent 2 启动
|
||
time.Sleep(1 * time.Second)
|
||
|
||
// 启动 Agent 3 (Worker2) - 监听 9093 端口
|
||
go runWorkerAgent(groupClient, "worker-2", 9093)
|
||
|
||
// 保持主程序运行
|
||
fmt.Println("\n=== Agent 已启动,等待群组测试 ===")
|
||
fmt.Println("Agent 1 (Coordinator): http://localhost:9091")
|
||
fmt.Println("Agent 2 (Worker-1): http://localhost:9092")
|
||
fmt.Println("Agent 3 (Worker-2): http://localhost:9093")
|
||
fmt.Println("\n按 Ctrl+C 停止...")
|
||
|
||
// 自动创建群组并开始测试
|
||
go func() {
|
||
time.Sleep(2 * time.Second)
|
||
createGroup()
|
||
}()
|
||
|
||
select {}
|
||
}
|
||
|
||
// 简化的群组客户端
|
||
type simpleGroupClient struct {
|
||
groups map[string]*group.GroupState
|
||
members map[string][]string // groupID -> agentIDs
|
||
}
|
||
|
||
// 创建群组并开始测试
|
||
func createGroup() {
|
||
log.Printf("\n=== [主程序] 创建群组 ===")
|
||
|
||
resp, err := http.Post(
|
||
"http://localhost:9091/api/group/create",
|
||
"application/json",
|
||
jsonBody(map[string]any{}),
|
||
)
|
||
if err != nil {
|
||
log.Printf("[主程序] 创建群组失败: %v", err)
|
||
return
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
var result map[string]any
|
||
json.NewDecoder(resp.Body).Decode(&result)
|
||
log.Printf("[主程序] 创建群组响应: %v", result)
|
||
|
||
// 等待任务完成
|
||
time.Sleep(8 * time.Second)
|
||
}
|
||
|
||
type agentInfo struct {
|
||
ID string
|
||
Name string
|
||
Port int
|
||
Handler interface{}
|
||
}
|
||
|
||
// Coordinator Agent(协调者)
|
||
func runCoordinatorAgent(client *simpleGroupClient) {
|
||
mux := http.NewServeMux()
|
||
|
||
// 健康检查
|
||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(200)
|
||
w.Write([]byte("OK - Coordinator"))
|
||
})
|
||
|
||
// 群组管理 API
|
||
mux.HandleFunc("/api/group/create", func(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != http.MethodPost {
|
||
http.Error(w, "method not allowed", 405)
|
||
return
|
||
}
|
||
|
||
groupID := fmt.Sprintf("group-%d", time.Now().UnixNano())
|
||
group := &group.GroupState{
|
||
GroupID: groupID,
|
||
Name: "视频制作组",
|
||
Topology: types.GroupTopologyStar,
|
||
Status: types.GroupStatusActive,
|
||
Members: []types.GroupMember{
|
||
{
|
||
AgentID: "coordinator",
|
||
AgentName: "协调者",
|
||
Role: "coordinator",
|
||
JoinedAt: types.NowTimestamp(),
|
||
Status: types.GroupMemberActive,
|
||
Capabilities: []string{"coordination"},
|
||
LoadFactor: 0,
|
||
},
|
||
{
|
||
AgentID: "worker-1",
|
||
AgentName: "工作者1",
|
||
Role: "worker",
|
||
JoinedAt: types.NowTimestamp(),
|
||
Status: types.GroupMemberActive,
|
||
Capabilities: []string{"video_generation"},
|
||
LoadFactor: 0,
|
||
},
|
||
{
|
||
AgentID: "worker-2",
|
||
AgentName: "工作者2",
|
||
Role: "worker",
|
||
JoinedAt: types.NowTimestamp(),
|
||
Status: types.GroupMemberActive,
|
||
Capabilities: []string{"audio_generation"},
|
||
LoadFactor: 0,
|
||
},
|
||
},
|
||
Role: "coordinator",
|
||
}
|
||
client.groups[groupID] = group
|
||
|
||
log.Printf("\n=== [Coordinator] 群组创建成功 ===")
|
||
log.Printf("Group ID: %s", groupID)
|
||
log.Printf("Members: coordinator, worker-1, worker-2")
|
||
|
||
// 模拟任务拆分
|
||
go func() {
|
||
time.Sleep(1 * time.Second)
|
||
simulateTaskSplit(groupID, client)
|
||
}()
|
||
|
||
// 模拟投票
|
||
go func() {
|
||
time.Sleep(3 * time.Second)
|
||
simulateVote(groupID)
|
||
}()
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(map[string]any{
|
||
"success": true,
|
||
"group_id": groupID,
|
||
"message": "群组创建成功",
|
||
})
|
||
})
|
||
|
||
// 获取群组信息
|
||
mux.HandleFunc("/api/group/", func(w http.ResponseWriter, r *http.Request) {
|
||
groupID := r.URL.Path[len("/api/group/"):]
|
||
group, ok := client.groups[groupID]
|
||
if !ok {
|
||
http.Error(w, "group not found", 404)
|
||
return
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(map[string]any{
|
||
"success": true,
|
||
"group": group,
|
||
})
|
||
})
|
||
|
||
log.Println("[Coordinator] 协调者 Agent 启动,监听端口 9091")
|
||
if err := http.ListenAndServe(":9091", mux); err != nil {
|
||
log.Fatalf("[Coordinator] Server error: %v", err)
|
||
}
|
||
}
|
||
|
||
// Worker Agent(工作者)
|
||
func runWorkerAgent(client *simpleGroupClient, workerID string, port int) {
|
||
mux := http.NewServeMux()
|
||
|
||
// 健康检查
|
||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(200)
|
||
w.Write([]byte(fmt.Sprintf("OK - %s", workerID)))
|
||
})
|
||
|
||
// 加入群组
|
||
mux.HandleFunc("/api/group/join", func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
GroupID string `json:"group_id"`
|
||
}
|
||
json.NewDecoder(r.Body).Decode(&req)
|
||
|
||
log.Printf("\n=== [%s] 申请加入群组 ===", workerID)
|
||
log.Printf("Group ID: %s", req.GroupID)
|
||
|
||
// 模拟处理加入请求
|
||
time.Sleep(500 * time.Millisecond)
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(map[string]any{
|
||
"success": true,
|
||
"message": fmt.Sprintf("%s 已加入群组", workerID),
|
||
"role": "worker",
|
||
"group_id": req.GroupID,
|
||
})
|
||
})
|
||
|
||
// 接收任务
|
||
mux.HandleFunc("/api/task/subtask", func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
GroupID string `json:"group_id"`
|
||
Subtask string `json:"subtask"`
|
||
TaskType string `json:"task_type"`
|
||
Payload map[string]interface{} `json:"payload"`
|
||
}
|
||
json.NewDecoder(r.Body).Decode(&req)
|
||
|
||
log.Printf("\n=== [%s] 收到子任务 ===", workerID)
|
||
log.Printf("Group ID: %s", req.GroupID)
|
||
log.Printf("Subtask: %s", req.Subtask)
|
||
log.Printf("Task Type: %s", req.TaskType)
|
||
log.Printf("Payload: %v", req.Payload)
|
||
|
||
// 模拟执行任务
|
||
go func() {
|
||
time.Sleep(1 * time.Second)
|
||
|
||
log.Printf("[%s] 子任务执行完成: %s", workerID, req.Subtask)
|
||
|
||
// 发送结果(这里简化处理,只是打印日志)
|
||
log.Printf("[%s] 发送子任务结果: %s -> 完成了 %s 的工作", workerID, req.Subtask, req.TaskType)
|
||
}()
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(map[string]any{
|
||
"success": true,
|
||
"message": fmt.Sprintf("%s 开始执行任务", workerID),
|
||
"subtask": req.Subtask,
|
||
"progress": 0,
|
||
})
|
||
})
|
||
|
||
// 接收投票
|
||
mux.HandleFunc("/api/vote", func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
GroupID string `json:"group_id"`
|
||
VoteID string `json:"vote_id"`
|
||
Question string `json:"question"`
|
||
Options []string `json:"options"`
|
||
}
|
||
json.NewDecoder(r.Body).Decode(&req)
|
||
|
||
log.Printf("\n=== [%s] 收到投票请求 ===", workerID)
|
||
log.Printf("Vote ID: %s", req.VoteID)
|
||
log.Printf("Question: %s", req.Question)
|
||
log.Printf("Options: %v", req.Options)
|
||
|
||
// 模拟投票决策(选择第一个选项)
|
||
selectedOption := req.Options[0]
|
||
log.Printf("[%s] 投票: %s", workerID, selectedOption)
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(map[string]any{
|
||
"success": true,
|
||
"vote_id": req.VoteID,
|
||
"selected_option": selectedOption,
|
||
"reason": "看起来更合理",
|
||
})
|
||
})
|
||
|
||
log.Printf("[%s] 工作者 Agent 启动,监听端口 %d", workerID, port)
|
||
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), mux); err != nil {
|
||
log.Fatalf("[%s] Server error: %v", workerID, err)
|
||
}
|
||
}
|
||
|
||
// 模拟任务拆分
|
||
func simulateTaskSplit(groupID string, client *simpleGroupClient) {
|
||
log.Printf("\n=== [Coordinator] 执行任务拆分 ===")
|
||
log.Printf("Original Task: 制作视频")
|
||
|
||
subtasks := []struct {
|
||
ID string
|
||
Description string
|
||
AssignedTo string
|
||
}{
|
||
{"sub-1", "生成视频脚本", "worker-1"},
|
||
{"sub-2", "生成配音", "worker-2"},
|
||
}
|
||
|
||
for _, st := range subtasks {
|
||
log.Printf("拆分任务: %s -> %s", st.ID, st.AssignedTo)
|
||
|
||
// 发送任务给 worker
|
||
port := 9092
|
||
if st.AssignedTo == "worker-2" {
|
||
port = 9093
|
||
}
|
||
|
||
resp, err := http.Post(
|
||
fmt.Sprintf("http://localhost:%d/api/task/subtask", port),
|
||
"application/json",
|
||
jsonBody(map[string]any{
|
||
"group_id": groupID,
|
||
"subtask": st.ID,
|
||
"task_type": "video_generation",
|
||
"payload": map[string]any{"description": st.Description},
|
||
}),
|
||
)
|
||
if err != nil {
|
||
log.Printf("[Coordinator] 发送任务失败: %v", err)
|
||
continue
|
||
}
|
||
resp.Body.Close()
|
||
|
||
time.Sleep(500 * time.Millisecond)
|
||
}
|
||
}
|
||
|
||
// 模拟投票
|
||
func simulateVote(groupID string) {
|
||
log.Printf("\n=== [Coordinator] 发起投票 ===")
|
||
|
||
voteQuestion := "选择视频风格?"
|
||
voteOptions := []string{"现代风格", "复古风格", "卡通风格"}
|
||
|
||
log.Printf("Question: %s", voteQuestion)
|
||
log.Printf("Options: %v", voteOptions)
|
||
|
||
// 收集投票结果
|
||
votes := make(map[string]int)
|
||
for _, opt := range voteOptions {
|
||
votes[opt] = 0
|
||
}
|
||
|
||
// 向两个 worker 发送投票
|
||
for _, port := range []int{9092, 9093} {
|
||
resp, err := http.Post(
|
||
fmt.Sprintf("http://localhost:%d/api/vote", port),
|
||
"application/json",
|
||
jsonBody(map[string]any{
|
||
"group_id": groupID,
|
||
"vote_id": fmt.Sprintf("vote-%d", time.Now().UnixNano()),
|
||
"question": voteQuestion,
|
||
"options": voteOptions,
|
||
}),
|
||
)
|
||
if err != nil {
|
||
log.Printf("[Coordinator] 投票请求失败: %v", err)
|
||
continue
|
||
}
|
||
|
||
var result map[string]any
|
||
json.NewDecoder(resp.Body).Decode(&result)
|
||
resp.Body.Close()
|
||
|
||
if selected, ok := result["selected_option"].(string); ok {
|
||
votes[selected]++
|
||
}
|
||
}
|
||
|
||
// 统计结果
|
||
log.Printf("\n=== [Coordinator] 投票结果 ===")
|
||
for opt, count := range votes {
|
||
log.Printf("%s: %d 票", opt, count)
|
||
}
|
||
|
||
// 确定获胜者
|
||
var winner string
|
||
maxVotes := 0
|
||
for opt, count := range votes {
|
||
if count > maxVotes {
|
||
maxVotes = count
|
||
winner = opt
|
||
}
|
||
}
|
||
|
||
log.Printf("\n最终决定: %s (获得 %d 票)", winner, maxVotes)
|
||
|
||
// 模拟结果合并
|
||
go func() {
|
||
time.Sleep(1 * time.Second)
|
||
log.Printf("\n=== [Coordinator] 合并任务结果 ===")
|
||
log.Printf("所有子任务已完成")
|
||
log.Printf("最终结果: 视频制作完成,采用 %s", winner)
|
||
}()
|
||
}
|
||
|
||
func jsonBody(v map[string]any) *bytes.Buffer {
|
||
data, _ := json.Marshal(v)
|
||
return bytes.NewBuffer(data)
|
||
}
|