Skip to content

Commit

Permalink
Merge pull request #5 from bancodobrasil/tracing_feature
Browse files Browse the repository at this point in the history
Tracing feature
  • Loading branch information
vivaldomp authored Apr 5, 2022
2 parents 5d0c256 + 9a1bd0c commit 3482414
Show file tree
Hide file tree
Showing 6 changed files with 409 additions and 40 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
branches: [ develop, master ]

env:
LATEST_GO_VERSION: "1.17"
LATEST_GO_VERSION: "1.18"
GO111MODULE: "on"

jobs:
Expand All @@ -16,7 +16,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
go_version: ['1.16', '1.17']
go_version: ['1.18']
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v2
Expand Down Expand Up @@ -48,5 +48,5 @@ jobs:
- name: Build
run: go build -v ./...

#- name: Test
# run: go test -v ./...
- name: Test
run: go test -v ./...
33 changes: 26 additions & 7 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,39 @@ package adapter

import (
"os"
"path/filepath"
"strings"

"github.com/bancodobrasil/featws-resolver-adapter-go/routes"
"github.com/bancodobrasil/featws-resolver-adapter-go/services"
ginMonitor "github.com/bancodobrasil/gin-monitor"
telemetry "github.com/bancodobrasil/gin-telemetry"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
ginlogrus "github.com/toorop/gin-logrus"
)

func setupLog() {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})

log.SetOutput(os.Stdout)
func init() {
ex, err := os.Executable()
if err != nil {
log.Fatal(err)
}
exePath := filepath.Dir(ex)
viper.AddConfigPath(exePath)
viper.SetConfigType("env")
viper.SetConfigName(".env")

log.SetLevel(log.DebugLevel)
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv()
viper.SetDefault("RESOLVER_LOG_JSON", false)
viper.SetDefault("RESOLVER_LOG_LEVEL", "error")
viper.SetDefault("RESOLVER_SERVICE_NAME", "resolver-adapter-go")
if err := viper.ReadInConfig(); err == nil {
log.Infof("Using config file: %s", viper.ConfigFileUsed())
}
}

// Config ...
Expand All @@ -28,9 +45,9 @@ type Config struct {
// Run start the resolver server with resolverFunc
func Run(resolverFunc services.ResolverFunc, config Config) error {

setupLog()
InitLogger()

monitor, err := ginMonitor.New("v0.0.1-rc7", ginMonitor.DefaultErrorMessageKey, ginMonitor.DefaultBuckets)
monitor, err := ginMonitor.New("v0.0.1-rc8", ginMonitor.DefaultErrorMessageKey, ginMonitor.DefaultBuckets)
if err != nil {
panic(err)
}
Expand All @@ -48,6 +65,8 @@ func Run(resolverFunc services.ResolverFunc, config Config) error {
router.Use(monitor.Prometheus())
// Register metrics endpoint
router.GET("/metrics", gin.WrapH(promhttp.Handler()))
// Register gin-telemetry middleware
router.Use(telemetry.Middleware(viper.GetString("RESOLVER_SERVICE_NAME")))

routes.SetupRoutes(router)

Expand Down
186 changes: 186 additions & 0 deletions adapter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package adapter

import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"testing"
"time"

"github.com/bancodobrasil/featws-resolver-adapter-go/types"
"github.com/stretchr/testify/assert"
)

const (
labelContextTest string = "adapter_context_test"
labelLoadTest string = "adapter_load_test"
labelLoadSystemError string = "adapter_load_system_error"
msgErrorContextMissing string = "Context missing"
msgErrorLoadSystemError string = "This resolver doesn't work for this loads %v"
msgEchoContext string = "#Echo# %s"
messageText string = "Lorem ipsum dolor sit amet"
urlResolver string = "http://localhost:7000/api/v1/resolve/"
contentType string = "application/text"
)

func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}

func setup() {
go func() {
Run(resolverTest, Config{
Port: "7000",
})
}()
// have to wait for the goroutine to start and run the server
// otherwise the main thread will complete
time.Sleep(5 * time.Millisecond)
}

func shutdown() {}

func resolverTest(resolveInput types.ResolveInput, resolveOutput *types.ResolveOutput) {
sort.Strings(resolveInput.Load)
if contains(resolveInput.Load, labelLoadTest) {
contextValue, ok := resolveInput.Context[labelContextTest]
if !ok {
resolveOutput.Errors[labelLoadTest] = msgErrorContextMissing
} else {
resolveOutput.Context[labelLoadTest] = fmt.Sprintf(msgEchoContext, contextValue)
}

} else {
resolveOutput.Errors[labelLoadSystemError] = fmt.Sprintf(msgErrorLoadSystemError, resolveInput.Load)
}
}

func contains(s []string, searchterm string) bool {
i := sort.SearchStrings(s, searchterm)
return i < len(s) && s[i] == searchterm
}

func TestAdapterSuccess(t *testing.T) {
resolveOutput := testRequest(t, labelContextTest, messageText, labelLoadTest)
assert.Equal(t, resolveOutput.Context[labelLoadTest], fmt.Sprintf(msgEchoContext, messageText))
}

func TestAdapterLabelInvalid(t *testing.T) {
resolveOutput := testRequest(t, labelContextTest, messageText, "label_invalid")
assert.Equal(t, resolveOutput.Errors[labelLoadSystemError], fmt.Sprintf(msgErrorLoadSystemError, []string{"label_invalid"}))
}

func TestAdapterContextInvalid(t *testing.T) {
resolveOutput := testRequest(t, "context_invalid", messageText, labelLoadTest)
assert.Equal(t, resolveOutput.Errors[labelLoadTest], msgErrorContextMissing)
}

func testRequest(t *testing.T, context string, data string, load string) *types.ResolveOutput {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}

client := &http.Client{Transport: tr}

body, _ := json.Marshal(types.ResolveInput{
Context: map[string]interface{}{
context: data,
},
Load: []string{load},
})

postBody := bytes.NewBuffer((body))

defer client.CloseIdleConnections()

resp, err := client.Post(urlResolver, contentType, postBody)

assert.NoError(t, err)
assert.Equal(t, "200 OK", resp.Status)

defer resp.Body.Close()

resBody, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)

