diff --git a/api/proto/workspace/v1/workspace.proto b/api/proto/workspace/v1/workspace.proto new file mode 100644 index 0000000..72ab8a7 --- /dev/null +++ b/api/proto/workspace/v1/workspace.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package qrixr.workspace.v1; + +option go_package = "github.com/Skoowshot/qrix-runtime/gen/go/workspace/v1;workspacev1"; + +service WorkspaceService { + rpc Create(CreateRequest) returns (CreateResponse); + rpc GetByName(GetByNameRequest) returns (GetByNameResponse); +} + +message CreateRequest { + string name = 1; +} + +message CreateResponse { + uint64 id = 1; +} + +message GetByNameRequest { + string name = 1; +} + +message GetByNameResponse { + uint64 id = 1; +} \ No newline at end of file diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..3e34221 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,13 @@ +version: v2 +managed: + enabled: true + override: + - file_option: go_package_prefix + value: github.com/Skoowshot/qrix-runtime/gen +plugins: + - remote: buf.build/protocolbuffers/go + out: gen/go + opt: paths=source_relative + - remote: buf.build/grpc/go + out: gen/go + opt: paths=source_relative \ No newline at end of file diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..b1347dc --- /dev/null +++ b/buf.yaml @@ -0,0 +1,10 @@ +# For details on buf.yaml configuration, visit https://buf.build/docs/configuration/v2/buf-yaml +version: v2 +modules: + - path: api/proto +lint: + use: + - STANDARD +breaking: + use: + - FILE diff --git a/gen/go/workspace/v1/workspace.pb.go b/gen/go/workspace/v1/workspace.pb.go new file mode 100644 index 0000000..f339c9b --- /dev/null +++ b/gen/go/workspace/v1/workspace.pb.go @@ -0,0 +1,271 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: workspace/v1/workspace.proto + +package workspacev1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type CreateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateRequest) Reset() { + *x = CreateRequest{} + mi := &file_workspace_v1_workspace_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateRequest) ProtoMessage() {} + +func (x *CreateRequest) ProtoReflect() protoreflect.Message { + mi := &file_workspace_v1_workspace_proto_msgTypes[0] + 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 CreateRequest.ProtoReflect.Descriptor instead. +func (*CreateRequest) Descriptor() ([]byte, []int) { + return file_workspace_v1_workspace_proto_rawDescGZIP(), []int{0} +} + +func (x *CreateRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type CreateResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateResponse) Reset() { + *x = CreateResponse{} + mi := &file_workspace_v1_workspace_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateResponse) ProtoMessage() {} + +func (x *CreateResponse) ProtoReflect() protoreflect.Message { + mi := &file_workspace_v1_workspace_proto_msgTypes[1] + 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 CreateResponse.ProtoReflect.Descriptor instead. +func (*CreateResponse) Descriptor() ([]byte, []int) { + return file_workspace_v1_workspace_proto_rawDescGZIP(), []int{1} +} + +func (x *CreateResponse) GetId() uint64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetByNameRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetByNameRequest) Reset() { + *x = GetByNameRequest{} + mi := &file_workspace_v1_workspace_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetByNameRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetByNameRequest) ProtoMessage() {} + +func (x *GetByNameRequest) ProtoReflect() protoreflect.Message { + mi := &file_workspace_v1_workspace_proto_msgTypes[2] + 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 GetByNameRequest.ProtoReflect.Descriptor instead. +func (*GetByNameRequest) Descriptor() ([]byte, []int) { + return file_workspace_v1_workspace_proto_rawDescGZIP(), []int{2} +} + +func (x *GetByNameRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type GetByNameResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetByNameResponse) Reset() { + *x = GetByNameResponse{} + mi := &file_workspace_v1_workspace_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetByNameResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetByNameResponse) ProtoMessage() {} + +func (x *GetByNameResponse) ProtoReflect() protoreflect.Message { + mi := &file_workspace_v1_workspace_proto_msgTypes[3] + 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 GetByNameResponse.ProtoReflect.Descriptor instead. +func (*GetByNameResponse) Descriptor() ([]byte, []int) { + return file_workspace_v1_workspace_proto_rawDescGZIP(), []int{3} +} + +func (x *GetByNameResponse) GetId() uint64 { + if x != nil { + return x.Id + } + return 0 +} + +var File_workspace_v1_workspace_proto protoreflect.FileDescriptor + +const file_workspace_v1_workspace_proto_rawDesc = "" + + "\n" + + "\x1cworkspace/v1/workspace.proto\x12\x12qrixr.workspace.v1\"#\n" + + "\rCreateRequest\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\" \n" + + "\x0eCreateResponse\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x04R\x02id\"&\n" + + "\x10GetByNameRequest\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\"#\n" + + "\x11GetByNameResponse\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x04R\x02id2\xbd\x01\n" + + "\x10WorkspaceService\x12O\n" + + "\x06Create\x12!.qrixr.workspace.v1.CreateRequest\x1a\".qrixr.workspace.v1.CreateResponse\x12X\n" + + "\tGetByName\x12$.qrixr.workspace.v1.GetByNameRequest\x1a%.qrixr.workspace.v1.GetByNameResponseB\xd2\x01\n" + + "\x16com.qrixr.workspace.v1B\x0eWorkspaceProtoP\x01Z>github.com/Skoowshot/qrix-runtime/gen/workspace/v1;workspacev1\xa2\x02\x03QWX\xaa\x02\x12Qrixr.Workspace.V1\xca\x02\x12Qrixr\\Workspace\\V1\xe2\x02\x1eQrixr\\Workspace\\V1\\GPBMetadata\xea\x02\x14Qrixr::Workspace::V1b\x06proto3" + +var ( + file_workspace_v1_workspace_proto_rawDescOnce sync.Once + file_workspace_v1_workspace_proto_rawDescData []byte +) + +func file_workspace_v1_workspace_proto_rawDescGZIP() []byte { + file_workspace_v1_workspace_proto_rawDescOnce.Do(func() { + file_workspace_v1_workspace_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_workspace_v1_workspace_proto_rawDesc), len(file_workspace_v1_workspace_proto_rawDesc))) + }) + return file_workspace_v1_workspace_proto_rawDescData +} + +var file_workspace_v1_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_workspace_v1_workspace_proto_goTypes = []any{ + (*CreateRequest)(nil), // 0: qrixr.workspace.v1.CreateRequest + (*CreateResponse)(nil), // 1: qrixr.workspace.v1.CreateResponse + (*GetByNameRequest)(nil), // 2: qrixr.workspace.v1.GetByNameRequest + (*GetByNameResponse)(nil), // 3: qrixr.workspace.v1.GetByNameResponse +} +var file_workspace_v1_workspace_proto_depIdxs = []int32{ + 0, // 0: qrixr.workspace.v1.WorkspaceService.Create:input_type -> qrixr.workspace.v1.CreateRequest + 2, // 1: qrixr.workspace.v1.WorkspaceService.GetByName:input_type -> qrixr.workspace.v1.GetByNameRequest + 1, // 2: qrixr.workspace.v1.WorkspaceService.Create:output_type -> qrixr.workspace.v1.CreateResponse + 3, // 3: qrixr.workspace.v1.WorkspaceService.GetByName:output_type -> qrixr.workspace.v1.GetByNameResponse + 2, // [2:4] is the sub-list for method output_type + 0, // [0:2] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_workspace_v1_workspace_proto_init() } +func file_workspace_v1_workspace_proto_init() { + if File_workspace_v1_workspace_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_v1_workspace_proto_rawDesc), len(file_workspace_v1_workspace_proto_rawDesc)), + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_workspace_v1_workspace_proto_goTypes, + DependencyIndexes: file_workspace_v1_workspace_proto_depIdxs, + MessageInfos: file_workspace_v1_workspace_proto_msgTypes, + }.Build() + File_workspace_v1_workspace_proto = out.File + file_workspace_v1_workspace_proto_goTypes = nil + file_workspace_v1_workspace_proto_depIdxs = nil +} diff --git a/gen/go/workspace/v1/workspace_grpc.pb.go b/gen/go/workspace/v1/workspace_grpc.pb.go new file mode 100644 index 0000000..f4ee506 --- /dev/null +++ b/gen/go/workspace/v1/workspace_grpc.pb.go @@ -0,0 +1,159 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.2 +// - protoc (unknown) +// source: workspace/v1/workspace.proto + +package workspacev1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + WorkspaceService_Create_FullMethodName = "/qrixr.workspace.v1.WorkspaceService/Create" + WorkspaceService_GetByName_FullMethodName = "/qrixr.workspace.v1.WorkspaceService/GetByName" +) + +// WorkspaceServiceClient is the client API for WorkspaceService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type WorkspaceServiceClient interface { + Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) + GetByName(ctx context.Context, in *GetByNameRequest, opts ...grpc.CallOption) (*GetByNameResponse, error) +} + +type workspaceServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewWorkspaceServiceClient(cc grpc.ClientConnInterface) WorkspaceServiceClient { + return &workspaceServiceClient{cc} +} + +func (c *workspaceServiceClient) Create(ctx context.Context, in *CreateRequest, opts ...grpc.CallOption) (*CreateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CreateResponse) + err := c.cc.Invoke(ctx, WorkspaceService_Create_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *workspaceServiceClient) GetByName(ctx context.Context, in *GetByNameRequest, opts ...grpc.CallOption) (*GetByNameResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetByNameResponse) + err := c.cc.Invoke(ctx, WorkspaceService_GetByName_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// WorkspaceServiceServer is the server API for WorkspaceService service. +// All implementations must embed UnimplementedWorkspaceServiceServer +// for forward compatibility. +type WorkspaceServiceServer interface { + Create(context.Context, *CreateRequest) (*CreateResponse, error) + GetByName(context.Context, *GetByNameRequest) (*GetByNameResponse, error) + mustEmbedUnimplementedWorkspaceServiceServer() +} + +// UnimplementedWorkspaceServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedWorkspaceServiceServer struct{} + +func (UnimplementedWorkspaceServiceServer) Create(context.Context, *CreateRequest) (*CreateResponse, error) { + return nil, status.Error(codes.Unimplemented, "method Create not implemented") +} +func (UnimplementedWorkspaceServiceServer) GetByName(context.Context, *GetByNameRequest) (*GetByNameResponse, error) { + return nil, status.Error(codes.Unimplemented, "method GetByName not implemented") +} +func (UnimplementedWorkspaceServiceServer) mustEmbedUnimplementedWorkspaceServiceServer() {} +func (UnimplementedWorkspaceServiceServer) testEmbeddedByValue() {} + +// UnsafeWorkspaceServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to WorkspaceServiceServer will +// result in compilation errors. +type UnsafeWorkspaceServiceServer interface { + mustEmbedUnimplementedWorkspaceServiceServer() +} + +func RegisterWorkspaceServiceServer(s grpc.ServiceRegistrar, srv WorkspaceServiceServer) { + // If the following call panics, it indicates UnimplementedWorkspaceServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&WorkspaceService_ServiceDesc, srv) +} + +func _WorkspaceService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).Create(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_Create_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).Create(ctx, req.(*CreateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _WorkspaceService_GetByName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetByNameRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).GetByName(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_GetByName_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).GetByName(ctx, req.(*GetByNameRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// WorkspaceService_ServiceDesc is the grpc.ServiceDesc for WorkspaceService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var WorkspaceService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "qrixr.workspace.v1.WorkspaceService", + HandlerType: (*WorkspaceServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Create", + Handler: _WorkspaceService_Create_Handler, + }, + { + MethodName: "GetByName", + Handler: _WorkspaceService_GetByName_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "workspace/v1/workspace.proto", +} diff --git a/internal/app/app.go b/internal/app/app.go index 96448d0..81b66ed 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/Skoowshot/qrix-runtime/internal/app/server" + "github.com/Skoowshot/qrix-runtime/internal/workspace" ) type App struct { @@ -20,7 +21,10 @@ func NewApp() *App { } func (app *App) Start() error { - ctrlServer, err := server.ListenControl(":7178") + wsRegistry := workspace.NewRegistry() + wsService := workspace.NewService(wsRegistry) + + ctrlServer, err := server.ListenControl(":7178", wsService) if err != nil { return fmt.Errorf("create control server: %w", err) } diff --git a/internal/app/grpchandler/workspace.go b/internal/app/grpchandler/workspace.go new file mode 100644 index 0000000..eb8053f --- /dev/null +++ b/internal/app/grpchandler/workspace.go @@ -0,0 +1,62 @@ +package grpchandler + +import ( + "context" + "errors" + "log/slog" + + workspacev1 "github.com/Skoowshot/qrix-runtime/gen/go/workspace/v1" + "github.com/Skoowshot/qrix-runtime/internal/workspace" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type Workspace struct { + service *workspace.Service + workspacev1.UnimplementedWorkspaceServiceServer +} + +func NewWorkspace(service *workspace.Service) *Workspace { + return &Workspace{ + service: service, + } +} + +func (h *Workspace) Create( + ctx context.Context, + req *workspacev1.CreateRequest, +) (*workspacev1.CreateResponse, error) { + name := workspace.Name(req.Name) + id, err := h.service.Create(ctx, name) + if err != nil { + if errors.Is(err, workspace.ErrNameAlreadyExists) { + return nil, status.Error(codes.AlreadyExists, "name already exists") + } + + slog.ErrorContext(ctx, "failed to create workspace", "error", err) + return nil, status.Error(codes.Internal, "internal server error") + } + + return &workspacev1.CreateResponse{ + Id: uint64(id), + }, nil +} +func (h *Workspace) GetByName( + ctx context.Context, + req *workspacev1.GetByNameRequest, +) (*workspacev1.GetByNameResponse, error) { + name := workspace.Name(req.Name) + id, err := h.service.GetByName(ctx, name) + if err != nil { + if errors.Is(err, workspace.ErrNotFound) { + return nil, status.Error(codes.NotFound, "name not found") + } + + slog.ErrorContext(ctx, "failed to get workspace by name", "error", err) + return nil, status.Error(codes.Internal, "internal server error") + } + + return &workspacev1.GetByNameResponse{ + Id: uint64(id), + }, nil +} diff --git a/internal/app/grpchandler/workspace_test.go b/internal/app/grpchandler/workspace_test.go new file mode 100644 index 0000000..fa46d97 --- /dev/null +++ b/internal/app/grpchandler/workspace_test.go @@ -0,0 +1,129 @@ +package grpchandler + +import ( + "context" + "net" + "testing" + + workspacev1 "github.com/Skoowshot/qrix-runtime/gen/go/workspace/v1" + "github.com/Skoowshot/qrix-runtime/internal/workspace" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" +) + +func TestWorkspace_Create(t *testing.T) { + tests := []struct { + name string + req *workspacev1.CreateRequest + setup func(t *testing.T, client workspacev1.WorkspaceServiceClient) + expectedCode codes.Code + }{ + { + name: "created successfully", + req: &workspacev1.CreateRequest{Name: "alpha"}, + setup: nil, + expectedCode: codes.OK, + }, + { + name: "duplicate name returns AlreadyExists", + req: &workspacev1.CreateRequest{Name: "alpha"}, + setup: setupGRPCWorkspace("alpha"), + expectedCode: codes.AlreadyExists, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := setupClient(t) + if tt.setup != nil { + tt.setup(t, client) + } + + resp, err := client.Create(context.Background(), tt.req) + if status.Code(err) != tt.expectedCode { + t.Errorf("code = %v, want %v (err: %v)", status.Code(err), tt.expectedCode, err) + } + if tt.expectedCode == codes.OK && resp.GetId() == 0 { + t.Errorf("id = 0, want non-zero") + } + }) + } +} + +func TestWorkspace_GetByName(t *testing.T) { + tests := []struct { + name string + req *workspacev1.GetByNameRequest + setup func(t *testing.T, client workspacev1.WorkspaceServiceClient) + expectedCode codes.Code + }{ + { + name: "existing workspace found", + req: &workspacev1.GetByNameRequest{Name: "alpha"}, + setup: setupGRPCWorkspace("alpha"), + expectedCode: codes.OK, + }, + { + name: "missing workspace returns NotFound", + req: &workspacev1.GetByNameRequest{Name: "missing"}, + setup: nil, + expectedCode: codes.NotFound, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := setupClient(t) + if tt.setup != nil { + tt.setup(t, client) + } + + resp, err := client.GetByName(context.Background(), tt.req) + if status.Code(err) != tt.expectedCode { + t.Errorf("code = %v, want %v (err: %v)", status.Code(err), tt.expectedCode, err) + } + if tt.expectedCode == codes.OK && resp.GetId() == 0 { + t.Errorf("id = 0, want non-zero") + } + }) + } +} + +func setupClient(t *testing.T) workspacev1.WorkspaceServiceClient { + t.Helper() + + lis := bufconn.Listen(1024 * 1024) + srv := grpc.NewServer() + + wsSvc := workspace.NewService(workspace.NewRegistry()) + workspacev1.RegisterWorkspaceServiceServer(srv, NewWorkspace(wsSvc)) + + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + + conn, err := grpc.NewClient( + "passthrough:///bufnet", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + return lis.DialContext(ctx) + }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + t.Fatalf("dial bufconn: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + + return workspacev1.NewWorkspaceServiceClient(conn) +} + +func setupGRPCWorkspace(name string) func(t *testing.T, client workspacev1.WorkspaceServiceClient) { + return func(t *testing.T, client workspacev1.WorkspaceServiceClient) { + t.Helper() + if _, err := client.Create(context.Background(), &workspacev1.CreateRequest{Name: name}); err != nil { + t.Fatalf("failed to setup workspace %q: %v", name, err) + } + } +} diff --git a/internal/app/server/control.go b/internal/app/server/control.go index b0ab629..c3977f0 100644 --- a/internal/app/server/control.go +++ b/internal/app/server/control.go @@ -4,6 +4,9 @@ import ( "log/slog" "net" + workspacev1 "github.com/Skoowshot/qrix-runtime/gen/go/workspace/v1" + "github.com/Skoowshot/qrix-runtime/internal/app/grpchandler" + "github.com/Skoowshot/qrix-runtime/internal/workspace" "google.golang.org/grpc" ) @@ -12,12 +15,18 @@ type Control struct { grpcServer *grpc.Server } -func ListenControl(addr string) (*Control, error) { +func ListenControl( + addr string, + wsService *workspace.Service, +) (*Control, error) { lis, err := net.Listen("tcp", addr) if err != nil { return nil, err } grpcServer := grpc.NewServer() + + workspacev1.RegisterWorkspaceServiceServer(grpcServer, grpchandler.NewWorkspace(wsService)) + return &Control{ listener: lis, grpcServer: grpcServer, diff --git a/internal/workspace/errors.go b/internal/workspace/errors.go index a21eedc..f341d76 100644 --- a/internal/workspace/errors.go +++ b/internal/workspace/errors.go @@ -4,4 +4,5 @@ import "errors" var ( ErrNameAlreadyExists = errors.New("name already exists") + ErrNotFound = errors.New("not found") ) diff --git a/internal/workspace/service.go b/internal/workspace/service.go new file mode 100644 index 0000000..c0b238d --- /dev/null +++ b/internal/workspace/service.go @@ -0,0 +1,47 @@ +package workspace + +import ( + "context" + "fmt" + + "github.com/Skoowshot/qrix-runtime/internal/store" +) + +type Service struct { + registry *Registry +} + +func NewService(registry *Registry) *Service { + return &Service{ + registry: registry, + } +} + +func (s *Service) Create(ctx context.Context, name Name) (ID, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + + ws := &Workspace{ + Stores: store.NewRegistry(), + Network: nil, + } + + id, err := s.registry.Put(name, ws) + if err != nil { + return 0, fmt.Errorf("put workspace to registry: %w", err) + } + return id, nil +} + +func (s *Service) GetByName(ctx context.Context, name Name) (ID, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + + id, ok := s.registry.GetID(name) + if !ok { + return 0, ErrNotFound + } + return id, nil +} diff --git a/internal/workspace/service_test.go b/internal/workspace/service_test.go new file mode 100644 index 0000000..8a9bce0 --- /dev/null +++ b/internal/workspace/service_test.go @@ -0,0 +1,120 @@ +package workspace + +import ( + "context" + "errors" + "testing" +) + +func TestService_Create(t *testing.T) { + tests := []struct { + name string + wsName Name + setup func(t *testing.T, svc *Service) + ctx func() context.Context + expectedErr error + }{ + { + name: "new workspace created successfully", + wsName: "alpha", + setup: nil, + ctx: context.Background, + expectedErr: nil, + }, + { + name: "duplicate workspace name returns error", + wsName: "alpha", + setup: setupWorkspace("alpha"), + ctx: context.Background, + expectedErr: ErrNameAlreadyExists, + }, + { + name: "canceled context returns error", + wsName: "alpha", + setup: nil, + ctx: canceledContext, + expectedErr: context.Canceled, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := NewService(NewRegistry()) + if tt.setup != nil { + tt.setup(t, svc) + } + + id, err := svc.Create(tt.ctx(), tt.wsName) + if !errors.Is(err, tt.expectedErr) { + t.Errorf("error = %v, want %v", err, tt.expectedErr) + } + if tt.expectedErr == nil && id == 0 { + t.Errorf("id = 0, want non-zero") + } + }) + } +} + +func TestService_GetByName(t *testing.T) { + tests := []struct { + name string + wsName Name + setup func(t *testing.T, svc *Service) + ctx func() context.Context + expectedErr error + }{ + { + name: "existing workspace found", + wsName: "alpha", + setup: setupWorkspace("alpha"), + ctx: context.Background, + expectedErr: nil, + }, + { + name: "missing workspace returns not found", + wsName: "missing", + setup: nil, + ctx: context.Background, + expectedErr: ErrNotFound, + }, + { + name: "canceled context returns error", + wsName: "alpha", + setup: setupWorkspace("alpha"), + ctx: canceledContext, + expectedErr: context.Canceled, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := NewService(NewRegistry()) + if tt.setup != nil { + tt.setup(t, svc) + } + + id, err := svc.GetByName(tt.ctx(), tt.wsName) + if !errors.Is(err, tt.expectedErr) { + t.Errorf("error = %v, want %v", err, tt.expectedErr) + } + if tt.expectedErr == nil && id == 0 { + t.Errorf("id = 0, want non-zero") + } + }) + } +} + +func setupWorkspace(name Name) func(t *testing.T, svc *Service) { + return func(t *testing.T, svc *Service) { + t.Helper() + if _, err := svc.Create(context.Background(), name); err != nil { + t.Fatalf("failed to setup workspace %q: %v", name, err) + } + } +} + +func canceledContext() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + return ctx +}