Skip to content

Commit

Permalink
fixup! Introduce snippet-service
Browse files Browse the repository at this point in the history
  • Loading branch information
Danielius1922 committed May 27, 2024
1 parent b6be68f commit e438968
Show file tree
Hide file tree
Showing 9 changed files with 316 additions and 136 deletions.
2 changes: 1 addition & 1 deletion snippet-service/service/grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (s *SnippetServiceServer) UpdateConfiguration(ctx context.Context, conf *pb
func (s *SnippetServiceServer) GetConfigurations(req *pb.GetConfigurationsRequest, srv pb.SnippetService_GetConfigurationsServer) error {
owner, err := s.checkOwner(srv.Context(), "")
if err != nil {
return s.logger.LogAndReturnError(status.Errorf(codes.PermissionDenied, "cannot update configuration: %v", err))
return s.logger.LogAndReturnError(status.Errorf(codes.PermissionDenied, "cannot get configurations: %v", err))
}

err = s.store.GetConfigurations(srv.Context(), owner, req, func(ctx context.Context, iter store.Iterator[store.Configuration]) error {
Expand Down
1 change: 0 additions & 1 deletion snippet-service/service/http/createConfiguration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ func TestRequestHandlerCreateConfiguration(t *testing.T) {
tests := []struct {
name string
args args
wantData map[string]interface{}
wantHTTPCode int
wantErr bool
}{
Expand Down
120 changes: 120 additions & 0 deletions snippet-service/service/http/getConfigurations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package http_test

import (
"context"
"crypto/tls"
"errors"
"io"
"net/http"
"testing"

"github.com/plgd-dev/go-coap/v3/message"
pkgHttp "github.com/plgd-dev/hub/v2/pkg/net/http"
"github.com/plgd-dev/hub/v2/snippet-service/pb"
snippetHttp "github.com/plgd-dev/hub/v2/snippet-service/service/http"
"github.com/plgd-dev/hub/v2/snippet-service/test"
hubTest "github.com/plgd-dev/hub/v2/test"
"github.com/plgd-dev/hub/v2/test/config"
httpTest "github.com/plgd-dev/hub/v2/test/http"
oauthTest "github.com/plgd-dev/hub/v2/test/oauth-server/test"
"github.com/plgd-dev/hub/v2/test/service"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)

func TestRequestHandlerGetConfigurations(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), config.TEST_TIMEOUT)
defer cancel()

shutDown := service.SetUpServices(context.Background(), t, service.SetUpServicesOAuth)
defer shutDown()

snippetCfg := test.MakeConfig(t)
shutdownHttp := test.New(t, snippetCfg)
defer shutdownHttp()

conn, err := grpc.NewClient(config.SNIPPET_SERVICE_HOST, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
RootCAs: hubTest.GetRootCertificatePool(t),
})))
require.NoError(t, err)
defer func() {
_ = conn.Close()
}()
c := pb.NewSnippetServiceClient(conn)
confs := test.AddConfigurations(ctx, t, snippetCfg.APIs.GRPC.Authorization.OwnerClaim, c, 30)

type args struct {
accept string
token string
}
tests := []struct {
name string
args args
wantHTTPCode int
wantErr bool
want func(*testing.T, []*pb.Configuration)
}{
{
name: test.ConfigurationOwner(1) + "/all",
args: args{
accept: pkgHttp.ApplicationProtoJsonContentType,
token: oauthTest.GetAccessToken(t, config.OAUTH_SERVER_HOST, oauthTest.ClientTest, map[string]interface{}{
snippetCfg.APIs.GRPC.Authorization.OwnerClaim: test.ConfigurationOwner(1),
}),
},
wantHTTPCode: http.StatusOK,
want: func(t *testing.T, values []*pb.Configuration) {
require.NotEmpty(t, values)
for _, v := range values {
conf, ok := confs[v.GetId()]
require.True(t, ok)
test.ConfigurationContains(t, conf, v)
}
},
},
{
name: "missing owner",
args: args{
accept: pkgHttp.ApplicationProtoJsonContentType,
token: oauthTest.GetAccessToken(t, config.OAUTH_SERVER_HOST, oauthTest.ClientTest, map[string]interface{}{
snippetCfg.APIs.GRPC.Authorization.OwnerClaim: nil,
}),
},
wantHTTPCode: http.StatusForbidden,
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rb := httpTest.NewRequest(http.MethodGet, test.HTTPURI(snippetHttp.Configurations), nil).AuthToken(tt.args.token)
rb = rb.Accept(tt.args.accept).ContentType(message.AppCBOR.String())
resp := httpTest.Do(t, rb.Build(ctx, t))
defer func() {
_ = resp.Body.Close()
}()
require.Equal(t, tt.wantHTTPCode, resp.StatusCode)

if tt.wantErr {
return
}

values := make([]*pb.Configuration, 0, 1)
for {
var value pb.Configuration
err = httpTest.Unmarshal(resp.StatusCode, resp.Body, &value)
if errors.Is(err, io.EOF) {
break
}
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
values = append(values, &value)
}
tt.want(t, values)
})
}
}
22 changes: 8 additions & 14 deletions snippet-service/service/http/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package http

