Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
add stdio support
Antonio Ojeac22b3eed6ddd
diff --git a/api/sam.pb.go b/api/sam.pb.goindex 086e8972..e80bc9a2 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -507,6 +507,148 @@ func (x *ServiceInfo) GetDescription() string {return ""}+type CommandBackend struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Command []string `protobuf:"bytes,1,rep,name=command,proto3" json:"command,omitempty"`+ Env map[string]string `protobuf:"bytes,2,rep,name=env,proto3" json:"env,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *CommandBackend) Reset() {+ *x = CommandBackend{}+ mi := &file_api_sam_proto_msgTypes[6]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *CommandBackend) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*CommandBackend) ProtoMessage() {}++func (x *CommandBackend) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[6]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use CommandBackend.ProtoReflect.Descriptor instead.+func (*CommandBackend) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{6}+}++func (x *CommandBackend) GetCommand() []string {+ if x != nil {+ return x.Command+ }+ return nil+}++func (x *CommandBackend) GetEnv() map[string]string {+ if x != nil {+ return x.Env+ }+ return nil+}++type RegisterServiceRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Service *ServiceInfo `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"`+ // Types that are valid to be assigned to Backend:+ //+ // *RegisterServiceRequest_TargetUrl+ // *RegisterServiceRequest_Command+ Backend isRegisterServiceRequest_Backend `protobuf_oneof:"backend"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RegisterServiceRequest) Reset() {+ *x = RegisterServiceRequest{}+ mi := &file_api_sam_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RegisterServiceRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RegisterServiceRequest) ProtoMessage() {}++func (x *RegisterServiceRequest) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RegisterServiceRequest.ProtoReflect.Descriptor instead.+func (*RegisterServiceRequest) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{7}+}++func (x *RegisterServiceRequest) GetService() *ServiceInfo {+ if x != nil {+ return x.Service+ }+ return nil+}++func (x *RegisterServiceRequest) GetBackend() isRegisterServiceRequest_Backend {+ if x != nil {+ return x.Backend+ }+ return nil+}++func (x *RegisterServiceRequest) GetTargetUrl() string {+ if x != nil {+ if x, ok := x.Backend.(*RegisterServiceRequest_TargetUrl); ok {+ return x.TargetUrl+ }+ }+ return ""+}++func (x *RegisterServiceRequest) GetCommand() *CommandBackend {+ if x != nil {+ if x, ok := x.Backend.(*RegisterServiceRequest_Command); ok {+ return x.Command+ }+ }+ return nil+}++type isRegisterServiceRequest_Backend interface {+ isRegisterServiceRequest_Backend()+}++type RegisterServiceRequest_TargetUrl struct {+ TargetUrl string `protobuf:"bytes,2,opt,name=target_url,json=targetUrl,proto3,oneof"`+}++type RegisterServiceRequest_Command struct {+ Command *CommandBackend `protobuf:"bytes,3,opt,name=command,proto3,oneof"`+}++func (*RegisterServiceRequest_TargetUrl) isRegisterServiceRequest_Backend() {}++func (*RegisterServiceRequest_Command) isRegisterServiceRequest_Backend() {}+type DiscoveredProvider struct {state protoimpl.MessageState `protogen:"open.v1"`PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`@@ -517,7 +659,7 @@ type DiscoveredProvider struct {func (x *DiscoveredProvider) Reset() {*x = DiscoveredProvider{}- mi := &file_api_sam_proto_msgTypes[6]+ mi := &file_api_sam_proto_msgTypes[8]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -529,7 +671,7 @@ func (x *DiscoveredProvider) String() string {func (*DiscoveredProvider) ProtoMessage() {}func (x *DiscoveredProvider) ProtoReflect() protoreflect.Message {- mi := &file_api_sam_proto_msgTypes[6]+ mi := &file_api_sam_proto_msgTypes[8]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -542,7 +684,7 @@ func (x *DiscoveredProvider) ProtoReflect() protoreflect.Message {// Deprecated: Use DiscoveredProvider.ProtoReflect.Descriptor instead.func (*DiscoveredProvider) Descriptor() ([]byte, []int) {- return file_api_sam_proto_rawDescGZIP(), []int{6}+ return file_api_sam_proto_rawDescGZIP(), []int{8}}func (x *DiscoveredProvider) GetPeerId() string {@@ -597,7 +739,19 @@ const file_api_sam_proto_rawDesc = "" +"\vServiceInfo\x12'\n" +"\x04type\x18\x01 \x01(\x0e2\x13.sam.v1.ServiceTypeR\x04type\x12\x12\n" +"\x04name\x18\x02 \x01(\tR\x04name\x12 \n" +- "\vdescription\x18\x03 \x01(\tR\vdescription\"U\n" ++ "\vdescription\x18\x03 \x01(\tR\vdescription\"\x95\x01\n" ++ "\x0eCommandBackend\x12\x18\n" ++ "\acommand\x18\x01 \x03(\tR\acommand\x121\n" ++ "\x03env\x18\x02 \x03(\v2\x1f.sam.v1.CommandBackend.EnvEntryR\x03env\x1a6\n" ++ "\bEnvEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xa7\x01\n" ++ "\x16RegisterServiceRequest\x12-\n" ++ "\aservice\x18\x01 \x01(\v2\x13.sam.v1.ServiceInfoR\aservice\x12\x1f\n" ++ "\n" ++ "target_url\x18\x02 \x01(\tH\x00R\ttargetUrl\x122\n" ++ "\acommand\x18\x03 \x01(\v2\x16.sam.v1.CommandBackendH\x00R\acommandB\t\n" ++ "\abackend\"U\n" +"\x12DiscoveredProvider\x12\x17\n" +"\apeer_id\x18\x01 \x01(\tR\x06peerId\x12&\n" +"\x0flocal_proxy_url\x18\x02 \x01(\tR\rlocalProxyUrl*s\n" +@@ -620,26 +774,32 @@ func file_api_sam_proto_rawDescGZIP() []byte {}var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 2)-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 7)+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 10)var file_api_sam_proto_goTypes = []any{- (ServiceType)(0), // 0: sam.v1.ServiceType- (MeshEvent_Type)(0), // 1: sam.v1.MeshEvent.Type- (*AuthFrame)(nil), // 2: sam.v1.AuthFrame- (*AuthResponse)(nil), // 3: sam.v1.AuthResponse- (*MeshEvent)(nil), // 4: sam.v1.MeshEvent- (*EnrollRequest)(nil), // 5: sam.v1.EnrollRequest- (*EnrollResponse)(nil), // 6: sam.v1.EnrollResponse- (*ServiceInfo)(nil), // 7: sam.v1.ServiceInfo- (*DiscoveredProvider)(nil), // 8: sam.v1.DiscoveredProvider+ (ServiceType)(0), // 0: sam.v1.ServiceType+ (MeshEvent_Type)(0), // 1: sam.v1.MeshEvent.Type+ (*AuthFrame)(nil), // 2: sam.v1.AuthFrame+ (*AuthResponse)(nil), // 3: sam.v1.AuthResponse+ (*MeshEvent)(nil), // 4: sam.v1.MeshEvent+ (*EnrollRequest)(nil), // 5: sam.v1.EnrollRequest+ (*EnrollResponse)(nil), // 6: sam.v1.EnrollResponse+ (*ServiceInfo)(nil), // 7: sam.v1.ServiceInfo+ (*CommandBackend)(nil), // 8: sam.v1.CommandBackend+ (*RegisterServiceRequest)(nil), // 9: sam.v1.RegisterServiceRequest+ (*DiscoveredProvider)(nil), // 10: sam.v1.DiscoveredProvider+ nil, // 11: sam.v1.CommandBackend.EnvEntry}var file_api_sam_proto_depIdxs = []int32{- 1, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type- 0, // 1: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType- 2, // [2:2] is the sub-list for method output_type- 2, // [2:2] is the sub-list for method input_type- 2, // [2:2] is the sub-list for extension type_name- 2, // [2:2] is the sub-list for extension extendee- 0, // [0:2] is the sub-list for field type_name+ 1, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type+ 0, // 1: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType+ 11, // 2: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry+ 7, // 3: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo+ 8, // 4: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend+ 5, // [5:5] is the sub-list for method output_type+ 5, // [5:5] is the sub-list for method input_type+ 5, // [5:5] is the sub-list for extension type_name+ 5, // [5:5] is the sub-list for extension extendee+ 0, // [0:5] is the sub-list for field type_name}func init() { file_api_sam_proto_init() }@@ -647,13 +807,17 @@ func file_api_sam_proto_init() {if File_api_sam_proto != nil {return}+ file_api_sam_proto_msgTypes[7].OneofWrappers = []any{+ (*RegisterServiceRequest_TargetUrl)(nil),+ (*RegisterServiceRequest_Command)(nil),+ }type x struct{}out := protoimpl.TypeBuilder{File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),NumEnums: 2,- NumMessages: 7,+ NumMessages: 10,NumExtensions: 0,NumServices: 0,},diff --git a/api/sam.proto b/api/sam.protoindex 377d4e2c..66db58b6 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -70,6 +70,19 @@ message ServiceInfo {string description = 3;}+message CommandBackend {+ repeated string command = 1;+ map<string, string> env = 2;+}++message RegisterServiceRequest {+ ServiceInfo service = 1;+ oneof backend {+ string target_url = 2;+ CommandBackend command = 3;+ }+}+message DiscoveredProvider {string peer_id = 1;string local_proxy_url = 2;diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex 29e1d41d..6845665f 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -20,8 +20,13 @@ import ("crypto/sha256""encoding/hex""fmt"+ "io"+ "bufio""net/http"+ "net/http/httputil"+ "net/url""os"+ "os/exec""strings""sync"@@ -70,6 +75,12 @@ type TrustedKey struct {ReceivedAt time.Time}+type ServiceManifest struct {+ Info *api.ServiceInfo+ Handler http.Handler+ Cmd *exec.Cmd+}+type SamNode struct {Host host.HostDHT *dht.IpfsDHT@@ -86,8 +97,7 @@ type SamNode struct {trustedKeys []TrustedKeykeysMu sync.RWMutexrateLimiter *PeerRateLimiter- services map[string]*api.ServiceInfo- serviceHandlers map[string]http.Handler+ services map[string]*ServiceManifestservicesMu sync.RWMutexBoundHTTPAddr string}@@ -105,8 +115,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PknownPeers: make(map[string]bool),receivedMsgs: make(map[string][]string),topics: make(map[string]*pubsub.Topic),- services: make(map[string]*api.ServiceInfo),- serviceHandlers: make(map[string]http.Handler),+ services: make(map[string]*ServiceManifest),LocalPolicy: localPolicy,}@@ -657,7 +666,124 @@ func serviceNameToCID(serviceType api.ServiceType, serviceName string) (cid.Cid,return cid.NewCidV1(cid.Raw, hash), nil}-func (n *SamNode) RegisterService(ctx context.Context, info *api.ServiceInfo) error {+type StdioBridge struct {+ cmd *exec.Cmd+ stdin io.WriteCloser+ stdout io.ReadCloser+ mu sync.Mutex+ clients map[chan string]bool+}++func (b *StdioBridge) Start() {+ b.clients = make(map[chan string]bool)+ go func() {+ scanner := bufio.NewScanner(b.stdout)+ for scanner.Scan() {+ line := scanner.Text()+ b.mu.Lock()+ for ch := range b.clients {+ select {+ case ch <- line:+ default:+ }+ }+ b.mu.Unlock()+ }+ }()+}++func (b *StdioBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ switch r.Method {+ case http.MethodGet:+ w.Header().Set("Content-Type", "text/event-stream")+ w.Header().Set("Cache-Control", "no-cache")+ w.Header().Set("Connection", "keep-alive")++ flusher, ok := w.(http.Flusher)+ if !ok {+ http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)+ return+ }++ ch := make(chan string, 10)+ b.mu.Lock()+ b.clients[ch] = true+ b.mu.Unlock()++ defer func() {+ b.mu.Lock()+ delete(b.clients, ch)+ b.mu.Unlock()+ close(ch)+ }()++ ctx := r.Context()+ for {+ select {+ case <-ctx.Done():+ return+ case line := <-ch:+ if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {+ logger.Errorf("Failed to write to SSE client: %v", err)+ return+ }+ flusher.Flush()+ }+ }+ case http.MethodPost:+ body, err := io.ReadAll(r.Body)+ if err != nil {+ http.Error(w, "Failed to read body", http.StatusInternalServerError)+ return+ }+ _ = r.Body.Close()++ b.mu.Lock()+ _, err = b.stdin.Write(append(body, '\n'))+ b.mu.Unlock()++ if err != nil {+ http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError)+ return+ }+ w.WriteHeader(http.StatusOK)+ default:+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}++func (n *SamNode) createStdioBridgeHandler(cmdBackend *api.CommandBackend) (http.Handler, *exec.Cmd, error) {+ cmd := exec.Command(cmdBackend.Command[0], cmdBackend.Command[1:]...)+ cmd.Env = os.Environ()+ for k, v := range cmdBackend.Env {+ cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))+ }++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ return nil, nil, err+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ return nil, nil, err+ }++ if err := cmd.Start(); err != nil {+ return nil, nil, err+ }++ bridge := &StdioBridge{+ cmd: cmd,+ stdin: stdin,+ stdout: stdout,+ }+ bridge.Start()++ return bridge, cmd, nil+}++func (n *SamNode) RegisterService(ctx context.Context, req *api.RegisterServiceRequest) error {+ info := req.Serviceif info.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {return fmt.Errorf("cannot register service with unspecified type")}@@ -674,8 +800,31 @@ func (n *SamNode) RegisterService(ctx context.Context, info *api.ServiceInfo) erreturn err}+ var handler http.Handler+ var cmd *exec.Cmd++ switch b := req.Backend.(type) {+ case *api.RegisterServiceRequest_TargetUrl:+ targetURL, err := url.Parse(b.TargetUrl)+ if err != nil {+ return fmt.Errorf("invalid target URL: %w", err)+ }+ handler = httputil.NewSingleHostReverseProxy(targetURL)+ case *api.RegisterServiceRequest_Command:+ handler, cmd, err = n.createStdioBridgeHandler(b.Command)+ if err != nil {+ return fmt.Errorf("failed to create stdio bridge: %w", err)+ }+ default:+ return fmt.Errorf("unsupported backend type")+ }+n.servicesMu.Lock()- n.services[info.Name] = info+ n.services[info.Name] = &ServiceManifest{+ Info: info,+ Handler: handler,+ Cmd: cmd,+ }n.servicesMu.Unlock()logger.Infof("[ServiceRegistry] Registering service %s/%s (CID: %s)", info.Type, info.Name, c)@@ -684,6 +833,12 @@ func (n *SamNode) RegisterService(ctx context.Context, info *api.ServiceInfo) erfunc (n *SamNode) UnregisterService(ctx context.Context, serviceName string) error {n.servicesMu.Lock()+ manifest, ok := n.services[serviceName]+ if ok && manifest.Cmd != nil {+ if err := manifest.Cmd.Process.Kill(); err != nil {+ logger.Errorf("Failed to kill process for service %s: %v", serviceName, err)+ }+ }delete(n.services, serviceName)n.servicesMu.Unlock()@@ -757,8 +912,8 @@ func (n *SamNode) ListLocalServices() []*api.ServiceInfo {defer n.servicesMu.RUnlock()var services []*api.ServiceInfo- for _, info := range n.services {- services = append(services, info)+ for _, manifest := range n.services {+ services = append(services, manifest.Info)}return services}@@ -790,17 +945,17 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {return}- n.mu.Lock()- handler, ok := n.serviceHandlers[serviceName]- n.mu.Unlock()+ n.servicesMu.RLock()+ manifest, ok := n.services[serviceName]+ n.servicesMu.RUnlock()- if !ok {+ if !ok || manifest.Handler == nil {http.Error(w, "Service not found", http.StatusNotFound)return}r.URL.Path = "/" + upstreamPath- handler.ServeHTTP(w, r)+ manifest.Handler.ServeHTTP(w, r)}),}@@ -825,7 +980,13 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {}func (n *SamNode) RegisterServiceHandler(name string, handler http.Handler) {- n.mu.Lock()- defer n.mu.Unlock()- n.serviceHandlers[name] = handler+ n.servicesMu.Lock()+ defer n.servicesMu.Unlock()+ if manifest, ok := n.services[name]; ok {+ manifest.Handler = handler+ } else {+ n.services[name] = &ServiceManifest{+ Handler: handler,+ }+ }}diff --git a/cmd/sam-node/proxy_test.go b/cmd/sam-node/proxy_test.goindex 0e9ba4e4..aaa32761 100644--- a/cmd/sam-node/proxy_test.go+++ b/cmd/sam-node/proxy_test.go@@ -6,6 +6,8 @@ import ("io""net/http""net/http/httptest"+ "net/http/httputil"+ "net/url""testing""time"@@ -95,17 +97,21 @@ func TestDatapathIntegration(t *testing.T) {Name: serviceName,}- // We need to make sure the node knows how to handle this service locally.- // We use the dummy server as the handler.- nodeA.RegisterServiceHandler(serviceName, dummyServer.Config.Handler)-- // We also register it in the DHT so Node B can find it if needed (though we use direct URL in test)+ // We register it in the DHT and also setup the local handler.// We ignore the error because DHT Provide might fail if routing table is empty in this isolated test.- _ = nodeA.RegisterService(ctx, serviceInfo)-+ _ = nodeA.RegisterService(ctx, &api.RegisterServiceRequest{+ Service: serviceInfo,+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: dummyServer.URL},+ })+// Manually add to services map to ensure it's registered for the test lookup+ // because RegisterService might have failed due to DHT not being ready in this isolated test.+ targetURL, _ := url.Parse(dummyServer.URL)nodeA.servicesMu.Lock()- nodeA.services[serviceName] = serviceInfo+ nodeA.services[serviceName] = &ServiceManifest{+ Info: serviceInfo,+ Handler: httputil.NewSingleHostReverseProxy(targetURL),+ }nodeA.servicesMu.Unlock()// Start the Sidecar server for Node B to get BoundHTTPAddr populateddiff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.goindex 40b7eb94..7434fad3 100644--- a/cmd/sam-node/sidecar.go+++ b/cmd/sam-node/sidecar.go@@ -19,7 +19,9 @@ import ("crypto/x509""encoding/json""fmt"+ "io""net"+ "google.golang.org/protobuf/encoding/protojson""net/http""net/http/httputil""os"@@ -168,17 +170,34 @@ func handleRegisterService(node *SamNode, w http.ResponseWriter, r *http.Requestreturn}- var req api.ServiceInfo- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ http.Error(w, "Failed to read request body", http.StatusInternalServerError)+ return+ }+ _ = r.Body.Close()++ var req api.RegisterServiceRequest+ if err := protojson.Unmarshal(body, &req); err != nil {+ http.Error(w, fmt.Sprintf("Invalid request body: %v", err), http.StatusBadRequest)return}- if req.Name == "" || req.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {+ if req.Service == nil {+ http.Error(w, "service field is required", http.StatusBadRequest)+ return+ }++ if req.Service.Name == "" || req.Service.Type == api.ServiceType_SERVICE_TYPE_UNSPECIFIED {http.Error(w, "name and type are required", http.StatusBadRequest)return}+ if req.Backend == nil {+ http.Error(w, "backend is required", http.StatusBadRequest)+ return+ }+if err := node.RegisterService(r.Context(), &req); err != nil {http.Error(w, fmt.Sprintf("Failed to register service: %v", err), http.StatusInternalServerError)returndiff --git a/cmd/sam-node/sidecar_test.go b/cmd/sam-node/sidecar_test.goindex e0166c49..24a0f37c 100644--- a/cmd/sam-node/sidecar_test.go+++ b/cmd/sam-node/sidecar_test.go@@ -18,6 +18,7 @@ import ("bytes""context""encoding/json"+ "google.golang.org/protobuf/encoding/protojson""net/http""net/http/httptest""testing"@@ -143,12 +144,15 @@ func TestHandleRegisterService(t *testing.T) {time.Sleep(100 * time.Millisecond)node := &SamNode{- services: make(map[string]*api.ServiceInfo),+ services: make(map[string]*ServiceManifest),DHT: d,}- reqBody := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "test-service", Description: "test desc"}- body, err := json.Marshal(reqBody)+ reqBody := &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "test-service", Description: "test desc"},+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},+ }+ body, err := protojson.Marshal(reqBody)if err != nil {t.Fatalf("Failed to marshal request body: %v", err)}@@ -169,9 +173,9 @@ func TestHandleRegisterService(t *testing.T) {func TestHandleUnregisterService(t *testing.T) {node := &SamNode{- services: make(map[string]*api.ServiceInfo),+ services: make(map[string]*ServiceManifest),}- node.services["test-service"] = &api.ServiceInfo{Name: "test-service"}+ node.services["test-service"] = &ServiceManifest{Info: &api.ServiceInfo{Name: "test-service"}}reqBody := &api.ServiceInfo{Name: "test-service"}body, err := json.Marshal(reqBody)@@ -206,7 +210,7 @@ func TestHandleDiscoverService(t *testing.T) {defer func() { _ = d.Close() }()node := &SamNode{- services: make(map[string]*api.ServiceInfo),+ services: make(map[string]*ServiceManifest),DHT: d,Host: h,BoundHTTPAddr: "127.0.0.1:8080",@@ -265,14 +269,14 @@ func TestHandleDiscoverService(t *testing.T) {func TestListLocalServices(t *testing.T) {node := &SamNode{- services: make(map[string]*api.ServiceInfo),+ services: make(map[string]*ServiceManifest),}service1 := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "service1"}service2 := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_INFERENCE, Name: "service2"}- node.services["service1"] = service1- node.services["service2"] = service2+ node.services["service1"] = &ServiceManifest{Info: service1}+ node.services["service2"] = &ServiceManifest{Info: service2}services := node.ListLocalServices()@@ -280,3 +284,63 @@ func TestListLocalServices(t *testing.T) {t.Errorf("expected 2 services, got %d", len(services))}}++func TestHandleRegisterService_Validation(t *testing.T) {+ node := &SamNode{+ services: make(map[string]*ServiceManifest),+ }++ tests := []struct {+ name string+ reqBody *api.RegisterServiceRequest+ expectedStatus int+ }{+ {+ name: "Missing service",+ reqBody: &api.RegisterServiceRequest{+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},+ },+ expectedStatus: http.StatusBadRequest,+ },+ {+ name: "Missing name",+ reqBody: &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP},+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},+ },+ expectedStatus: http.StatusBadRequest,+ },+ {+ name: "Unspecified type",+ reqBody: &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Name: "test-service", Type: api.ServiceType_SERVICE_TYPE_UNSPECIFIED},+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},+ },+ expectedStatus: http.StatusBadRequest,+ },+ {+ name: "Missing backend",+ reqBody: &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Name: "test-service", Type: api.ServiceType_SERVICE_TYPE_MCP},+ },+ expectedStatus: http.StatusBadRequest,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ body, err := protojson.Marshal(tt.reqBody)+ if err != nil {+ t.Fatal(err)+ }+ req := httptest.NewRequest("POST", "/sam/service/register", bytes.NewBuffer(body))+ rr := httptest.NewRecorder()++ handleRegisterService(node, rr, req)++ if rr.Code != tt.expectedStatus {+ t.Errorf("expected status %d, got %d, body: %s", tt.expectedStatus, rr.Code, rr.Body.String())+ }+ })+ }+}diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.goindex 8320bfe8..4a0f24f3 100644--- a/tests/integration/service_discovery_test.go+++ b/tests/integration/service_discovery_test.go@@ -17,6 +17,7 @@ package integration_testimport ("bytes""encoding/json"+ "google.golang.org/protobuf/encoding/protojson""io""net/http""path/filepath"@@ -143,8 +144,18 @@ func waitForAPI(t *testing.T, addr string) {func registerService(t *testing.T, apiAddr, token, serviceName string) {t.Helper()- reqBody := map[string]any{"Type": api.ServiceType_SERVICE_TYPE_MCP, "Name": serviceName, "Description": "test desc"}- body, _ := json.Marshal(reqBody)+ reqData := &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{+ Type: api.ServiceType_SERVICE_TYPE_MCP,+ Name: serviceName,+ Description: "test desc",+ },+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: "http://localhost:8080"},+ }+ body, err := protojson.Marshal(reqData)+ if err != nil {+ t.Fatal(err)+ }req, _ := http.NewRequest("POST", "http://"+apiAddr+"/sam/service/register", bytes.NewBuffer(body))req.Header.Set("Authorization", "Bearer "+token)req.Header.Set("Content-Type", "application/json")