灵隙(synapse) v1.0.0 版本
This commit is contained in:
@@ -224,6 +224,10 @@ func (p *P2PProtocol) handleTaskRequest(ctx context.Context, msg *types.UnifiedS
|
||||
taskCtx, cancel := context.WithTimeout(ctx, p.config.TaskTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Store task status
|
||||
status := types.P2PStatusPending
|
||||
p.tasks[taskID] = &status
|
||||
|
||||
// Execute task asynchronously
|
||||
go p.executeTask(taskCtx, msg, taskID, payload.Task.Type, payload.Task.Payload)
|
||||
|
||||
@@ -233,6 +237,12 @@ func (p *P2PProtocol) handleTaskRequest(ctx context.Context, msg *types.UnifiedS
|
||||
|
||||
// executeTask executes a task and handles callbacks
|
||||
func (p *P2PProtocol) executeTask(ctx context.Context, origMsg *types.UnifiedSynapseMessage, taskID, taskType string, payload map[string]interface{}) {
|
||||
// Update status to executing
|
||||
p.mu.Lock()
|
||||
execStatus := types.P2PStatusExecuting
|
||||
p.tasks[taskID] = &execStatus
|
||||
p.mu.Unlock()
|
||||
|
||||
// Send initial status update
|
||||
p.sendStatusUpdate(ctx, taskID, types.P2PStatusExecuting, 0, "Task started")
|
||||
|
||||
@@ -241,11 +251,19 @@ func (p *P2PProtocol) executeTask(ctx context.Context, origMsg *types.UnifiedSyn
|
||||
|
||||
if err != nil {
|
||||
// Task failed
|
||||
p.mu.Lock()
|
||||
failStatus := types.P2PStatusFailed
|
||||
p.tasks[taskID] = &failStatus
|
||||
p.mu.Unlock()
|
||||
p.sendTaskFailed(ctx, taskID, "execution_failed", err.Error(), true, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Task completed
|
||||
p.mu.Lock()
|
||||
compStatus := types.P2PStatusCompleted
|
||||
p.tasks[taskID] = &compStatus
|
||||
p.mu.Unlock()
|
||||
p.sendTaskComplete(ctx, taskID, result)
|
||||
}
|
||||
|
||||
@@ -498,7 +516,18 @@ func (p *P2PProtocol) newAck(msg *types.UnifiedSynapseMessage, taskID, note stri
|
||||
|
||||
// newNACK creates a NACK response
|
||||
func (p *P2PProtocol) newNACK(msg *types.UnifiedSynapseMessage, err *types.SynapseError) (*types.UnifiedSynapseMessage, error) {
|
||||
return nil, err
|
||||
errBytes, _ := json.Marshal(err)
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PNack),
|
||||
Sender: p.agentEndpoint,
|
||||
Receiver: &msg.Sender,
|
||||
CorrelationID: msg.CorrelationID,
|
||||
ReplyTo: msg.ID,
|
||||
Payload: errBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// newReject creates a task rejection response
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestHandleHeartbeat(t *testing.T) {
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PHeartbeat),
|
||||
Sender: types.AgentEndpoint{AgentID: "agent-002"},
|
||||
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||
Payload: json.RawMessage("{}"),
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
@@ -217,7 +217,7 @@ func TestHandleAck(t *testing.T) {
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PAck),
|
||||
Sender: types.AgentEndpoint{AgentID: "agent-002"},
|
||||
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||
ReplyTo: "msg-001",
|
||||
Payload: json.RawMessage("{}"),
|
||||
Timestamp: types.NowTimestamp(),
|
||||
@@ -295,6 +295,10 @@ func TestGetTaskStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
proto := NewP2PProtocol(ep, nil)
|
||||
proto.SetTaskHandler(&mockTaskHandler{
|
||||
canHandle: true,
|
||||
result: "test result",
|
||||
})
|
||||
|
||||
// 查询不存在的任务
|
||||
status, ok := proto.GetTaskStatus("nonexistent")
|
||||
@@ -327,9 +331,9 @@ func TestGetTaskStatus(t *testing.T) {
|
||||
if !ok {
|
||||
t.Error("Task should be found")
|
||||
}
|
||||
// 状态应该是 pending 或 confirmed
|
||||
if status != types.P2PStatusPending && status != types.P2PStatusConfirmed {
|
||||
t.Errorf("Status should be pending or confirmed: got %s", status)
|
||||
// 状态应该是 pending 或 executing(异步执行可能已经开始)
|
||||
if status != types.P2PStatusPending && status != types.P2PStatusExecuting && status != types.P2PStatusCompleted {
|
||||
t.Errorf("Status should be pending/executing/completed: got %s", status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +344,10 @@ func TestListTasks(t *testing.T) {
|
||||
}
|
||||
|
||||
proto := NewP2PProtocol(ep, nil)
|
||||
proto.SetTaskHandler(&mockTaskHandler{
|
||||
canHandle: true,
|
||||
result: "test result",
|
||||
})
|
||||
|
||||
// 初始应该为空
|
||||
tasks := proto.ListTasks()
|
||||
@@ -487,8 +495,14 @@ func TestHandleUnknownMessageType(t *testing.T) {
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
_, err := proto.HandleMessage(context.Background(), msg)
|
||||
if err == nil {
|
||||
t.Error("Unknown message type should return error")
|
||||
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||
if err != nil {
|
||||
t.Errorf("Unknown message type should return NACK response, not error: %v", err)
|
||||
}
|
||||
if resp == nil {
|
||||
t.Error("Unknown message type should return NACK response")
|
||||
}
|
||||
if resp.Type != string(types.P2PNack) {
|
||||
t.Errorf("Expected NACK response, got: %s", resp.Type)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,15 +96,24 @@ type VoteStatus struct {
|
||||
// NewGRPCServer creates a new gRPC server
|
||||
func NewGRPCServer(taskExec TaskExecutor, msgRouter MessageRouter, capsProvider CapabilitiesProvider, groupManager GroupManager) *GRPCServer {
|
||||
return &GRPCServer{
|
||||
taskExecutor: taskExec,
|
||||
msgRouter: msgRouter,
|
||||
capsProvider: capsProvider,
|
||||
groupManager: groupManager,
|
||||
taskService: &TaskServiceImpl{},
|
||||
messageService: &MessageServiceImpl{},
|
||||
capabilitiesService: &CapabilitiesServiceImpl{},
|
||||
groupService: &GroupServiceImpl{},
|
||||
healthService: &HealthServiceImpl{},
|
||||
taskExecutor: taskExec,
|
||||
msgRouter: msgRouter,
|
||||
capsProvider: capsProvider,
|
||||
groupManager: groupManager,
|
||||
taskService: &TaskServiceImpl{
|
||||
taskExecutor: taskExec,
|
||||
streamClients: make(map[string]chan *TaskStatusUpdate),
|
||||
},
|
||||
messageService: &MessageServiceImpl{
|
||||
msgRouter: msgRouter,
|
||||
},
|
||||
capabilitiesService: &CapabilitiesServiceImpl{
|
||||
provider: capsProvider,
|
||||
},
|
||||
groupService: &GroupServiceImpl{
|
||||
groupManager: groupManager,
|
||||
},
|
||||
healthService: &HealthServiceImpl{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,11 +133,12 @@ func (s *GRPCServer) Start(grpcPort, gatewayPort int) error {
|
||||
}
|
||||
s.grpcServer = grpc.NewServer(opts...)
|
||||
|
||||
// Register services
|
||||
// Note: These would be generated from proto
|
||||
// RegisterTaskServiceServer(s.grpcServer, s.taskService)
|
||||
// RegisterA2AMessageServiceServer(s.grpcServer, s.messageService)
|
||||
// ... etc
|
||||
// Register services using ServiceDesc
|
||||
s.grpcServer.RegisterService(&TaskService_ServiceDesc, s.taskService)
|
||||
s.grpcServer.RegisterService(&A2AMessageService_ServiceDesc, s.messageService)
|
||||
s.grpcServer.RegisterService(&CapabilitiesService_ServiceDesc, s.capabilitiesService)
|
||||
s.grpcServer.RegisterService(&GroupService_ServiceDesc, s.groupService)
|
||||
s.grpcServer.RegisterService(&HealthService_ServiceDesc, s.healthService)
|
||||
|
||||
log.Printf("[gRPC] Server started on port %d", grpcPort)
|
||||
if err := s.grpcServer.Serve(lis); err != nil {
|
||||
|
||||
@@ -73,8 +73,8 @@ func NewCircuitBreaker(name string, config *CircuitBreakerConfig) *CircuitBreake
|
||||
|
||||
// Allow 是否允许请求通过
|
||||
func (cb *CircuitBreaker) Allow() bool {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
|
||||
switch cb.state {
|
||||
case CircuitClosed:
|
||||
@@ -82,16 +82,10 @@ func (cb *CircuitBreaker) Allow() bool {
|
||||
case CircuitOpen:
|
||||
// 检查是否超时,可以进入半开状态
|
||||
if time.Since(cb.lastFailure) > cb.timeout {
|
||||
cb.mu.RUnlock()
|
||||
cb.mu.Lock()
|
||||
if cb.state == CircuitOpen && time.Since(cb.lastFailure) > cb.timeout {
|
||||
cb.state = CircuitHalfOpen
|
||||
cb.successCount = 0
|
||||
log.Printf("[灵枢] 熔断器 %s 进入半开状态", cb.name)
|
||||
}
|
||||
cb.mu.Unlock()
|
||||
cb.mu.RLock()
|
||||
return cb.state == CircuitHalfOpen
|
||||
cb.state = CircuitHalfOpen
|
||||
cb.successCount = 0
|
||||
log.Printf("[灵枢] 熔断器 %s 进入半开状态", cb.name)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case CircuitHalfOpen:
|
||||
|
||||
@@ -41,6 +41,10 @@ type HTTPTransport struct {
|
||||
// Callbacks
|
||||
callbackEndpoint string
|
||||
callbackHandler MessageCallbackHandler
|
||||
|
||||
// Pending callbacks (for SendWithCallback)
|
||||
pendingCallbacks map[string]chan *types.UnifiedSynapseMessage
|
||||
pendingMu sync.RWMutex
|
||||
}
|
||||
|
||||
// HTTPTransportConfig holds HTTP transport configuration
|
||||
@@ -68,11 +72,12 @@ func NewHTTPTransport(config *HTTPTransportConfig) *HTTPTransport {
|
||||
}
|
||||
|
||||
t := &HTTPTransport{
|
||||
baseURL: config.BaseURL,
|
||||
timeout: config.Timeout,
|
||||
maxRetries: config.MaxRetries,
|
||||
retryDelay: config.RetryDelay,
|
||||
authSecret: config.AuthSecret,
|
||||
baseURL: config.BaseURL,
|
||||
timeout: config.Timeout,
|
||||
maxRetries: config.MaxRetries,
|
||||
retryDelay: config.RetryDelay,
|
||||
authSecret: config.AuthSecret,
|
||||
pendingCallbacks: make(map[string]chan *types.UnifiedSynapseMessage),
|
||||
client: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
},
|
||||
@@ -177,6 +182,18 @@ func (t *HTTPTransport) SendWithCallback(
|
||||
correlationID = msg.ID
|
||||
}
|
||||
|
||||
// Register pending callback
|
||||
t.pendingMu.Lock()
|
||||
t.pendingCallbacks[correlationID] = respChan
|
||||
t.pendingMu.Unlock()
|
||||
|
||||
// Cleanup on exit
|
||||
defer func() {
|
||||
t.pendingMu.Lock()
|
||||
delete(t.pendingCallbacks, correlationID)
|
||||
t.pendingMu.Unlock()
|
||||
}()
|
||||
|
||||
// Start timeout goroutine
|
||||
go func() {
|
||||
select {
|
||||
@@ -240,7 +257,33 @@ func (t *HTTPTransport) HandleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle message
|
||||
// Check if this is a pending callback response
|
||||
correlationID := msg.CorrelationID
|
||||
if correlationID == "" {
|
||||
correlationID = msg.ID
|
||||
}
|
||||
|
||||
t.pendingMu.RLock()
|
||||
ch, pending := t.pendingCallbacks[correlationID]
|
||||
t.pendingMu.RUnlock()
|
||||
|
||||
if pending {
|
||||
// Send response to waiting goroutine
|
||||
select {
|
||||
case ch <- &msg:
|
||||
default:
|
||||
}
|
||||
// Send success response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "callback received",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Handle message via callback handler
|
||||
if t.callbackHandler != nil {
|
||||
if err := t.callbackHandler.HandleMessage(&msg); err != nil {
|
||||
log.Printf("[Transport] Failed to handle message: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user