Skip to content

Commit

Permalink
Merge pull request #33 from suyuan32/mg
Browse files Browse the repository at this point in the history
Merge latest codes
  • Loading branch information
suyuan32 authored Mar 26, 2023
2 parents 2d30d1b + 9cc66ff commit 17346a2
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 99 deletions.
18 changes: 18 additions & 0 deletions core/conf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,24 @@ d = "abcd"
}
}

func TestConfigWithLower(t *testing.T) {
text := `a = "foo"
b = 1
`
tmpfile, err := createTempFile(".toml", text)
assert.Nil(t, err)
defer os.Remove(tmpfile)

var val struct {
A string `json:"a"`
b int
}
if assert.NoError(t, Load(tmpfile, &val)) {
assert.Equal(t, "foo", val.A)
assert.Equal(t, 0, val.b)
}
}

func TestConfigJsonCanonical(t *testing.T) {
text := []byte(`{"a": "foo", "B": "bar"}`)

Expand Down
2 changes: 1 addition & 1 deletion core/executors/periodicalexecutor.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (pe *PeriodicalExecutor) Flush() bool {
}())
}

// Sync lets caller to run fn thread-safe with pe, especially for the underlying container.
// Sync lets caller run fn thread-safe with pe, especially for the underlying container.
func (pe *PeriodicalExecutor) Sync(fn func()) {
pe.lock.Lock()
defer pe.lock.Unlock()
Expand Down
13 changes: 7 additions & 6 deletions core/mapping/unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,10 @@ func (u *Unmarshaler) processFieldWithEnvValue(fieldType reflect.Type, value ref

func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
m valuerWithParent, fullName string) error {
if !field.IsExported() {
return nil
}

key, opts, err := u.parseOptionsWithContext(field, m, fullName)
if err != nil {
return err
Expand Down Expand Up @@ -869,12 +873,9 @@ func (u *Unmarshaler) unmarshalWithFullName(m valuerWithParent, v any, fullName

numFields := baseType.NumField()
for i := 0; i < numFields; i++ {
field := baseType.Field(i)
if !field.IsExported() {
continue
}

if err := u.processField(field, valElem.Field(i), m, fullName); err != nil {
typeField := baseType.Field(i)
valueField := valElem.Field(i)
if err := u.processField(typeField, valueField, m, fullName); err != nil {
return err
}
}
Expand Down
46 changes: 46 additions & 0 deletions core/mapping/unmarshaler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,52 @@ func TestUnmarshalWithoutTagName(t *testing.T) {
}
}

func TestUnmarshalWithLowerField(t *testing.T) {
type (
Lower struct {
value int `key:"lower"`
}

inner struct {
Lower
Optional bool `key:",optional"`
}
)
m := map[string]any{
"Optional": true,
"lower": 1,
}

var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.True(t, in.Optional)
assert.Equal(t, 0, in.value)
}
}

func TestUnmarshalWithLowerAnonymousStruct(t *testing.T) {
type (
lower struct {
Value int `key:"lower"`
}

inner struct {
lower
Optional bool `key:",optional"`
}
)
m := map[string]any{
"Optional": true,
"lower": 1,
}

var in inner
if assert.NoError(t, UnmarshalKey(m, &in)) {
assert.True(t, in.Optional)
assert.Equal(t, 1, in.Value)
}
}

func TestUnmarshalWithoutTagNameWithCanonicalKey(t *testing.T) {
type inner struct {
Name string `key:"name"`
Expand Down
2 changes: 0 additions & 2 deletions core/stat/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
)

func TestMetrics(t *testing.T) {
logx.Disable()
DisableLog()
defer logEnabled.Set(true)

Expand Down
64 changes: 64 additions & 0 deletions core/stat/usage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package stat

import (
"bytes"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
)

func TestBToMb(t *testing.T) {
tests := []struct {
name string
bytes uint64
expected float32
}{
{
name: "Test 1: Convert 0 bytes to MB",
bytes: 0,
expected: 0,
},
{
name: "Test 2: Convert 1048576 bytes to MB",
bytes: 1048576,
expected: 1,
},
{
name: "Test 3: Convert 2097152 bytes to MB",
bytes: 2097152,
expected: 2,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result := bToMb(test.bytes)
assert.Equal(t, test.expected, result)
})
}
}

func TestPrintUsage(t *testing.T) {
var buf bytes.Buffer
writer := logx.NewWriter(&buf)
old := logx.Reset()
logx.SetWriter(writer)
defer logx.SetWriter(old)

printUsage()

output := buf.String()
assert.Contains(t, output, "CPU:")
assert.Contains(t, output, "MEMORY:")
assert.Contains(t, output, "Alloc=")
assert.Contains(t, output, "TotalAlloc=")
assert.Contains(t, output, "Sys=")
assert.Contains(t, output, "NumGC=")

lines := strings.Split(output, "\n")
assert.Len(t, lines, 2)
fields := strings.Split(lines[0], ", ")
assert.Len(t, fields, 5)
}
7 changes: 7 additions & 0 deletions core/validation/validator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package validation

// Validator represents a validator.
type Validator interface {
// Validate validates the value.
Validate() error
}
77 changes: 0 additions & 77 deletions go.sum

Large diffs are not rendered by default.

34 changes: 21 additions & 13 deletions zrpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,30 +110,38 @@ func SetServerSlowThreshold(threshold time.Duration) {
serverinterceptors.SetSlowThreshold(threshold)
}

func setupInterceptors(server internal.Server, c RpcServerConf, metrics *stat.Metrics) error {
func setupAuthInterceptors(svr internal.Server, c RpcServerConf) error {
rds, err := redis.NewRedis(c.Redis.RedisConf)
if err != nil {
return err
}

authenticator, err := auth.NewAuthenticator(rds, c.Redis.Key, c.StrictControl)
if err != nil {
return err
}

svr.AddStreamInterceptors(serverinterceptors.StreamAuthorizeInterceptor(authenticator))
svr.AddUnaryInterceptors(serverinterceptors.UnaryAuthorizeInterceptor(authenticator))

return nil
}

func setupInterceptors(svr internal.Server, c RpcServerConf, metrics *stat.Metrics) error {
if c.CpuThreshold > 0 {
shedder := load.NewAdaptiveShedder(load.WithCpuThreshold(c.CpuThreshold))
server.AddUnaryInterceptors(serverinterceptors.UnarySheddingInterceptor(shedder, metrics))
svr.AddUnaryInterceptors(serverinterceptors.UnarySheddingInterceptor(shedder, metrics))
}

if c.Timeout > 0 {
server.AddUnaryInterceptors(serverinterceptors.UnaryTimeoutInterceptor(
svr.AddUnaryInterceptors(serverinterceptors.UnaryTimeoutInterceptor(
time.Duration(c.Timeout) * time.Millisecond))
}

if c.Auth {
rds, err := redis.NewRedis(c.Redis.RedisConf)
if err != nil {
return err
}

authenticator, err := auth.NewAuthenticator(rds, c.Redis.Key, c.StrictControl)
if err != nil {
if err := setupAuthInterceptors(svr, c); err != nil {
return err
}

server.AddStreamInterceptors(serverinterceptors.StreamAuthorizeInterceptor(authenticator))
server.AddUnaryInterceptors(serverinterceptors.UnaryAuthorizeInterceptor(authenticator))
}

return nil
Expand Down

0 comments on commit 17346a2

Please sign in to comment.