resolveOutput := types.ResolveOutput{
Context: make(map[string]interface{}),
Errors: make(map[string]interface{}),
}
json.Unmarshal(resBody, &resolveOutput)

return &resolveOutput

}

// go test -bench . -run="none" -v -count=5

func BenchmarkAdapterResolver(b *testing.B) {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
testRequestBench(labelContextTest, messageText, labelLoadTest)
}
})
}

func testRequestBench(context string, data string, load string) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}

client := &http.Client{Transport: tr}

body, _ := json.Marshal(types.ResolveInput{
Context: map[string]interface{}{
context: data,
},
Load: []string{load},
})

postBody := bytes.NewBuffer((body))

defer client.CloseIdleConnections()

resp, err := client.Post(urlResolver, contentType, postBody)
if err != nil {
log.Fatal(err)
}

if resp.StatusCode != 200 {
log.Fatal("Http response status not equals 200")
}

defer resp.Body.Close()

resBody, err := ioutil.ReadAll(resp.Body)

if err != nil {
log.Fatal(err)
}

resolveOutput := types.ResolveOutput{
Context: make(map[string]interface{}),
Errors: make(map[string]interface{}),
}

err = json.Unmarshal(resBody, &resolveOutput)

if err != nil {
log.Fatal(err)
}

}
55 changes: 47 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,20 +1,59 @@
module github.com/bancodobrasil/featws-resolver-adapter-go

go 1.16
go 1.18

require (
github.com/bancodobrasil/gin-monitor v1.0.0-rc1
github.com/bancodobrasil/gin-telemetry v0.0.1-rc1
github.com/gin-gonic/gin v1.7.7
github.com/go-playground/validator/v10 v10.10.1 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/prometheus/client_golang v1.12.1
github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0 // indirect
github.com/toorop/gin-logrus v0.0.0-20210225092905-2c785434f26f // indirect
github.com/ugorji/go v1.2.7 // indirect
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.1
)

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/toorop/gin-logrus v0.0.0-20210225092905-2c785434f26f
github.com/ugorji/go/codec v1.2.7 // indirect
go.opentelemetry.io/otel v1.6.1 // indirect
go.opentelemetry.io/otel/exporters/jaeger v1.6.1 // indirect
go.opentelemetry.io/otel/sdk v1.6.1 // indirect
go.opentelemetry.io/otel/trace v1.6.1 // indirect
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f // indirect
golang.org/x/sys v0.0.0-20220405052023-b1e9470b6e64 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
Loading

0 comments on commit 3482414

Please sign in to comment.