Repository: go-kratos/kratos
Pull request #3095 (2023-11-20 18:41:22)

build(deps): bump github.com/aliyun/aliyun-log-go-sdk from 0.1.65 to 0.1.66 in /contrib/log/aliyun
Bumps [github.com/aliyun/aliyun-log-go-sdk](https://github.com/aliyun/aliyun-log-go-sdk) from 0.1.65 to 0.1.66.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/aliyun/aliyun-log-go-sdk/releases">github.com/aliyun/aliyun-log-go-sdk's releases</a>.</em></p>
<blockquote>
<h2>v0.1.66</h2>
<p>Add SetRetryTimeout interface</p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/aliyun/aliyun-log-go-sdk/commit/f9971c5bb581d8b866d8649cb641ff7c2402be8f"><code>f9971c5</code></a> Merge pull request <a href="https://redirect.github.com/aliyun/aliyun-log-go-sdk/issues/240">#240</a> from crimson-gao/addTimeout</li>
<li><a href="https://github.com/aliyun/aliyun-log-go-sdk/commit/f5fd0c78cf81741686beb1496a491792749fefe7"><code>f5fd0c7</code></a> add token update client</li>
<li><a href="https://github.com/aliyun/aliyun-log-go-sdk/commit/10ec710f01d567e55b247fb853cfda644aef3445"><code>10ec710</code></a> add retry timeout interface</li>
<li>See full diff in <a href="https://github.com/aliyun/aliyun-log-go-sdk/compare/v0.1.65...v0.1.66">compare view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/aliyun/aliyun-log-go-sdk&package-manager=go_modules&previous-version=0.1.65&new-version=0.1.66)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)


</details>


Patch:
diff --git a/.golangci.yml b/.golangci.yml
index b38bf368..556fcfbc 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -29,6 +29,7 @@ linters:
     - whitespace
     - wastedassign
     - unconvert
+    - misspell
 
   # don't enable:
   # - asciicheck
@@ -66,3 +67,5 @@ linters-settings:
     min-complexity: 50
   goimports:
     local-prefixes: github.com/go-kratos # Put imports beginning with prefix after 3rd-party packages
