灵隙(synapse) v1.0.0 版本

This commit is contained in:
lychang
2026-06-28 03:24:26 +08:00
parent 88b606b9ca
commit 812f68d5aa
48 changed files with 5566 additions and 1499 deletions

View File

@@ -0,0 +1,595 @@
package p2p
import (
"context"
"encoding/json"
"fmt"
"log"
"sync"
"time"
"synapse/pkg/types"
)
// =============================================================================
// P2P Protocol Handler
// =============================================================================
// TaskHandler is the interface for handling task execution
type TaskHandler interface {
// ExecuteTask executes a task and returns the result
ExecuteTask(ctx context.Context, taskType string, payload map[string]interface{}) (any, error)
// ValidateTask validates if the task can be executed
ValidateTask(taskType string, payload map[string]interface{}) ([]types.MissingField, bool)
// GetCapabilities returns the agent's capabilities
GetCapabilities() []string
}
// MessageHandler is the interface for handling incoming messages
type MessageHandler interface {
// HandleMessage handles an incoming P2P message
HandleMessage(msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
}
// CallbackSender is the interface for sending callbacks to remote agents
type CallbackSender interface {
// SendCallback sends a message to a remote agent
SendCallback(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error
}
// =============================================================================
// P2PProtocol represents the P2P protocol handler
// =============================================================================
// P2PProtocol handles point-to-point Synapse communication
type P2PProtocol struct {
mu sync.RWMutex
// Agent identity
agentEndpoint types.AgentEndpoint
// Task state
tasks map[string]*types.P2PTaskStatus
// Handlers
taskHandler TaskHandler
callbackSender CallbackSender
// Configuration
config *P2PConfig
}
// P2PConfig holds P2P protocol configuration
type P2PConfig struct {
MaxRetries int // Max callback retries
RetryBaseDelay time.Duration // Base delay for retries
TaskTimeout time.Duration // Task execution timeout
HeartbeatInterval time.Duration // Heartbeat interval
}
// DefaultP2PConfig returns default P2P configuration
func DefaultP2PConfig() *P2PConfig {
return &P2PConfig{
MaxRetries: 5,
RetryBaseDelay: 2 * time.Second,
TaskTimeout: 5 * time.Minute,
HeartbeatInterval: 30 * time.Second,
}
}
// =============================================================================
// P2PTask represents an active task
// =============================================================================
type P2PTask struct {
ID string
Type string
Priority types.Priority
Status types.P2PTaskStatus
Payload map[string]interface{}
Sender types.AgentEndpoint
Receiver types.AgentEndpoint
CorrelationID string
CreatedAt time.Time
UpdatedAt time.Time
CompletedAt *time.Time
Result any
Error *types.SynapseError
}
// =============================================================================
// NewP2PProtocol creates a new P2P protocol handler
// =============================================================================
func NewP2PProtocol(agentEndpoint types.AgentEndpoint, config *P2PConfig) *P2PProtocol {
if config == nil {
config = DefaultP2PConfig()
}
return &P2PProtocol{
agentEndpoint: agentEndpoint,
tasks: make(map[string]*types.P2PTaskStatus),
config: config,
}
}
// SetTaskHandler sets the task handler
func (p *P2PProtocol) SetTaskHandler(h TaskHandler) {
p.taskHandler = h
}
// SetCallbackSender sets the callback sender
func (p *P2PProtocol) SetCallbackSender(s CallbackSender) {
p.callbackSender = s
}
// AgentEndpoint returns the agent's endpoint
func (p *P2PProtocol) AgentEndpoint() types.AgentEndpoint {
return p.agentEndpoint
}
// =============================================================================
// HandleMessage processes an incoming P2P message
// =============================================================================
func (p *P2PProtocol) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
p.mu.Lock()
defer p.mu.Unlock()
// Validate message
if err := p.validateMessage(msg); err != nil {
a2aErr, ok := err.(*types.SynapseError)
if !ok {
a2aErr = types.NewSynapseError(types.ErrMessageFormatInvalid, err.Error(), nil)
}
return p.newNACK(msg, a2aErr)
}
// Route based on message type
switch types.P2PMessageType(msg.Type) {
case types.P2PTaskRequest:
return p.handleTaskRequest(ctx, msg)
case types.P2PTaskConfirm:
return p.handleTaskConfirm(ctx, msg)
case types.P2PTaskReject:
return p.handleTaskReject(ctx, msg)
case types.P2PTaskNeedInfo:
return p.handleTaskNeedInfo(ctx, msg)
case types.P2PTaskInfoProvided:
return p.handleTaskInfoProvided(ctx, msg)
case types.P2PTaskStatusUpdate:
return p.handleTaskStatusUpdate(ctx, msg)
case types.P2PTaskComplete:
return p.handleTaskComplete(ctx, msg)
case types.P2PTaskFailed:
return p.handleTaskFailed(ctx, msg)
case types.P2PTaskCancel:
return p.handleTaskCancel(ctx, msg)
case types.P2PTaskAck:
return p.handleTaskAck(ctx, msg)
case types.P2PTaskNeedHuman:
return p.handleTaskNeedHuman(ctx, msg)
case types.P2PHumanDecision:
return p.handleHumanDecision(ctx, msg)
case types.P2PAck:
return p.handleAck(ctx, msg)
case types.P2PNack:
return p.handleNack(ctx, msg)
case types.P2PHeartbeat:
return p.handleHeartbeat(ctx, msg)
default:
return p.newNACK(msg, types.NewSynapseError(
types.ErrMessageFormatInvalid,
fmt.Sprintf("Unknown message type: %s", msg.Type),
nil,
))
}
}
// =============================================================================
// Message Handlers
// =============================================================================
// handleTaskRequest handles incoming task requests
func (p *P2PProtocol) handleTaskRequest(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskRequestPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(
types.ErrMessageFormatInvalid,
"Invalid task request payload",
err.Error(),
))
}
taskID := payload.Task.ID
log.Printf("[P2P] Task request received: %s (type: %s)", taskID, payload.Task.Type)
// Check if we have a task handler
if p.taskHandler == nil {
return p.newReject(msg, taskID, "agent_not_ready", "Task handler not configured", nil)
}
// Validate the task
missingFields, canHandle := p.taskHandler.ValidateTask(payload.Task.Type, payload.Task.Payload)
if !canHandle {
if len(missingFields) > 0 {
// Need more info
return p.newNeedInfo(msg, taskID, missingFields)
}
return p.newReject(msg, taskID, "capability_lacking", "Agent cannot handle this task type", nil)
}
// Create task context
taskCtx, cancel := context.WithTimeout(ctx, p.config.TaskTimeout)
defer cancel()
// Execute task asynchronously
go p.executeTask(taskCtx, msg, taskID, payload.Task.Type, payload.Task.Payload)
// Return immediate confirmation
return p.newAck(msg, taskID, "task_accepted")
}
// executeTask executes a task and handles callbacks
func (p *P2PProtocol) executeTask(ctx context.Context, origMsg *types.UnifiedSynapseMessage, taskID, taskType string, payload map[string]interface{}) {
// Send initial status update
p.sendStatusUpdate(ctx, taskID, types.P2PStatusExecuting, 0, "Task started")
// Execute the task
result, err := p.taskHandler.ExecuteTask(ctx, taskType, payload)
if err != nil {
// Task failed
p.sendTaskFailed(ctx, taskID, "execution_failed", err.Error(), true, nil)
return
}
// Task completed
p.sendTaskComplete(ctx, taskID, result)
}
// sendStatusUpdate sends a status update to the sender
func (p *P2PProtocol) sendStatusUpdate(ctx context.Context, taskID string, status types.P2PTaskStatus, progress int, message string) {
if p.callbackSender == nil {
return
}
payload := types.TaskStatusUpdatePayload{
TaskID: taskID,
Status: string(status),
Progress: progress,
Message: message,
}
payloadBytes, _ := json.Marshal(payload)
response := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskStatusUpdate),
Sender: p.agentEndpoint,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
log.Printf("[P2P] Failed to send status update: %v", err)
}
}
// sendTaskComplete sends task completion notification
func (p *P2PProtocol) sendTaskComplete(ctx context.Context, taskID string, result any) {
if p.callbackSender == nil {
return
}
payload := types.TaskCompletePayload{}
payload.TaskID = taskID
payload.Result.OutputType = "task_result"
payload.Result.Output = result
payloadBytes, _ := json.Marshal(payload)
response := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskComplete),
Sender: p.agentEndpoint,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
log.Printf("[P2P] Failed to send task complete: %v", err)
}
}
// sendTaskFailed sends task failure notification
func (p *P2PProtocol) sendTaskFailed(ctx context.Context, taskID, errorCode, errorMessage string, recoverable bool, partialResult any) {
if p.callbackSender == nil {
return
}
payload := types.TaskFailedPayload{}
payload.TaskID = taskID
payload.Error.Code = errorCode
payload.Error.Message = errorMessage
payload.Error.Recoverable = recoverable
payload.PartialResult = partialResult
payloadBytes, _ := json.Marshal(payload)
response := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskFailed),
Sender: p.agentEndpoint,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
log.Printf("[P2P] Failed to send task failed: %v", err)
}
}
// handleTaskConfirm handles task confirmation from receiver
func (p *P2PProtocol) handleTaskConfirm(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskConfirmPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid confirm payload", err.Error()))
}
log.Printf("[P2P] Task confirmed: %s (estimated: %ds)", payload.TaskID, payload.EstimatedDuration)
return p.newAck(msg, payload.TaskID, "confirmed")
}
// handleTaskReject handles task rejection from receiver
func (p *P2PProtocol) handleTaskReject(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskRejectPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid reject payload", err.Error()))
}
log.Printf("[P2P] Task rejected: %s (%s: %s)", payload.TaskID, payload.Reason.Code, payload.Reason.Message)
return p.newAck(msg, payload.TaskID, "rejected")
}
// handleTaskNeedInfo handles information request from receiver
func (p *P2PProtocol) handleTaskNeedInfo(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskNeedInfoPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid need info payload", err.Error()))
}
log.Printf("[P2P] Information requested: %s (missing %d fields)", payload.TaskID, len(payload.MissingFields))
// This would typically be handled by the application logic
// For now, just acknowledge
return p.newAck(msg, payload.TaskID, "info_request_received")
}
// handleTaskInfoProvided handles information provided by sender
func (p *P2PProtocol) handleTaskInfoProvided(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskInfoProvidedPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid info provided payload", err.Error()))
}
log.Printf("[P2P] Information provided: %s (%d fields)", payload.TaskID, len(payload.ProvidedInfo))
return p.newAck(msg, payload.TaskID, "info_received")
}
// handleTaskStatusUpdate handles status updates from receiver
func (p *P2PProtocol) handleTaskStatusUpdate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskStatusUpdatePayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid status update payload", err.Error()))
}
log.Printf("[P2P] Status update: %s - %s (progress: %d%%)", payload.TaskID, payload.Status, payload.Progress)
return p.newAck(msg, payload.TaskID, "status_received")
}
// handleTaskComplete handles task completion notification
func (p *P2PProtocol) handleTaskComplete(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskCompletePayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid complete payload", err.Error()))
}
log.Printf("[P2P] Task completed: %s", payload.TaskID)
return p.newAck(msg, payload.TaskID, "completed")
}
// handleTaskFailed handles task failure notification
func (p *P2PProtocol) handleTaskFailed(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskFailedPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid failed payload", err.Error()))
}
log.Printf("[P2P] Task failed: %s (%s: %s)", payload.TaskID, payload.Error.Code, payload.Error.Message)
return p.newAck(msg, payload.TaskID, "failure_noted")
}
// handleTaskCancel handles task cancellation
func (p *P2PProtocol) handleTaskCancel(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskCancelPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid cancel payload", err.Error()))
}
log.Printf("[P2P] Task cancelled: %s (by %s)", payload.TaskID, payload.CancelledBy)
return p.newAck(msg, payload.TaskID, "cancelled")
}
// handleTaskAck handles task-level acknowledgment
func (p *P2PProtocol) handleTaskAck(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
log.Printf("[P2P] Task ACK received for message: %s", msg.ReplyTo)
return nil, nil // No response needed for ACK
}
// handleTaskNeedHuman handles human intervention request
func (p *P2PProtocol) handleTaskNeedHuman(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.TaskNeedHumanPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid need human payload", err.Error()))
}
log.Printf("[P2P] Human intervention needed: %s (level: %d)", payload.TaskID, payload.EscalationLevel)
// Store the HiL request and wait for human decision
// This would typically be handled by a HiL manager
return p.newAck(msg, payload.TaskID, "human_intervention_requested")
}
// handleHumanDecision handles human decision response
func (p *P2PProtocol) handleHumanDecision(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
var payload types.HumanDecisionPayload
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid human decision payload", err.Error()))
}
log.Printf("[P2P] Human decision: %s (action: %s, by %s)", payload.TaskID, payload.Decision.Action, payload.DecidedBy.UserName)
// Process the human decision
// This would resume the task execution with the decision
return p.newAck(msg, payload.TaskID, "decision_received")
}
// handleAck handles generic ACK
func (p *P2PProtocol) handleAck(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
log.Printf("[P2P] ACK received for: %s", msg.ReplyTo)
return nil, nil
}
// handleNack handles generic NACK
func (p *P2PProtocol) handleNack(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
log.Printf("[P2P] NACK received for: %s", msg.ReplyTo)
return nil, nil
}
// handleHeartbeat handles heartbeat
func (p *P2PProtocol) handleHeartbeat(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
return p.newAck(msg, "", "alive")
}
// =============================================================================
// Response Builders
// =============================================================================
// newAck creates an ACK response
func (p *P2PProtocol) newAck(msg *types.UnifiedSynapseMessage, taskID, note string) (*types.UnifiedSynapseMessage, error) {
return &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PAck),
Sender: p.agentEndpoint,
Receiver: &msg.Sender,
CorrelationID: msg.CorrelationID,
ReplyTo: msg.ID,
Timestamp: types.NowTimestamp(),
}, nil
}
// newNACK creates a NACK response
func (p *P2PProtocol) newNACK(msg *types.UnifiedSynapseMessage, err *types.SynapseError) (*types.UnifiedSynapseMessage, error) {
return nil, err
}
// newReject creates a task rejection response
func (p *P2PProtocol) newReject(msg *types.UnifiedSynapseMessage, taskID, reasonCode, reasonMessage string, alternatives *struct {
SuggestedAgentID string `json:"suggested_agent_id,omitempty"`
RetryAfter int `json:"retry_after,omitempty"`
PartialSupport bool `json:"partial_support,omitempty"`
}) (*types.UnifiedSynapseMessage, error) {
payload := types.TaskRejectPayload{}
payload.TaskID = taskID
payload.Reason.Code = reasonCode
payload.Reason.Message = reasonMessage
if alternatives != nil {
payload.Alternatives = alternatives
}
payloadBytes, _ := json.Marshal(payload)
return &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskReject),
Sender: p.agentEndpoint,
Receiver: &msg.Sender,
CorrelationID: msg.CorrelationID,
ReplyTo: msg.ID,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}, nil
}
// newNeedInfo creates a need info response
func (p *P2PProtocol) newNeedInfo(msg *types.UnifiedSynapseMessage, taskID string, missingFields []types.MissingField) (*types.UnifiedSynapseMessage, error) {
payload := types.TaskNeedInfoPayload{}
payload.TaskID = taskID
payload.MissingFields = missingFields
payloadBytes, _ := json.Marshal(payload)
return &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskNeedInfo),
Sender: p.agentEndpoint,
Receiver: &msg.Sender,
CorrelationID: msg.CorrelationID,
ReplyTo: msg.ID,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}, nil
}
// =============================================================================
// Validation
// =============================================================================
func (p *P2PProtocol) validateMessage(msg *types.UnifiedSynapseMessage) error {
if msg.ID == "" {
return types.ErrMessageFormatInvalidError
}
if msg.Sender.AgentID == "" {
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender agent_id", nil)
}
if msg.Sender.Endpoint == "" {
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender endpoint", nil)
}
return nil
}
// =============================================================================
// Task Management
// =============================================================================
// GetTaskStatus returns the status of a task
func (p *P2PProtocol) GetTaskStatus(taskID string) (types.P2PTaskStatus, bool) {
p.mu.RLock()
defer p.mu.RUnlock()
status, ok := p.tasks[taskID]
if !ok {
return "", false
}
return *status, true
}
// ListTasks returns all tasks
func (p *P2PProtocol) ListTasks() map[string]types.P2PTaskStatus {
p.mu.RLock()
defer p.mu.RUnlock()
result := make(map[string]types.P2PTaskStatus)
for k, v := range p.tasks {
result[k] = *v
}
return result
}