import (
"fmt"
"strings"

"github.com/plgd-dev/hub/v2/http-gateway/uri"
"github.com/plgd-dev/hub/v2/pkg/fsnotify"
Expand All @@ -23,15 +22,14 @@ type Service struct {
// New parses configuration and creates new Server with provided store and bus
func New(serviceName string, config Config, snippetServiceServer *grpcService.SnippetServiceServer, validator *validator.Validator, fileWatcher *fsnotify.Watcher, logger log.Logger, tracerProvider trace.TracerProvider) (*Service, error) {
service, err := httpService.New(httpService.Config{
HTTPConnection: config.Connection,
HTTPServer: config.Server,
ServiceName: serviceName,
AuthRules: kitNetHttp.NewDefaultAuthorizationRules(uri.API),
FileWatcher: fileWatcher,
Logger: logger,
TraceProvider: tracerProvider,
Validator: validator,
QueryCaseInsensitive: queryCaseInsensitive,
HTTPConnection: config.Connection,
HTTPServer: config.Server,
ServiceName: serviceName,
AuthRules: kitNetHttp.NewDefaultAuthorizationRules(uri.API),
FileWatcher: fileWatcher,
Logger: logger,
TraceProvider: tracerProvider,
Validator: validator,
})
if err != nil {
return nil, fmt.Errorf("cannot create http service: %w", err)
Expand All @@ -48,7 +46,3 @@ func New(serviceName string, config Config, snippetServiceServer *grpcService.Sn
requestHandler: requestHandler,
}, nil
}

var queryCaseInsensitive = map[string]string{
strings.ToLower(ConfigurationIDKey): "id",
}
1 change: 0 additions & 1 deletion snippet-service/service/http/updateConfiguration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ func TestRequestHandlerUpdateConfiguration(t *testing.T) {
tests := []struct {
name string
args args
wantData map[string]interface{}
wantHTTPCode int
wantErr bool
}{
Expand Down
23 changes: 13 additions & 10 deletions snippet-service/store/mongodb/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,31 +76,31 @@ func compareIdFilter(i, j *pb.IDFilter) int {
return cmp.Compare(i.GetValue(), j.GetValue())
}

func normalizeIdFilter(idfilter []*pb.IDFilter) []*pb.IDFilter {
func checkEmptyIdFilter(idfilter []*pb.IDFilter) []*pb.IDFilter {
// if an empty query is provided, return all
if len(idfilter) == 0 {
return nil
}

slices.SortFunc(idfilter, compareIdFilter)

// if the first filter is All, we can ignore all other filters
first := idfilter[0]
if first.GetId() == "" && first.GetAll() {
return nil
}
return idfilter
}

func normalizeIdFilter(idfilter []*pb.IDFilter) []*pb.IDFilter {
idfilter = checkEmptyIdFilter(idfilter)
if len(idfilter) == 0 {
return nil
}

updatedFilter := make([]*pb.IDFilter, 0)
var idAll bool
var idLatest bool
var idValue bool
var idValueVersion uint64
setNextInitial := func(idf *pb.IDFilter) {
idAll = idf.GetAll()
idLatest = idf.GetLatest()
idValue = !idAll && !idLatest
idValueVersion = idf.GetValue()
}
setNextLatest := func(idf *pb.IDFilter) {
// we already have the latest filter
if idLatest {
Expand All @@ -123,7 +123,10 @@ func normalizeIdFilter(idfilter []*pb.IDFilter) []*pb.IDFilter {
prevID := ""
for _, idf := range idfilter {
if idf.GetId() != prevID {
setNextInitial(idf)
idAll = idf.GetAll()
idLatest = idf.GetLatest()
idValue = !idAll && !idLatest
idValueVersion = idf.GetValue()
updatedFilter = append(updatedFilter, idf)
}

Expand Down
Loading

0 comments on commit e438968

Please sign in to comment.