+  misspell: # Finds commonly misspelled English words in comments
+    locale: US
diff --git a/contrib/config/apollo/watcher.go b/contrib/config/apollo/watcher.go
index ad842420..8431fca2 100644
--- a/contrib/config/apollo/watcher.go
+++ b/contrib/config/apollo/watcher.go
@@ -27,18 +27,15 @@ func (c *customChangeListener) onChange(namespace string, changes map[string]*st
 	kv := make([]*config.KeyValue, 0, 2)
 	if strings.Contains(namespace, ".") && !strings.HasSuffix(namespace, "."+properties) &&
 		(format(namespace) == yaml || format(namespace) == yml || format(namespace) == json) {
-		value, err := c.apollo.client.GetConfigCache(namespace).Get("content")
-		if err != nil {
-			log.Warnw("apollo get config failed", "err", err)
-			return nil
+		if value, ok := changes["content"]; ok {
+			kv = append(kv, &config.KeyValue{
+				Key:    namespace,
+				Value:  []byte(value.NewValue.(string)),
+				Format: format(namespace),
+			})
+
+			return kv
 		}
-		kv = append(kv, &config.KeyValue{
-			Key:    namespace,
-			Value:  []byte(value.(string)),
-			Format: format(namespace),
-		})
-
-		return kv
 	}
 
 	next := make(map[string]interface{})
diff --git a/contrib/log/aliyun/go.mod b/contrib/log/aliyun/go.mod
index 25413ceb..8448e928 100644
--- a/contrib/log/aliyun/go.mod
+++ b/contrib/log/aliyun/go.mod
@@ -3,7 +3,7 @@ module github.com/go-kratos/kratos/contrib/log/aliyun/v2
 go 1.19
 
 require (
-	github.com/aliyun/aliyun-log-go-sdk v0.1.65
+	github.com/aliyun/aliyun-log-go-sdk v0.1.66
 	github.com/go-kratos/kratos/v2 v2.7.1
 	google.golang.org/protobuf v1.31.0
 )
diff --git a/contrib/log/aliyun/go.sum b/contrib/log/aliyun/go.sum
index 0867116c..b921ec4c 100644
--- a/contrib/log/aliyun/go.sum
+++ b/contrib/log/aliyun/go.sum
@@ -40,8 +40,8 @@ github.com/alibabacloud-go/tea-utils/v2 v2.0.1 h1:K6kwgo+UiYx+/kr6CO0PN5ACZDzE3n
 github.com/alibabacloud-go/tea-utils/v2 v2.0.1/go.mod h1:U5MTY10WwlquGPS34DOeomUGBB0gXbLueiq5Trwu0C4=
 github.com/alibabacloud-go/tea-xml v1.1.2 h1:oLxa7JUXm2EDFzMg+7oRsYc+kutgCVwm+bZlhhmvW5M=
 github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
-github.com/aliyun/aliyun-log-go-sdk v0.1.65 h1:F5HsYYTFwkkoEa1h2U0ekELC3+0IXd+zwPBC/2QUOc8=
-github.com/aliyun/aliyun-log-go-sdk v0.1.65/go.mod h1:FSKcIjukUy+LeUKhRk13PCO+9gPMTfGsYhFBHQbDqmM=
+github.com/aliyun/aliyun-log-go-sdk v0.1.66 h1:my4x9WLaHgkf5AUgefX+/6KTlcuAPvlgWOT8Aroi9sI=
+github.com/aliyun/aliyun-log-go-sdk v0.1.66/go.mod h1:FSKcIjukUy+LeUKhRk13PCO+9gPMTfGsYhFBHQbDqmM=
 github.com/aliyun/credentials-go v1.1.2 h1:qU1vwGIBb3UJ8BwunHDRFtAhS6jnQLnde/yk0+Ih2GY=
 github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
 github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
diff --git a/contrib/registry/discovery/impl_discover.go b/contrib/registry/discovery/impl_discover.go
index fb1b01d1..38b1fc5c 100644
--- a/contrib/registry/discovery/impl_discover.go
+++ b/contrib/registry/discovery/impl_discover.go
@@ -64,7 +64,7 @@ func (w *watcher) Next() ([]*registry.ServiceInstance, error) {
 	case <-event:
 	// change event come
 	case <-w.cancelCtx.Done():
-		return nil, fmt.Errorf("watch context cancelled: %v", w.cancelCtx.Err())
+		return nil, fmt.Errorf("watch context canceled: %v", w.cancelCtx.Err())
 	}
 
 	ctx, cancel := context.WithTimeout(context.TODO(), 15*time.Second)
diff --git a/log/filter.go b/log/filter.go
index 7ef96655..993fa926 100644
--- a/log/filter.go
+++ b/log/filter.go
@@ -1,7 +1,5 @@
 package log
 
-import "context"
-
 // FilterOption is filter option.
 type FilterOption func(*Filter)
 
@@ -41,7 +39,6 @@ func FilterFunc(f func(level Level, keyvals ...interface{}) bool) FilterOption {
 
 // Filter is a logger filter.
 type Filter struct {
-	ctx    context.Context
 	logger Logger
 	level  Level
 	key    map[interface{}]struct{}
@@ -70,9 +67,6 @@ func (f *Filter) Log(level Level, keyvals ...interface{}) error {
 	// prefixkv contains the slice of arguments defined as prefixes during the log initialization
 	var prefixkv []interface{}
 	l, ok := f.logger.(*logger)
-	if ok {
-		l.ctx = f.ctx
-	}
 	if ok && len(l.prefix) > 0 {
 		prefixkv = make([]interface{}, 0, len(l.prefix))
 		prefixkv = append(prefixkv, l.prefix...)
diff --git a/log/log.go b/log/log.go
index 38cef805..b3c34d37 100644
--- a/log/log.go
+++ b/log/log.go
@@ -50,28 +50,16 @@ func With(l Logger, kv ...interface{}) Logger {
 // WithContext returns a shallow copy of l with its context changed
 // to ctx. The provided ctx must be non-nil.
 func WithContext(ctx context.Context, l Logger) Logger {
-	c, ok := l.(*logger)
-	if ok {
-		return &logger{
-			logger:    c.logger,
-			prefix:    c.prefix,
-			hasValuer: c.hasValuer,
-			ctx:       ctx,
-		}
-	}
-
-	f, ok := l.(*Filter)
-	if ok {
-		f.ctx = ctx
-		return &Filter{
-			ctx:    ctx,
-			logger: f.logger,
-			level:  f.level,
-			key:    f.key,
-			value:  f.value,
-			filter: f.filter,
-		}
+	switch v := l.(type) {
+	default:
+		return &logger{logger: l, ctx: ctx}
+	case *logger:
+		lv := *v
+		lv.ctx = ctx
+		return &lv
+	case *Filter:
+		fv := *v
+		fv.logger = WithContext(ctx, fv.logger)
+		return &fv
 	}
-
-	return &logger{logger: l, ctx: ctx}
 }


Test patch:
diff --git a/contrib/config/apollo/watcher_test.go b/contrib/config/apollo/watcher_test.go
new file mode 100644
index 00000000..5341b769
--- /dev/null
+++ b/contrib/config/apollo/watcher_test.go
@@ -0,0 +1,79 @@
+package apollo
+
+import (
+	"testing"
+
+	"github.com/apolloconfig/agollo/v4/storage"
+
+	"github.com/go-kratos/kratos/v2/config"
+	"github.com/go-kratos/kratos/v2/encoding"
+)
+
+func Test_onChange(t *testing.T) {
+	s := map[string]struct {
+		Name string `yaml:"name"`
+	}{
+		"app": {
+			Name: "new",
+		},
+	}
+	codec := encoding.GetCodec(yaml)
+	val, _ := codec.Marshal(s)
+	c := customChangeListener{}
+	tests := []struct {
+		name      string
+		namespace string
+		changes   map[string]*storage.ConfigChange
+		kvs       []*config.KeyValue
+	}{
+		{
+			"test yaml onChange",
+			"app.yaml",
+			map[string]*storage.ConfigChange{
+				"name": {
+					OldValue:   "old",
+					NewValue:   "new",
+					ChangeType: storage.MODIFIED,
+				},
+			},
+			[]*config.KeyValue{
+				{
+					Key:    "app.yaml",
+					Value:  val,
+					Format: yaml,
+				},
+			},
+		},
+		{
+			"test json onChange",
+			"app.json",
+			map[string]*storage.ConfigChange{
+				"content": {
+					OldValue:   `{"name":"old"}`,
+					NewValue:   `{"name":"new"}`,
+					ChangeType: storage.MODIFIED,
+				},
+			},
+			[]*config.KeyValue{
+				{
+					Key:    "app.json",
+					Value:  []byte(`{"name":"new"}`),
+					Format: json,
+				},
+			},
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			kvs := c.onChange(tt.namespace, tt.changes)
+			if len(kvs) != len(tt.kvs) {
+				t.Errorf("len(kvs) = %v, want %v", len(kvs), len(tt.kvs))
+			}
+			for i := range kvs {
+				if kvs[i].Format != tt.kvs[i].Format || kvs[i].Key != tt.kvs[i].Key || string(kvs[i].Value) != string(tt.kvs[i].Value) {
+					t.Errorf("got %v, want %v", kvs[i], tt.kvs[i])
+				}
+			}
+		})
+	}
+}
diff --git a/contrib/metrics/prometheus/gauge_test.go b/contrib/metrics/prometheus/gauge_test.go
index 31744a5a..fdeb94e9 100644
--- a/contrib/metrics/prometheus/gauge_test.go
+++ b/contrib/metrics/prometheus/gauge_test.go
@@ -7,21 +7,21 @@ import (
 	"github.com/prometheus/client_golang/prometheus"
 )
 
-func TestGuage(t *testing.T) {
-	expect := `# HELP test_request_test_guage_metric test
-# TYPE test_request_test_guage_metric gauge
-test_request_test_guage_metric{code="test",kind="test",operation="test",reason="test"} %d
+func TestGauge(t *testing.T) {
+	expect := `# HELP test_request_test_gauge_metric test
+# TYPE test_request_test_gauge_metric gauge
+test_request_test_gauge_metric{code="test",kind="test",operation="test",reason="test"} %d
 `
 
 	guageVec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
 		Namespace: "test",
-		Name:      "test_guage_metric",
+		Name:      "test_gauge_metric",
 		Subsystem: "request",
 		Help:      "test",
 	}, []string{"kind", "operation", "code", "reason"})
 
-	guage := NewGauge(guageVec)
-	guage.With("test", "test", "test", "test").Set(1)
+	gauge := NewGauge(guageVec)
+	gauge.With("test", "test", "test", "test").Set(1)
 
 	reg := prometheus.NewRegistry()
 	reg.MustRegister(guageVec)
@@ -35,7 +35,7 @@ test_request_test_guage_metric{code="test",kind="test",operation="test",reason="
 		t.Fatal("metrics error")
 	}
 
-	guage.With("test", "test", "test", "test").Add(1)
+	gauge.With("test", "test", "test", "test").Add(1)
 	result, err = gatherLatest(reg)
 	if err != nil {
 		t.Fatal(err)
@@ -44,7 +44,7 @@ test_request_test_guage_metric{code="test",kind="test",operation="test",reason="
 		t.Fatal("metrics error")
 	}
 
-	guage.With("test", "test", "test", "test").Sub(1)
+	gauge.With("test", "test", "test", "test").Sub(1)
 	result, err = gatherLatest(reg)
 	if err != nil {
 		t.Fatal(err)
diff --git a/contrib/registry/consul/registry_test.go b/contrib/registry/consul/registry_test.go
index 791c2efc..02b61720 100644
--- a/contrib/registry/consul/registry_test.go
+++ b/contrib/registry/consul/registry_test.go
@@ -333,7 +333,7 @@ func TestRegistry_Watch(t *testing.T) {
 			},
 		},
 		{
-			name: "ctx has been cancelled",
+			name: "ctx has been canceled",
 			args: args{
 				ctx:      canceledCtx,
 				cancel:   cancel,
diff --git a/log/filter_test.go b/log/filter_test.go
index 679fbe8c..8463a472 100644
--- a/log/filter_test.go
+++ b/log/filter_test.go
@@ -5,7 +5,9 @@ import (
 	"context"
 	"io"
 	"strings"
+	"sync"
 	"testing"
+	"time"
 )
 
 func TestFilterAll(_ *testing.T) {
@@ -172,3 +174,52 @@ func TestFilterWithContext(t *testing.T) {
 		t.Error("don't read ctx value")
 	}
 }
+
+type traceIDKey struct{}
+
+func setTraceID(ctx context.Context, tid string) context.Context {
+	return context.WithValue(ctx, traceIDKey{}, tid)
+}
+
+func traceIDValuer() Valuer {
+	return func(ctx context.Context) any {
+		if ctx == nil {
+			return ""
+		}
+		if tid := ctx.Value(traceIDKey{}); tid != nil {
+			return tid
+		}
+		return ""
+	}
+}
+
+func TestFilterWithContextConcurrent(t *testing.T) {
+	var buf bytes.Buffer
+	pctx := context.Background()
+	l := NewFilter(
+		With(NewStdLogger(&buf), "trace-id", traceIDValuer()),
+		FilterLevel(LevelInfo),
+	)
+
+	var wg sync.WaitGroup
+	wg.Add(1)
+	go func() {
+		defer wg.Done()
+		time.Sleep(time.Second)
+		NewHelper(l).Info("done1")
+	}()
+
+	wg.Add(1)
+	go func() {
+		defer wg.Done()
+		tid := "world"
+		ctx := setTraceID(pctx, tid)
+		NewHelper((WithContext(ctx, l))).Info("done2")
+	}()
+
+	wg.Wait()
+	expected := "INFO trace-id=world msg=done2\nINFO trace-id= msg=done1\n"
+	if got := buf.String(); got != expected {
+		t.Errorf("got: %#v", got)
+	}
+}
diff --git a/log/log_test.go b/log/log_test.go
index 8221d9ef..7adbba8d 100644
--- a/log/log_test.go
+++ b/log/log_test.go
@@ -1,7 +1,6 @@
 package log
 
 import (
-	"context"
 	"testing"
 )
 
@@ -11,7 +10,3 @@ func TestInfo(_ *testing.T) {
 	logger = With(logger, "caller", DefaultCaller)
 	_ = logger.Log(LevelInfo, "key1", "value1")
 }
-
-func TestWithContext(_ *testing.T) {
-	WithContext(context.Background(), nil)
-}