View File

@@ -0,0 +1,494 @@
package p2p
import (
"context"
"encoding/json"
"testing"
"time"
"synapse/pkg/types"
)
// =============================================================================
// Mock Task Handler
// =============================================================================
type mockTaskHandler struct {
canHandle bool
missingFields []types.MissingField
result any
err error
}
func (m *mockTaskHandler) ExecuteTask(ctx context.Context, taskType string, payload map[string]interface{}) (any, error) {
return m.result, m.err
}
func (m *mockTaskHandler) ValidateTask(taskType string, payload map[string]interface{}) ([]types.MissingField, bool) {
return m.missingFields, m.canHandle
}
func (m *mockTaskHandler) GetCapabilities() []string {
return []string{"text_generation", "image_generation"}
}
// =============================================================================
// Mock Callback Sender
// =============================================================================
type mockCallbackSender struct {
lastMsg *types.UnifiedSynapseMessage
err error
}
func (m *mockCallbackSender) SendCallback(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
m.lastMsg = msg
return m.err
}
// =============================================================================
// P2PProtocol 测试
// =============================================================================
func TestNewP2PProtocol(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
if proto == nil {
t.Error("Protocol should not be nil")
}
if proto.AgentEndpoint().AgentID != "agent-001" {
t.Error("Agent ID mismatch")
}
}
func TestP2PProtocolWithCustomConfig(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
config := &P2PConfig{
MaxRetries: 10,
RetryBaseDelay: 5 * time.Second,
TaskTimeout: 10 * time.Minute,
HeartbeatInterval: 60 * time.Second,
}
proto := NewP2PProtocol(ep, config)
if proto.config.MaxRetries != 10 {
t.Errorf("MaxRetries mismatch: got %d, want 10", proto.config.MaxRetries)
}
}
func TestDefaultP2PConfig(t *testing.T) {
config := DefaultP2PConfig()
if config.MaxRetries != 5 {
t.Errorf("Default MaxRetries should be 5")
}
if config.TaskTimeout != 5*time.Minute {
t.Errorf("Default TaskTimeout should be 5 minutes")
}
}
// =============================================================================
// 消息处理测试
// =============================================================================
func TestHandleTaskRequest(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
proto.SetTaskHandler(&mockTaskHandler{
canHandle: true,
result: "test result",
})
// 构造任务请求消息
taskReq := types.TaskRequestPayload{}
taskReq.Task.ID = "task-001"
taskReq.Task.Type = "text_generation"
taskReq.Task.Priority = types.PriorityNormal
taskReq.Task.Payload = map[string]interface{}{"prompt": "test"}
payloadBytes, _ := json.Marshal(taskReq)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
resp, err := proto.HandleMessage(context.Background(), msg)
if err != nil {
t.Errorf("HandleMessage failed: %v", err)
}
if resp == nil {
t.Error("Response should not be nil")
}
}
func TestHandleTaskReject(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
proto.SetTaskHandler(&mockTaskHandler{
canHandle: false,
missingFields: nil,
})
// 构造任务请求消息
taskReq := types.TaskRequestPayload{}
taskReq.Task.ID = "task-001"
taskReq.Task.Type = "unsupported_type"
taskReq.Task.Priority = types.PriorityNormal
payloadBytes, _ := json.Marshal(taskReq)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
resp, err := proto.HandleMessage(context.Background(), msg)
if err != nil {
t.Errorf("HandleMessage should not return error for rejection: %v", err)
}
if resp == nil {
t.Error("Response should not be nil")
}
// 应该返回拒绝消息
if resp.Type != string(types.P2PTaskReject) {
t.Errorf("Expected reject response, got: %s", resp.Type)
}
}
func TestHandleHeartbeat(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PHeartbeat),
Sender: types.AgentEndpoint{AgentID: "agent-002"},
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
resp, err := proto.HandleMessage(context.Background(), msg)
if err != nil {
t.Errorf("HandleHeartbeat failed: %v", err)
}
if resp == nil {
t.Error("Heartbeat response should not be nil")
}
}
func TestHandleAck(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PAck),
Sender: types.AgentEndpoint{AgentID: "agent-002"},
ReplyTo: "msg-001",
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
resp, err := proto.HandleMessage(context.Background(), msg)
if err != nil {
t.Errorf("HandleAck failed: %v", err)
}
// ACK 不需要响应
if resp != nil {
t.Error("ACK should not produce a response")
}
}
// =============================================================================
// 消息验证测试
// =============================================================================
func TestValidateMessage(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
// 有效消息
validMsg := &types.UnifiedSynapseMessage{
ID: "msg-001",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
if err := proto.validateMessage(validMsg); err != nil {
t.Errorf("Valid message should pass validation: %v", err)
}
// 缺少 ID 的消息
noIDMsg := &types.UnifiedSynapseMessage{
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
if err := proto.validateMessage(noIDMsg); err == nil {
t.Error("Message without ID should fail validation")
}
// 缺少 Sender AgentID 的消息
noSenderMsg := &types.UnifiedSynapseMessage{
ID: "msg-001",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{Endpoint: "http://localhost:8081"},
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
if err := proto.validateMessage(noSenderMsg); err == nil {
t.Error("Message without sender AgentID should fail validation")
}
}
// =============================================================================
// 状态管理测试
// =============================================================================
func TestGetTaskStatus(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
// 查询不存在的任务
status, ok := proto.GetTaskStatus("nonexistent")
if ok {
t.Error("Nonexistent task should not be found")
}
// 先通过任务请求添加任务状态
taskReq := types.TaskRequestPayload{}
taskReq.Task.ID = "task-001"
taskReq.Task.Type = "text_generation"
taskReq.Task.Priority = types.PriorityNormal
taskReq.Task.Payload = map[string]interface{}{"prompt": "test"}
payloadBytes, _ := json.Marshal(taskReq)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
proto.HandleMessage(context.Background(), msg)
// 然后查询状态
status, ok = proto.GetTaskStatus("task-001")
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)
}
}
func TestListTasks(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
// 初始应该为空
tasks := proto.ListTasks()
if len(tasks) != 0 {
t.Error("Initial task list should be empty")
}
// 添加任务(通过消息处理)
taskReq := types.TaskRequestPayload{}
taskReq.Task.ID = "task-001"
taskReq.Task.Type = "text_generation"
taskReq.Task.Priority = types.PriorityNormal
payloadBytes, _ := json.Marshal(taskReq)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
proto.HandleMessage(context.Background(), msg)
tasks = proto.ListTasks()
if len(tasks) < 1 {
t.Errorf("Task list should have at least 1 item: got %d", len(tasks))
}
}
// =============================================================================
// 回调发送测试
// =============================================================================
func TestSendStatusUpdate(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
mockSender := &mockCallbackSender{}
proto.SetCallbackSender(mockSender)
// 发送状态更新
proto.sendStatusUpdate(context.Background(), "task-001", types.P2PStatusExecuting, 50, "Processing")
if mockSender.lastMsg == nil {
t.Error("Callback should have been sent")
}
if mockSender.lastMsg.Type != string(types.P2PTaskStatusUpdate) {
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
}
}
func TestSendTaskComplete(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
mockSender := &mockCallbackSender{}
proto.SetCallbackSender(mockSender)
// 发送完成通知
proto.sendTaskComplete(context.Background(), "task-001", "test result")
if mockSender.lastMsg == nil {
t.Error("Callback should have been sent")
}
if mockSender.lastMsg.Type != string(types.P2PTaskComplete) {
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
}
}
func TestSendTaskFailed(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
mockSender := &mockCallbackSender{}
proto.SetCallbackSender(mockSender)
// 发送失败通知
proto.sendTaskFailed(context.Background(), "task-001", "execution_failed", "test error", true, nil)
if mockSender.lastMsg == nil {
t.Error("Callback should have been sent")
}
if mockSender.lastMsg.Type != string(types.P2PTaskFailed) {
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
}
}
// =============================================================================
// 错误处理测试
// =============================================================================
func TestHandleInvalidPayload(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: json.RawMessage("invalid json"),
Timestamp: types.NowTimestamp(),
}
resp, err := proto.HandleMessage(context.Background(), msg)
if err != nil {
t.Errorf("Should handle invalid payload gracefully: %v", err)
}
// 应该返回 NACK
if resp == nil {
t.Error("Should return NACK for invalid payload")
}
}
func TestHandleUnknownMessageType(t *testing.T) {
ep := types.AgentEndpoint{
AgentID: "agent-001",
Endpoint: "http://localhost:8080",
}
proto := NewP2PProtocol(ep, nil)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: "p2p:unknown_type",
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
Payload: json.RawMessage("{}"),
Timestamp: types.NowTimestamp(),
}
_, err := proto.HandleMessage(context.Background(), msg)
if err == nil {
t.Error("Unknown message type should return error")
}
}