repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/utils_test.go | core/trace/utils_test.go | package trace
import (
"context"
"net"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/peer"
)
func TestPeerFromContext(t *testing.T) {
addrs, err := net.InterfaceAddrs()
assert.Nil(t, err)
assert.NotEmpty(t, addrs)
tests := []struct {
name string
ctx context.Context
empty bool
}{
{
name: "empty",
ctx: context.Background(),
empty: true,
},
{
name: "nil",
ctx: peer.NewContext(context.Background(), nil),
empty: true,
},
{
name: "with value",
ctx: peer.NewContext(context.Background(), &peer.Peer{
Addr: addrs[0],
}),
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
addr := PeerFromCtx(test.ctx)
assert.Equal(t, test.empty, len(addr) == 0)
})
}
}
func TestParseFullMethod(t *testing.T) {
tests := []struct {
fullMethod string
name string
attr []attribute.KeyValue
}{
{
fullMethod: "/grpc.test.EchoService/Echo",
name: "grpc.test.EchoService/Echo",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("grpc.test.EchoService"),
semconv.RPCMethodKey.String("Echo"),
},
}, {
fullMethod: "/com.example.ExampleRmiService/exampleMethod",
name: "com.example.ExampleRmiService/exampleMethod",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("com.example.ExampleRmiService"),
semconv.RPCMethodKey.String("exampleMethod"),
},
}, {
fullMethod: "/MyCalcService.Calculator/Add",
name: "MyCalcService.Calculator/Add",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("MyCalcService.Calculator"),
semconv.RPCMethodKey.String("Add"),
},
}, {
fullMethod: "/MyServiceReference.ICalculator/Add",
name: "MyServiceReference.ICalculator/Add",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("MyServiceReference.ICalculator"),
semconv.RPCMethodKey.String("Add"),
},
}, {
fullMethod: "/MyServiceWithNoPackage/theMethod",
name: "MyServiceWithNoPackage/theMethod",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("MyServiceWithNoPackage"),
semconv.RPCMethodKey.String("theMethod"),
},
}, {
fullMethod: "/pkg.svr",
name: "pkg.svr",
attr: []attribute.KeyValue(nil),
}, {
fullMethod: "/pkg.svr/",
name: "pkg.svr/",
attr: []attribute.KeyValue{
semconv.RPCServiceKey.String("pkg.svr"),
},
},
}
for _, test := range tests {
n, a := ParseFullMethod(test.fullMethod)
assert.Equal(t, test.name, n)
assert.Equal(t, test.attr, a)
}
}
func TestSpanInfo(t *testing.T) {
val, kvs := SpanInfo("/fullMethod", "remote")
assert.Equal(t, "fullMethod", val)
assert.NotEmpty(t, kvs)
}
func TestPeerAttr(t *testing.T) {
tests := []struct {
name string
addr string
expect []attribute.KeyValue
}{
{
name: "empty",
},
{
name: "port only",
addr: ":8080",
expect: []attribute.KeyValue{
semconv.NetPeerIPKey.String(localhost),
semconv.NetPeerPortKey.String("8080"),
},
},
{
name: "port only",
addr: "192.168.0.2:8080",
expect: []attribute.KeyValue{
semconv.NetPeerIPKey.String("192.168.0.2"),
semconv.NetPeerPortKey.String("8080"),
},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
kvs := PeerAttr(test.addr)
assert.EqualValues(t, test.expect, kvs)
})
}
}
func TestTracerFromContext(t *testing.T) {
traceFn := func(ctx context.Context, hasTraceId bool) {
spanContext := trace.SpanContextFromContext(ctx)
assert.Equal(t, spanContext.IsValid(), hasTraceId)
parentTraceId := spanContext.TraceID().String()
tracer := TracerFromContext(ctx)
_, span := tracer.Start(ctx, "b")
defer span.End()
spanContext = span.SpanContext()
assert.True(t, spanContext.IsValid())
if hasTraceId {
assert.Equal(t, parentTraceId, spanContext.TraceID().String())
}
}
t.Run("context", func(t *testing.T) {
opts := []sdktrace.TracerProviderOption{
// Set the sampling rate based on the parent span to 100%
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))),
// Record information about this application in a Resource.
sdktrace.WithResource(resource.NewSchemaless(semconv.ServiceNameKey.String("test"))),
}
tp = sdktrace.NewTracerProvider(opts...)
otel.SetTracerProvider(tp)
ctx, span := tp.Tracer(TraceName).Start(context.Background(), "a")
defer span.End()
traceFn(ctx, true)
})
t.Run("global", func(t *testing.T) {
opts := []sdktrace.TracerProviderOption{
// Set the sampling rate based on the parent span to 100%
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))),
// Record information about this application in a Resource.
sdktrace.WithResource(resource.NewSchemaless(semconv.ServiceNameKey.String("test"))),
}
tp = sdktrace.NewTracerProvider(opts...)
otel.SetTracerProvider(tp)
traceFn(context.Background(), false)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/resource.go | core/trace/resource.go | package trace
import "go.opentelemetry.io/otel/attribute"
var attrResources = make([]attribute.KeyValue, 0)
// AddResources add more resources in addition to configured trace name.
func AddResources(attrs ...attribute.KeyValue) {
attrResources = append(attrResources, attrs...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/vars.go | core/trace/vars.go | package trace
import "net/http"
// TraceIdKey is the trace id header.
// https://www.w3.org/TR/trace-context/#trace-id
// May change it to trace-id afterward.
var TraceIdKey = http.CanonicalHeaderKey("x-trace-id")
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/tracer_test.go | core/trace/tracer_test.go | package trace
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/metadata"
)
const (
traceIDStr = "4bf92f3577b34da6a3ce929d0e0e4736"
spanIDStr = "00f067aa0ba902b7"
)
var (
traceID = mustTraceIDFromHex(traceIDStr)
spanID = mustSpanIDFromHex(spanIDStr)
)
func mustTraceIDFromHex(s string) (t trace.TraceID) {
var err error
t, err = trace.TraceIDFromHex(s)
if err != nil {
panic(err)
}
return
}
func mustSpanIDFromHex(s string) (t trace.SpanID) {
var err error
t, err = trace.SpanIDFromHex(s)
if err != nil {
panic(err)
}
return
}
func TestExtractValidTraceContext(t *testing.T) {
stateStr := "key1=value1,key2=value2"
state, err := trace.ParseTraceState(stateStr)
require.NoError(t, err)
tests := []struct {
name string
traceparent string
tracestate string
sc trace.SpanContext
}{
{
name: "not sampled",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "sampled",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: trace.FlagsSampled,
Remote: true,
}),
},
{
name: "valid tracestate",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
tracestate: stateStr,
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceState: state,
Remote: true,
}),
},
{
name: "invalid tracestate preserves traceparent",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
tracestate: "invalid$@#=invalid",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "future version not sampled",
traceparent: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "future version sampled",
traceparent: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: trace.FlagsSampled,
Remote: true,
}),
},
{
name: "future version sample bit set",
traceparent: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: trace.FlagsSampled,
Remote: true,
}),
},
{
name: "future version sample bit not set",
traceparent: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-08",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "future version additional data",
traceparent: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00-XYZxsf09",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "B3 format ending in dash",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00-",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "future version B3 format ending in dash",
traceparent: "03-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00-",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
}
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
propagator := otel.GetTextMapPropagator()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
md := metadata.MD{}
md.Set("traceparent", tt.traceparent)
md.Set("tracestate", tt.tracestate)
_, spanCtx := Extract(ctx, propagator, &md)
assert.Equal(t, tt.sc, spanCtx)
})
}
}
func TestExtractInvalidTraceContext(t *testing.T) {
tests := []struct {
name string
header string
}{
{
name: "wrong version length",
header: "0000-00000000000000000000000000000000-0000000000000000-01",
},
{
name: "wrong trace ID length",
header: "00-ab00000000000000000000000000000000-cd00000000000000-01",
},
{
name: "wrong span ID length",
header: "00-ab000000000000000000000000000000-cd0000000000000000-01",
},
{
name: "wrong trace flag length",
header: "00-ab000000000000000000000000000000-cd00000000000000-0100",
},
{
name: "bogus version",
header: "qw-00000000000000000000000000000000-0000000000000000-01",
},
{
name: "bogus trace ID",
header: "00-qw000000000000000000000000000000-cd00000000000000-01",
},
{
name: "bogus span ID",
header: "00-ab000000000000000000000000000000-qw00000000000000-01",
},
{
name: "bogus trace flag",
header: "00-ab000000000000000000000000000000-cd00000000000000-qw",
},
{
name: "upper case version",
header: "A0-00000000000000000000000000000000-0000000000000000-01",
},
{
name: "upper case trace ID",
header: "00-AB000000000000000000000000000000-cd00000000000000-01",
},
{
name: "upper case span ID",
header: "00-ab000000000000000000000000000000-CD00000000000000-01",
},
{
name: "upper case trace flag",
header: "00-ab000000000000000000000000000000-cd00000000000000-A1",
},
{
name: "zero trace ID and span ID",
header: "00-00000000000000000000000000000000-0000000000000000-01",
},
{
name: "trace-flag unused bits set",
header: "00-ab000000000000000000000000000000-cd00000000000000-09",
},
{
name: "missing options",
header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7",
},
{
name: "empty options",
header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-",
},
}
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
propagator := otel.GetTextMapPropagator()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
md := metadata.MD{}
md.Set("traceparent", tt.header)
_, spanCtx := Extract(ctx, propagator, &md)
assert.Equal(t, trace.SpanContext{}, spanCtx)
})
}
}
func TestInjectValidTraceContext(t *testing.T) {
stateStr := "key1=value1,key2=value2"
state, err := trace.ParseTraceState(stateStr)
require.NoError(t, err)
tests := []struct {
name string
traceparent string
tracestate string
sc trace.SpanContext
}{
{
name: "not sampled",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
Remote: true,
}),
},
{
name: "sampled",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: trace.FlagsSampled,
Remote: true,
}),
},
{
name: "unsupported trace flag bits dropped",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: 0xff,
Remote: true,
}),
},
{
name: "with tracestate",
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00",
tracestate: stateStr,
sc: trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceState: state,
Remote: true,
}),
},
}
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
propagator := otel.GetTextMapPropagator()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
ctx = trace.ContextWithRemoteSpanContext(ctx, tt.sc)
want := metadata.MD{}
want.Set("traceparent", tt.traceparent)
if len(tt.tracestate) > 0 {
want.Set("tracestate", tt.tracestate)
}
md := metadata.MD{}
Inject(ctx, propagator, &md)
assert.Equal(t, want, md)
mm := &metadataSupplier{
metadata: &md,
}
assert.NotEmpty(t, mm.Keys())
})
}
}
func TestInvalidSpanContextDropped(t *testing.T) {
invalidSC := trace.SpanContext{}
require.False(t, invalidSC.IsValid())
ctx := trace.ContextWithRemoteSpanContext(context.Background(), invalidSC)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
propagator := otel.GetTextMapPropagator()
md := metadata.MD{}
Inject(ctx, propagator, &md)
mm := &metadataSupplier{
metadata: &md,
}
assert.Empty(t, mm.Keys())
assert.Equal(t, "", mm.Get("traceparent"), "injected invalid SpanContext")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/message.go | core/trace/message.go | package trace
import (
"context"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"google.golang.org/protobuf/proto"
)
const messageEvent = "message"
var (
// MessageSent is the type of sent messages.
MessageSent = messageType(RPCMessageTypeSent)
// MessageReceived is the type of received messages.
MessageReceived = messageType(RPCMessageTypeReceived)
)
type messageType attribute.KeyValue
// Event adds an event of the messageType to the span associated with the
// passed context with id and size (if message is a proto message).
func (m messageType) Event(ctx context.Context, id int, message any) {
span := trace.SpanFromContext(ctx)
if p, ok := message.(proto.Message); ok {
span.AddEvent(messageEvent, trace.WithAttributes(
attribute.KeyValue(m),
RPCMessageIDKey.Int(id),
RPCMessageUncompressedSizeKey.Int(proto.Size(p)),
))
} else {
span.AddEvent(messageEvent, trace.WithAttributes(
attribute.KeyValue(m),
RPCMessageIDKey.Int(id),
))
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/message_test.go | core/trace/message_test.go | package trace
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/dynamicpb"
)
func TestMessageType_Event(t *testing.T) {
ctx, s := otel.Tracer(TraceName).Start(context.Background(), "test")
span := mockSpan{Span: s}
ctx = trace.ContextWithSpan(ctx, &span)
MessageReceived.Event(ctx, 1, "foo")
assert.Equal(t, messageEvent, span.name)
assert.NotEmpty(t, span.options)
}
func TestMessageType_EventProtoMessage(t *testing.T) {
var span mockSpan
var message mockMessage
ctx := trace.ContextWithSpan(context.Background(), &span)
MessageReceived.Event(ctx, 1, message)
assert.Equal(t, messageEvent, span.name)
assert.NotEmpty(t, span.options)
}
type mockSpan struct {
trace.Span
name string
options []trace.EventOption
}
func (m *mockSpan) End(_ ...trace.SpanEndOption) {
}
func (m *mockSpan) AddEvent(name string, options ...trace.EventOption) {
m.name = name
m.options = options
}
func (m *mockSpan) IsRecording() bool {
return false
}
func (m *mockSpan) RecordError(_ error, _ ...trace.EventOption) {
}
func (m *mockSpan) SpanContext() trace.SpanContext {
panic("implement me")
}
func (m *mockSpan) SetStatus(_ codes.Code, _ string) {
}
func (m *mockSpan) SetName(_ string) {
}
func (m *mockSpan) SetAttributes(_ ...attribute.KeyValue) {
}
func (m *mockSpan) TracerProvider() trace.TracerProvider {
return nil
}
type mockMessage struct{}
func (m mockMessage) ProtoReflect() protoreflect.Message {
return new(dynamicpb.Message)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/propagation.go | core/trace/propagation.go | package trace
import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
)
func init() {
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/trace/tracetest/tracetest.go | core/trace/tracetest/tracetest.go | package tracetest
import (
"testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
// NewInMemoryExporter returns a new InMemoryExporter
// and sets it as the global for tests.
func NewInMemoryExporter(t *testing.T) *tracetest.InMemoryExporter {
me := tracetest.NewInMemoryExporter()
t.Cleanup(func() {
me.Reset()
})
otel.SetTracerProvider(trace.NewTracerProvider(trace.WithSyncer(me)))
return me
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/repr.go | core/timex/repr.go | package timex
import (
"fmt"
"time"
)
// ReprOfDuration returns the string representation of given duration in ms.
func ReprOfDuration(duration time.Duration) string {
return fmt.Sprintf("%.1fms", float32(duration)/float32(time.Millisecond))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/repr_test.go | core/timex/repr_test.go | package timex
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestReprOfDuration(t *testing.T) {
assert.Equal(t, "1000.0ms", ReprOfDuration(time.Second))
assert.Equal(t, "1111.6ms", ReprOfDuration(
time.Second+time.Millisecond*111+time.Microsecond*555))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/ticker.go | core/timex/ticker.go | package timex
import (
"errors"
"time"
"github.com/zeromicro/go-zero/core/lang"
)
// errTimeout indicates a timeout.
var errTimeout = errors.New("timeout")
type (
// Ticker interface wraps the Chan and Stop methods.
Ticker interface {
Chan() <-chan time.Time
Stop()
}
// FakeTicker interface is used for unit testing.
FakeTicker interface {
Ticker
Done()
Tick()
Wait(d time.Duration) error
}
fakeTicker struct {
c chan time.Time
done chan lang.PlaceholderType
}
realTicker struct {
*time.Ticker
}
)
// NewTicker returns a Ticker.
func NewTicker(d time.Duration) Ticker {
return &realTicker{
Ticker: time.NewTicker(d),
}
}
func (rt *realTicker) Chan() <-chan time.Time {
return rt.C
}
// NewFakeTicker returns a FakeTicker.
func NewFakeTicker() FakeTicker {
return &fakeTicker{
c: make(chan time.Time, 1),
done: make(chan lang.PlaceholderType, 1),
}
}
func (ft *fakeTicker) Chan() <-chan time.Time {
return ft.c
}
func (ft *fakeTicker) Done() {
ft.done <- lang.Placeholder
}
func (ft *fakeTicker) Stop() {
close(ft.c)
}
func (ft *fakeTicker) Tick() {
ft.c <- time.Now()
}
func (ft *fakeTicker) Wait(d time.Duration) error {
select {
case <-time.After(d):
return errTimeout
case <-ft.done:
return nil
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/relativetime.go | core/timex/relativetime.go | package timex
import "time"
// Use the long enough past time as start time, in case timex.Now() - lastTime equals 0.
var initTime = time.Now().AddDate(-1, -1, -1)
// Now returns a relative time duration since initTime, which is not important.
// The caller only needs to care about the relative value.
func Now() time.Duration {
return time.Since(initTime)
}
// Since returns a diff since given d.
func Since(d time.Duration) time.Duration {
return time.Since(initTime) - d
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/relativetime_test.go | core/timex/relativetime_test.go | package timex
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRelativeTime(t *testing.T) {
time.Sleep(time.Millisecond)
now := Now()
assert.True(t, now > 0)
time.Sleep(time.Millisecond)
assert.True(t, Since(now) > 0)
}
func BenchmarkTimeSince(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = time.Since(time.Now())
}
}
func BenchmarkTimexSince(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Since(Now())
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/timex/ticker_test.go | core/timex/ticker_test.go | package timex
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRealTickerDoTick(t *testing.T) {
ticker := NewTicker(time.Millisecond * 10)
defer ticker.Stop()
var count int
for range ticker.Chan() {
count++
if count > 5 {
break
}
}
}
func TestFakeTicker(t *testing.T) {
const total = 5
ticker := NewFakeTicker()
defer ticker.Stop()
var count int32
go func() {
for range ticker.Chan() {
if atomic.AddInt32(&count, 1) == total {
ticker.Done()
}
}
}()
for i := 0; i < 5; i++ {
ticker.Tick()
}
assert.Nil(t, ticker.Wait(time.Second))
assert.Equal(t, int32(total), atomic.LoadInt32(&count))
}
func TestFakeTickerTimeout(t *testing.T) {
ticker := NewFakeTicker()
defer ticker.Stop()
assert.NotNil(t, ticker.Wait(time.Millisecond))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/queue_test.go | core/queue/queue_test.go | package queue
import (
"errors"
"math"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
const (
consumers = 4
rounds = 100
)
func TestQueue(t *testing.T) {
producer := newMockedProducer(rounds)
consumer := newMockedConsumer()
consumer.wait.Add(consumers)
q := NewQueue(func() (Producer, error) {
return producer, nil
}, func() (Consumer, error) {
return consumer, nil
})
q.AddListener(new(mockedListener))
q.SetName("mockqueue")
q.SetNumConsumer(consumers)
q.SetNumProducer(1)
q.pause()
q.resume()
go func() {
producer.wait.Wait()
q.Stop()
}()
q.Start()
assert.Equal(t, int32(rounds), atomic.LoadInt32(&consumer.count))
}
func TestQueue_Broadcast(t *testing.T) {
producer := newMockedProducer(math.MaxInt32)
consumer := newMockedConsumer()
consumer.wait.Add(consumers)
q := NewQueue(func() (Producer, error) {
return producer, nil
}, func() (Consumer, error) {
return consumer, nil
})
q.AddListener(new(mockedListener))
q.SetName("mockqueue")
q.SetNumConsumer(consumers)
q.SetNumProducer(1)
go func() {
time.Sleep(time.Millisecond * 100)
q.Stop()
}()
go q.Start()
time.Sleep(time.Millisecond * 50)
q.Broadcast("message")
consumer.wait.Wait()
assert.Equal(t, int32(consumers), atomic.LoadInt32(&consumer.events))
}
func TestQueue_PauseResume(t *testing.T) {
producer := newMockedProducer(rounds)
consumer := newMockedConsumer()
consumer.wait.Add(consumers)
q := NewQueue(func() (Producer, error) {
return producer, nil
}, func() (Consumer, error) {
return consumer, nil
})
q.AddListener(new(mockedListener))
q.SetName("mockqueue")
q.SetNumConsumer(consumers)
q.SetNumProducer(1)
go func() {
producer.wait.Wait()
q.Stop()
}()
q.Start()
producer.listener.OnProducerPause()
assert.Equal(t, int32(0), atomic.LoadInt32(&q.active))
producer.listener.OnProducerResume()
assert.Equal(t, int32(1), atomic.LoadInt32(&q.active))
assert.Equal(t, int32(rounds), atomic.LoadInt32(&consumer.count))
}
func TestQueue_ConsumeError(t *testing.T) {
producer := newMockedProducer(rounds)
consumer := newMockedConsumer()
consumer.consumeErr = errors.New("consume error")
consumer.wait.Add(consumers)
q := NewQueue(func() (Producer, error) {
return producer, nil
}, func() (Consumer, error) {
return consumer, nil
})
q.AddListener(new(mockedListener))
q.SetName("mockqueue")
q.SetNumConsumer(consumers)
q.SetNumProducer(1)
go func() {
producer.wait.Wait()
q.Stop()
}()
q.Start()
assert.Equal(t, int32(rounds), atomic.LoadInt32(&consumer.count))
}
type mockedConsumer struct {
count int32
events int32
consumeErr error
wait sync.WaitGroup
}
func newMockedConsumer() *mockedConsumer {
return new(mockedConsumer)
}
func (c *mockedConsumer) Consume(string) error {
atomic.AddInt32(&c.count, 1)
return c.consumeErr
}
func (c *mockedConsumer) OnEvent(any) {
if atomic.AddInt32(&c.events, 1) <= consumers {
c.wait.Done()
}
}
type mockedProducer struct {
total int32
count int32
listener ProduceListener
wait sync.WaitGroup
}
func newMockedProducer(total int32) *mockedProducer {
p := new(mockedProducer)
p.total = total
p.wait.Add(int(total))
return p
}
func (p *mockedProducer) AddListener(listener ProduceListener) {
p.listener = listener
}
func (p *mockedProducer) Produce() (string, bool) {
if atomic.AddInt32(&p.count, 1) <= p.total {
p.wait.Done()
return "item", true
}
time.Sleep(time.Second)
return "", false
}
type mockedListener struct{}
func (l *mockedListener) OnPause() {
}
func (l *mockedListener) OnResume() {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/balancedpusher_test.go | core/queue/balancedpusher_test.go | package queue
import (
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBalancedQueuePusher(t *testing.T) {
const numPushers = 100
var pushers []Pusher
var mockedPushers []*mockedPusher
for i := 0; i < numPushers; i++ {
p := &mockedPusher{
name: "pusher:" + strconv.Itoa(i),
}
pushers = append(pushers, p)
mockedPushers = append(mockedPushers, p)
}
pusher := NewBalancedPusher(pushers)
assert.True(t, len(pusher.Name()) > 0)
for i := 0; i < numPushers*1000; i++ {
assert.Nil(t, pusher.Push("item"))
}
var counts []int
for _, p := range mockedPushers {
counts = append(counts, p.count)
}
mean := calcMean(counts)
variance := calcVariance(mean, counts)
assert.True(t, variance < 100, fmt.Sprintf("too big variance - %.2f", variance))
}
func TestBalancedQueuePusher_NoAvailable(t *testing.T) {
pusher := NewBalancedPusher(nil)
assert.True(t, len(pusher.Name()) == 0)
assert.Equal(t, ErrNoAvailablePusher, pusher.Push("item"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/multipusher_test.go | core/queue/multipusher_test.go | package queue
import (
"fmt"
"math"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMultiQueuePusher(t *testing.T) {
const numPushers = 100
var pushers []Pusher
var mockedPushers []*mockedPusher
for i := 0; i < numPushers; i++ {
p := &mockedPusher{
name: "pusher:" + strconv.Itoa(i),
}
pushers = append(pushers, p)
mockedPushers = append(mockedPushers, p)
}
pusher := NewMultiPusher(pushers)
assert.True(t, len(pusher.Name()) > 0)
for i := 0; i < 1000; i++ {
_ = pusher.Push("item")
}
var counts []int
for _, p := range mockedPushers {
counts = append(counts, p.count)
}
mean := calcMean(counts)
variance := calcVariance(mean, counts)
assert.True(t, math.Abs(mean-1000*(1-failProba)) < 10)
assert.True(t, variance < 100, fmt.Sprintf("too big variance - %.2f", variance))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/util.go | core/queue/util.go | package queue
import "strings"
func generateName(pushers []Pusher) string {
names := make([]string, len(pushers))
for i, pusher := range pushers {
names[i] = pusher.Name()
}
return strings.Join(names, ",")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/producer.go | core/queue/producer.go | package queue
type (
// A Producer interface represents a producer that produces messages.
Producer interface {
AddListener(listener ProduceListener)
Produce() (string, bool)
}
// A ProduceListener interface represents a produce listener.
ProduceListener interface {
OnProducerPause()
OnProducerResume()
}
// ProducerFactory defines the method to generate a Producer.
ProducerFactory func() (Producer, error)
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/consumer.go | core/queue/consumer.go | package queue
type (
// A Consumer interface represents a consumer that can consume string messages.
Consumer interface {
Consume(string) error
OnEvent(event any)
}
// ConsumerFactory defines the factory to generate consumers.
ConsumerFactory func() (Consumer, error)
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/messagequeue.go | core/queue/messagequeue.go | package queue
// A MessageQueue interface represents a message queue.
type MessageQueue interface {
Start()
Stop()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/balancedpusher.go | core/queue/balancedpusher.go | package queue
import (
"errors"
"sync/atomic"
"github.com/zeromicro/go-zero/core/logx"
)
// ErrNoAvailablePusher indicates no pusher available.
var ErrNoAvailablePusher = errors.New("no available pusher")
// A BalancedPusher is used to push messages to multiple pusher with round robin algorithm.
type BalancedPusher struct {
name string
pushers []Pusher
index uint64
}
// NewBalancedPusher returns a BalancedPusher.
func NewBalancedPusher(pushers []Pusher) Pusher {
return &BalancedPusher{
name: generateName(pushers),
pushers: pushers,
}
}
// Name returns the name of pusher.
func (pusher *BalancedPusher) Name() string {
return pusher.name
}
// Push pushes message to one of the underlying pushers.
func (pusher *BalancedPusher) Push(message string) error {
size := len(pusher.pushers)
for i := 0; i < size; i++ {
index := atomic.AddUint64(&pusher.index, 1) % uint64(size)
target := pusher.pushers[index]
if err := target.Push(message); err != nil {
logx.Error(err)
} else {
return nil
}
}
return ErrNoAvailablePusher
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/multipusher.go | core/queue/multipusher.go | package queue
import "github.com/zeromicro/go-zero/core/errorx"
// A MultiPusher is a pusher that can push messages to multiple underlying pushers.
type MultiPusher struct {
name string
pushers []Pusher
}
// NewMultiPusher returns a MultiPusher.
func NewMultiPusher(pushers []Pusher) Pusher {
return &MultiPusher{
name: generateName(pushers),
pushers: pushers,
}
}
// Name returns the name of pusher.
func (pusher *MultiPusher) Name() string {
return pusher.name
}
// Push pushes a message into the underlying queue.
func (pusher *MultiPusher) Push(message string) error {
var batchError errorx.BatchError
for _, each := range pusher.pushers {
if err := each.Push(message); err != nil {
batchError.Add(err)
}
}
return batchError.Err()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/util_test.go | core/queue/util_test.go | package queue
import (
"errors"
"math"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mathx"
)
var (
proba = mathx.NewProba()
failProba = 0.01
)
func init() {
logx.Disable()
}
func TestGenerateName(t *testing.T) {
pushers := []Pusher{
&mockedPusher{name: "first"},
&mockedPusher{name: "second"},
&mockedPusher{name: "third"},
}
assert.Equal(t, "first,second,third", generateName(pushers))
}
func TestGenerateNameNil(t *testing.T) {
var pushers []Pusher
assert.Equal(t, "", generateName(pushers))
}
func calcMean(vals []int) float64 {
if len(vals) == 0 {
return 0
}
var result float64
for _, val := range vals {
result += float64(val)
}
return result / float64(len(vals))
}
func calcVariance(mean float64, vals []int) float64 {
if len(vals) == 0 {
return 0
}
var result float64
for _, val := range vals {
result += math.Pow(float64(val)-mean, 2)
}
return result / float64(len(vals))
}
type mockedPusher struct {
name string
count int
}
func (p *mockedPusher) Name() string {
return p.name
}
func (p *mockedPusher) Push(_ string) error {
if proba.TrueOnProba(failProba) {
return errors.New("dummy")
}
p.count++
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/queue/queue.go | core/queue/queue.go | package queue
import (
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/rescue"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/threading"
"github.com/zeromicro/go-zero/core/timex"
)
const queueName = "queue"
type (
// A Queue is a message queue.
Queue struct {
name string
metrics *stat.Metrics
producerFactory ProducerFactory
producerRoutineGroup *threading.RoutineGroup
consumerFactory ConsumerFactory
consumerRoutineGroup *threading.RoutineGroup
producerCount int
consumerCount int
active int32
channel chan string
quit chan struct{}
listeners []Listener
eventLock sync.Mutex
eventChannels []chan any
}
// A Listener interface represents a listener that can be notified with queue events.
Listener interface {
OnPause()
OnResume()
}
// A Poller interface wraps the method Poll.
Poller interface {
Name() string
Poll() string
}
// A Pusher interface wraps the method Push.
Pusher interface {
Name() string
Push(string) error
}
)
// NewQueue returns a Queue.
func NewQueue(producerFactory ProducerFactory, consumerFactory ConsumerFactory) *Queue {
q := &Queue{
metrics: stat.NewMetrics(queueName),
producerFactory: producerFactory,
producerRoutineGroup: threading.NewRoutineGroup(),
consumerFactory: consumerFactory,
consumerRoutineGroup: threading.NewRoutineGroup(),
producerCount: runtime.NumCPU(),
consumerCount: runtime.NumCPU() << 1,
channel: make(chan string),
quit: make(chan struct{}),
}
q.SetName(queueName)
return q
}
// AddListener adds a listener to q.
func (q *Queue) AddListener(listener Listener) {
q.listeners = append(q.listeners, listener)
}
// Broadcast broadcasts the message to all event channels.
func (q *Queue) Broadcast(message any) {
go func() {
q.eventLock.Lock()
defer q.eventLock.Unlock()
for _, channel := range q.eventChannels {
channel <- message
}
}()
}
// SetName sets the name of q.
func (q *Queue) SetName(name string) {
q.name = name
q.metrics.SetName(name)
}
// SetNumConsumer sets the number of consumers.
func (q *Queue) SetNumConsumer(count int) {
q.consumerCount = count
}
// SetNumProducer sets the number of producers.
func (q *Queue) SetNumProducer(count int) {
q.producerCount = count
}
// Start starts q.
func (q *Queue) Start() {
q.startProducers(q.producerCount)
q.startConsumers(q.consumerCount)
q.producerRoutineGroup.Wait()
close(q.channel)
q.consumerRoutineGroup.Wait()
}
// Stop stops q.
func (q *Queue) Stop() {
close(q.quit)
}
func (q *Queue) consume(eventChan chan any) {
var consumer Consumer
for {
var err error
if consumer, err = q.consumerFactory(); err != nil {
logx.Errorf("Error on creating consumer: %v", err)
time.Sleep(time.Second)
} else {
break
}
}
for {
select {
case message, ok := <-q.channel:
if ok {
q.consumeOne(consumer, message)
} else {
logx.Info("Task channel was closed, quitting consumer...")
return
}
case event := <-eventChan:
consumer.OnEvent(event)
}
}
}
func (q *Queue) consumeOne(consumer Consumer, message string) {
threading.RunSafe(func() {
startTime := timex.Now()
defer func() {
duration := timex.Since(startTime)
q.metrics.Add(stat.Task{
Duration: duration,
})
logx.WithDuration(duration).Infof("%s", message)
}()
if err := consumer.Consume(message); err != nil {
logx.Errorf("Error occurred while consuming %v: %v", message, err)
}
})
}
func (q *Queue) pause() {
for _, listener := range q.listeners {
listener.OnPause()
}
}
func (q *Queue) produce() {
var producer Producer
for {
var err error
if producer, err = q.producerFactory(); err != nil {
logx.Errorf("Error on creating producer: %v", err)
time.Sleep(time.Second)
} else {
break
}
}
atomic.AddInt32(&q.active, 1)
producer.AddListener(routineListener{
queue: q,
})
for {
select {
case <-q.quit:
logx.Info("Quitting producer")
return
default:
if v, ok := q.produceOne(producer); ok {
q.channel <- v
}
}
}
}
func (q *Queue) produceOne(producer Producer) (string, bool) {
// avoid panic quit the producer, log it and continue
defer rescue.Recover()
return producer.Produce()
}
func (q *Queue) resume() {
for _, listener := range q.listeners {
listener.OnResume()
}
}
func (q *Queue) startConsumers(number int) {
for i := 0; i < number; i++ {
eventChan := make(chan any)
q.eventLock.Lock()
q.eventChannels = append(q.eventChannels, eventChan)
q.eventLock.Unlock()
q.consumerRoutineGroup.Run(func() {
q.consume(eventChan)
})
}
}
func (q *Queue) startProducers(number int) {
for i := 0; i < number; i++ {
q.producerRoutineGroup.Run(func() {
q.produce()
})
}
}
type routineListener struct {
queue *Queue
}
func (rl routineListener) OnProducerPause() {
if atomic.AddInt32(&rl.queue.active, -1) <= 0 {
rl.queue.pause()
}
}
func (rl routineListener) OnProducerResume() {
if atomic.AddInt32(&rl.queue.active, 1) == 1 {
rl.queue.resume()
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/histogram_test.go | core/metric/histogram_test.go | package metric
import (
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
)
func TestNewHistogramVec(t *testing.T) {
histogramVec := NewHistogramVec(&HistogramVecOpts{
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Buckets: []float64{1, 2, 3},
})
defer histogramVec.(*promHistogramVec).close()
histogramVecNil := NewHistogramVec(nil)
assert.NotNil(t, histogramVec)
assert.Nil(t, histogramVecNil)
}
func TestHistogramObserve(t *testing.T) {
startAgent()
histogramVec := NewHistogramVec(&HistogramVecOpts{
Name: "counts",
Help: "rpc server requests duration(ms).",
Buckets: []float64{1, 2, 3},
Labels: []string{"method"},
})
defer histogramVec.(*promHistogramVec).close()
hv, _ := histogramVec.(*promHistogramVec)
hv.Observe(2, "/Users")
hv.ObserveFloat(1.1, "/Users")
metadata := `
# HELP counts rpc server requests duration(ms).
# TYPE counts histogram
`
val := `
counts_bucket{method="/Users",le="1"} 0
counts_bucket{method="/Users",le="2"} 2
counts_bucket{method="/Users",le="3"} 2
counts_bucket{method="/Users",le="+Inf"} 2
counts_sum{method="/Users"} 3.1
counts_count{method="/Users"} 2
`
err := testutil.CollectAndCompare(hv.histogram, strings.NewReader(metadata+val))
assert.Nil(t, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/counter_test.go | core/metric/counter_test.go | package metric
import (
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/prometheus"
)
func TestNewCounterVec(t *testing.T) {
counterVec := NewCounterVec(&CounterVecOpts{
Namespace: "http_server",
Subsystem: "requests",
Name: "total",
Help: "rpc client requests error count.",
})
defer counterVec.close()
counterVecNil := NewCounterVec(nil)
counterVec.Inc("path", "code")
counterVec.Add(1, "path", "code")
proc.Shutdown()
assert.NotNil(t, counterVec)
assert.Nil(t, counterVecNil)
}
func TestCounterIncr(t *testing.T) {
startAgent()
counterVec := NewCounterVec(&CounterVecOpts{
Namespace: "http_client",
Subsystem: "call",
Name: "code_total",
Help: "http client requests error count.",
Labels: []string{"path", "code"},
})
defer counterVec.close()
cv, _ := counterVec.(*promCounterVec)
cv.Inc("/Users", "500")
cv.Inc("/Users", "500")
r := testutil.ToFloat64(cv.counter)
assert.Equal(t, float64(2), r)
}
func TestCounterAdd(t *testing.T) {
startAgent()
counterVec := NewCounterVec(&CounterVecOpts{
Namespace: "rpc_server",
Subsystem: "requests",
Name: "err_total",
Help: "rpc client requests error count.",
Labels: []string{"method", "code"},
})
defer counterVec.close()
cv, _ := counterVec.(*promCounterVec)
cv.Add(11, "/Users", "500")
cv.Add(22, "/Users", "500")
r := testutil.ToFloat64(cv.counter)
assert.Equal(t, float64(33), r)
}
func startAgent() {
prometheus.StartAgent(prometheus.Config{
Host: "127.0.0.1",
Port: 9101,
Path: "/metrics",
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/summary.go | core/metric/summary.go | package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
)
type (
// A SummaryVecOpts is a summary vector options
SummaryVecOpts struct {
VecOpt VectorOpts
Objectives map[float64]float64
}
// A SummaryVec interface represents a summary vector.
SummaryVec interface {
// Observe adds observation v to labels.
Observe(v float64, labels ...string)
close() bool
}
promSummaryVec struct {
summary *prom.SummaryVec
}
)
// NewSummaryVec return a SummaryVec
func NewSummaryVec(cfg *SummaryVecOpts) SummaryVec {
if cfg == nil {
return nil
}
vec := prom.NewSummaryVec(
prom.SummaryOpts{
Namespace: cfg.VecOpt.Namespace,
Subsystem: cfg.VecOpt.Subsystem,
Name: cfg.VecOpt.Name,
Help: cfg.VecOpt.Help,
Objectives: cfg.Objectives,
},
cfg.VecOpt.Labels,
)
prom.MustRegister(vec)
sv := &promSummaryVec{
summary: vec,
}
proc.AddShutdownListener(func() {
sv.close()
})
return sv
}
func (sv *promSummaryVec) Observe(v float64, labels ...string) {
update(func() {
sv.summary.WithLabelValues(labels...).Observe(v)
})
}
func (sv *promSummaryVec) close() bool {
return prom.Unregister(sv.summary)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/gauge_test.go | core/metric/gauge_test.go | package metric
import (
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
)
func TestNewGaugeVec(t *testing.T) {
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "rpc_server",
Subsystem: "requests",
Name: "duration",
Help: "rpc server requests duration(ms).",
})
defer gaugeVec.close()
gaugeVecNil := NewGaugeVec(nil)
assert.NotNil(t, gaugeVec)
assert.Nil(t, gaugeVecNil)
proc.Shutdown()
}
func TestGaugeInc(t *testing.T) {
startAgent()
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "rpc_client2",
Subsystem: "requests",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"path"},
})
defer gaugeVec.close()
gv, _ := gaugeVec.(*promGaugeVec)
gv.Inc("/users")
gv.Inc("/users")
r := testutil.ToFloat64(gv.gauge)
assert.Equal(t, float64(2), r)
}
func TestGaugeDec(t *testing.T) {
startAgent()
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "rpc_client",
Subsystem: "requests",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"path"},
})
defer gaugeVec.close()
gv, _ := gaugeVec.(*promGaugeVec)
gv.Dec("/users")
gv.Dec("/users")
r := testutil.ToFloat64(gv.gauge)
assert.Equal(t, float64(-2), r)
}
func TestGaugeAdd(t *testing.T) {
startAgent()
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "rpc_client",
Subsystem: "request",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"path"},
})
defer gaugeVec.close()
gv, _ := gaugeVec.(*promGaugeVec)
gv.Add(-10, "/classroom")
gv.Add(30, "/classroom")
r := testutil.ToFloat64(gv.gauge)
assert.Equal(t, float64(20), r)
}
func TestGaugeSub(t *testing.T) {
startAgent()
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "rpc_client",
Subsystem: "request",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"path"},
})
defer gaugeVec.close()
gv, _ := gaugeVec.(*promGaugeVec)
gv.Sub(-100, "/classroom")
gv.Sub(30, "/classroom")
r := testutil.ToFloat64(gv.gauge)
assert.Equal(t, float64(70), r)
}
func TestGaugeSet(t *testing.T) {
startAgent()
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "http_client",
Subsystem: "request",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"path"},
})
gaugeVec.close()
gv, _ := gaugeVec.(*promGaugeVec)
gv.Set(666, "/users")
r := testutil.ToFloat64(gv.gauge)
assert.Equal(t, float64(666), r)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/metric.go | core/metric/metric.go | package metric
import "github.com/zeromicro/go-zero/core/prometheus"
// A VectorOpts is a general configuration.
type VectorOpts struct {
Namespace string
Subsystem string
Name string
Help string
Labels []string
}
func update(fn func()) {
if !prometheus.Enabled() {
return
}
fn()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/counter.go | core/metric/counter.go | package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
)
type (
// A CounterVecOpts is an alias of VectorOpts.
CounterVecOpts VectorOpts
// CounterVec interface represents a counter vector.
CounterVec interface {
// Inc increments labels.
Inc(labels ...string)
// Add adds labels with v.
Add(v float64, labels ...string)
close() bool
}
promCounterVec struct {
counter *prom.CounterVec
}
)
// NewCounterVec returns a CounterVec.
func NewCounterVec(cfg *CounterVecOpts) CounterVec {
if cfg == nil {
return nil
}
vec := prom.NewCounterVec(prom.CounterOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
cv := &promCounterVec{
counter: vec,
}
proc.AddShutdownListener(func() {
cv.close()
})
return cv
}
func (cv *promCounterVec) Add(v float64, labels ...string) {
update(func() {
cv.counter.WithLabelValues(labels...).Add(v)
})
}
func (cv *promCounterVec) Inc(labels ...string) {
update(func() {
cv.counter.WithLabelValues(labels...).Inc()
})
}
func (cv *promCounterVec) close() bool {
return prom.Unregister(cv.counter)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/summary_test.go | core/metric/summary_test.go | package metric
import (
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
)
func TestNewSummaryVec(t *testing.T) {
summaryVec := NewSummaryVec(&SummaryVecOpts{
VecOpt: VectorOpts{
Namespace: "http_server",
Subsystem: "requests",
Name: "duration_quantiles",
Help: "rpc client requests duration(ms) φ quantiles ",
Labels: []string{"method"},
},
Objectives: map[float64]float64{
0.5: 0.01,
0.9: 0.01,
},
})
defer summaryVec.close()
summaryVecNil := NewSummaryVec(nil)
assert.NotNil(t, summaryVec)
assert.Nil(t, summaryVecNil)
}
func TestSummaryObserve(t *testing.T) {
startAgent()
summaryVec := NewSummaryVec(&SummaryVecOpts{
VecOpt: VectorOpts{
Namespace: "http_server",
Subsystem: "requests",
Name: "duration_quantiles",
Help: "rpc client requests duration(ms) φ quantiles ",
Labels: []string{"method"},
},
Objectives: map[float64]float64{
0.3: 0.01,
0.6: 0.01,
1: 0.01,
},
})
defer summaryVec.close()
sv := summaryVec.(*promSummaryVec)
sv.Observe(100, "GET")
sv.Observe(200, "GET")
sv.Observe(300, "GET")
metadata := `
# HELP http_server_requests_duration_quantiles rpc client requests duration(ms) φ quantiles
# TYPE http_server_requests_duration_quantiles summary
`
val := `
http_server_requests_duration_quantiles{method="GET",quantile="0.3"} 100
http_server_requests_duration_quantiles{method="GET",quantile="0.6"} 200
http_server_requests_duration_quantiles{method="GET",quantile="1"} 300
http_server_requests_duration_quantiles_sum{method="GET"} 600
http_server_requests_duration_quantiles_count{method="GET"} 3
`
err := testutil.CollectAndCompare(sv.summary, strings.NewReader(metadata+val))
assert.Nil(t, err)
proc.Shutdown()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/gauge.go | core/metric/gauge.go | package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
)
type (
// GaugeVecOpts is an alias of VectorOpts.
GaugeVecOpts VectorOpts
// GaugeVec represents a gauge vector.
GaugeVec interface {
// Set sets v to labels.
Set(v float64, labels ...string)
// Inc increments labels.
Inc(labels ...string)
// Dec decrements labels.
Dec(labels ...string)
// Add adds v to labels.
Add(v float64, labels ...string)
// Sub subtracts v to labels.
Sub(v float64, labels ...string)
close() bool
}
promGaugeVec struct {
gauge *prom.GaugeVec
}
)
// NewGaugeVec returns a GaugeVec.
func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
if cfg == nil {
return nil
}
vec := prom.NewGaugeVec(prom.GaugeOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
gv := &promGaugeVec{
gauge: vec,
}
proc.AddShutdownListener(func() {
gv.close()
})
return gv
}
func (gv *promGaugeVec) Add(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Add(v)
})
}
func (gv *promGaugeVec) Dec(labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Dec()
})
}
func (gv *promGaugeVec) Inc(labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Inc()
})
}
func (gv *promGaugeVec) Set(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Set(v)
})
}
func (gv *promGaugeVec) Sub(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Sub(v)
})
}
func (gv *promGaugeVec) close() bool {
return prom.Unregister(gv.gauge)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/metric/histogram.go | core/metric/histogram.go | package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
)
type (
// A HistogramVecOpts is a histogram vector options.
HistogramVecOpts struct {
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
ConstLabels map[string]string
}
// A HistogramVec interface represents a histogram vector.
HistogramVec interface {
// Observe adds observation v to labels.
Observe(v int64, labels ...string)
// ObserveFloat allow to observe float64 values.
ObserveFloat(v float64, labels ...string)
close() bool
}
promHistogramVec struct {
histogram *prom.HistogramVec
}
)
// NewHistogramVec returns a HistogramVec.
func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
if cfg == nil {
return nil
}
vec := prom.NewHistogramVec(prom.HistogramOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
ConstLabels: cfg.ConstLabels,
}, cfg.Labels)
prom.MustRegister(vec)
hv := &promHistogramVec{
histogram: vec,
}
proc.AddShutdownListener(func() {
hv.close()
})
return hv
}
func (hv *promHistogramVec) Observe(v int64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(float64(v))
})
}
func (hv *promHistogramVec) ObserveFloat(v float64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(v)
})
}
func (hv *promHistogramVec) close() bool {
return prom.Unregister(hv.histogram)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/range_test.go | core/mathx/range_test.go | package mathx
import "testing"
func TestAtLeast(t *testing.T) {
t.Run("test int", func(t *testing.T) {
if got := AtLeast(10, 5); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(3, 5); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(5, 5); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test int8", func(t *testing.T) {
if got := AtLeast(int8(10), int8(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(int8(3), int8(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(int8(5), int8(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test int16", func(t *testing.T) {
if got := AtLeast(int16(10), int16(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(int16(3), int16(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(int16(5), int16(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test int32", func(t *testing.T) {
if got := AtLeast(int32(10), int32(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(int32(3), int32(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(int32(5), int32(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test int64", func(t *testing.T) {
if got := AtLeast(int64(10), int64(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(int64(3), int64(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(int64(5), int64(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test uint", func(t *testing.T) {
if got := AtLeast(uint(10), uint(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(uint(3), uint(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(uint(5), uint(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test uint8", func(t *testing.T) {
if got := AtLeast(uint8(10), uint8(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(uint8(3), uint8(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(uint8(5), uint8(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test uint16", func(t *testing.T) {
if got := AtLeast(uint16(10), uint16(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(uint16(3), uint16(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(uint16(5), uint16(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test uint32", func(t *testing.T) {
if got := AtLeast(uint32(10), uint32(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(uint32(3), uint32(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(uint32(5), uint32(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test uint64", func(t *testing.T) {
if got := AtLeast(uint64(10), uint64(5)); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(uint64(3), uint64(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(uint64(5), uint64(5)); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
})
t.Run("test float32", func(t *testing.T) {
if got := AtLeast(float32(10.0), float32(5.0)); got != 10.0 {
t.Errorf("AtLeast() = %v, want 10.0", got)
}
if got := AtLeast(float32(3.0), float32(5.0)); got != 5.0 {
t.Errorf("AtLeast() = %v, want 5.0", got)
}
if got := AtLeast(float32(5.0), float32(5.0)); got != 5.0 {
t.Errorf("AtLeast() = %v, want 5.0", got)
}
})
t.Run("test float64", func(t *testing.T) {
if got := AtLeast(10.0, 5.0); got != 10.0 {
t.Errorf("AtLeast() = %v, want 10.0", got)
}
if got := AtLeast(3.0, 5.0); got != 5.0 {
t.Errorf("AtLeast() = %v, want 5.0", got)
}
if got := AtLeast(5.0, 5.0); got != 5.0 {
t.Errorf("AtLeast() = %v, want 5.0", got)
}
})
}
func TestAtMost(t *testing.T) {
t.Run("test int", func(t *testing.T) {
if got := AtMost(10, 5); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(3, 5); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(5, 5); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test int8", func(t *testing.T) {
if got := AtMost(int8(10), int8(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(int8(3), int8(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(int8(5), int8(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test int16", func(t *testing.T) {
if got := AtMost(int16(10), int16(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(int16(3), int16(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(int16(5), int16(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test int32", func(t *testing.T) {
if got := AtMost(int32(10), int32(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(int32(3), int32(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(int32(5), int32(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test int64", func(t *testing.T) {
if got := AtMost(int64(10), int64(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(int64(3), int64(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(int64(5), int64(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test uint", func(t *testing.T) {
if got := AtMost(uint(10), uint(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(uint(3), uint(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(uint(5), uint(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test uint8", func(t *testing.T) {
if got := AtMost(uint8(10), uint8(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(uint8(3), uint8(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(uint8(5), uint8(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test uint16", func(t *testing.T) {
if got := AtMost(uint16(10), uint16(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(uint16(3), uint16(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(uint16(5), uint16(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test uint32", func(t *testing.T) {
if got := AtMost(uint32(10), uint32(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(uint32(3), uint32(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(uint32(5), uint32(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test uint64", func(t *testing.T) {
if got := AtMost(uint64(10), uint64(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
if got := AtMost(uint64(3), uint64(5)); got != 3 {
t.Errorf("AtMost() = %v, want 3", got)
}
if got := AtMost(uint64(5), uint64(5)); got != 5 {
t.Errorf("AtMost() = %v, want 5", got)
}
})
t.Run("test float32", func(t *testing.T) {
if got := AtMost(float32(10.0), float32(5.0)); got != 5.0 {
t.Errorf("AtMost() = %v, want 5.0", got)
}
if got := AtMost(float32(3.0), float32(5.0)); got != 3.0 {
t.Errorf("AtMost() = %v, want 3.0", got)
}
if got := AtMost(float32(5.0), float32(5.0)); got != 5.0 {
t.Errorf("AtMost() = %v, want 5.0", got)
}
})
t.Run("test float64", func(t *testing.T) {
if got := AtMost(10.0, 5.0); got != 5.0 {
t.Errorf("AtMost() = %v, want 5.0", got)
}
if got := AtMost(3.0, 5.0); got != 3.0 {
t.Errorf("AtMost() = %v, want 3.0", got)
}
if got := AtMost(5.0, 5.0); got != 5.0 {
t.Errorf("AtMost() = %v, want 5.0", got)
}
})
}
func TestBetween(t *testing.T) {
t.Run("test int", func(t *testing.T) {
if got := Between(10, 5, 15); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(3, 5, 15); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(20, 5, 15); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(5, 5, 15); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(15, 5, 15); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test int8", func(t *testing.T) {
if got := Between(int8(10), int8(5), int8(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(int8(3), int8(5), int8(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int8(20), int8(5), int8(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(int8(5), int8(5), int8(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int8(15), int8(5), int8(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test int16", func(t *testing.T) {
if got := Between(int16(10), int16(5), int16(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(int16(3), int16(5), int16(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int16(20), int16(5), int16(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(int16(5), int16(5), int16(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int16(15), int16(5), int16(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test int32", func(t *testing.T) {
if got := Between(int32(10), int32(5), int32(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(int32(3), int32(5), int32(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int32(20), int32(5), int32(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(int32(5), int32(5), int32(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int32(15), int32(5), int32(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test int64", func(t *testing.T) {
if got := Between(int64(10), int64(5), int64(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(int64(3), int64(5), int64(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int64(20), int64(5), int64(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(int64(5), int64(5), int64(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(int64(15), int64(5), int64(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test uint", func(t *testing.T) {
if got := Between(uint(10), uint(5), uint(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(uint(3), uint(5), uint(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint(20), uint(5), uint(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(uint(5), uint(5), uint(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint(15), uint(5), uint(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test uint8", func(t *testing.T) {
if got := Between(uint8(10), uint8(5), uint8(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(uint8(3), uint8(5), uint8(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint8(20), uint8(5), uint8(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(uint8(5), uint8(5), uint8(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint8(15), uint8(5), uint8(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test uint16", func(t *testing.T) {
if got := Between(uint16(10), uint16(5), uint16(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(uint16(3), uint16(5), uint16(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint16(20), uint16(5), uint16(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(uint16(5), uint16(5), uint16(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint16(15), uint16(5), uint16(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test uint32", func(t *testing.T) {
if got := Between(uint32(10), uint32(5), uint32(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(uint32(3), uint32(5), uint32(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint32(20), uint32(5), uint32(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(uint32(5), uint32(5), uint32(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint32(15), uint32(5), uint32(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test uint64", func(t *testing.T) {
if got := Between(uint64(10), uint64(5), uint64(15)); got != 10 {
t.Errorf("Between() = %v, want 10", got)
}
if got := Between(uint64(3), uint64(5), uint64(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint64(20), uint64(5), uint64(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
if got := Between(uint64(5), uint64(5), uint64(15)); got != 5 {
t.Errorf("Between() = %v, want 5", got)
}
if got := Between(uint64(15), uint64(5), uint64(15)); got != 15 {
t.Errorf("Between() = %v, want 15", got)
}
})
t.Run("test float32", func(t *testing.T) {
if got := Between(float32(10.0), float32(5.0), float32(15.0)); got != 10.0 {
t.Errorf("Between() = %v, want 10.0", got)
}
if got := Between(float32(3.0), float32(5.0), float32(15.0)); got != 5.0 {
t.Errorf("Between() = %v, want 5.0", got)
}
if got := Between(float32(20.0), float32(5.0), float32(15.0)); got != 15.0 {
t.Errorf("Between() = %v, want 15.0", got)
}
if got := Between(float32(5.0), float32(5.0), float32(15.0)); got != 5.0 {
t.Errorf("Between() = %v, want 5.0", got)
}
if got := Between(float32(15.0), float32(5.0), float32(15.0)); got != 15.0 {
t.Errorf("Between() = %v, want 15.0", got)
}
})
t.Run("test float64", func(t *testing.T) {
if got := Between(10.0, 5.0, 15.0); got != 10.0 {
t.Errorf("Between() = %v, want 10.0", got)
}
if got := Between(3.0, 5.0, 15.0); got != 5.0 {
t.Errorf("Between() = %v, want 5.0", got)
}
if got := Between(20.0, 5.0, 15.0); got != 15.0 {
t.Errorf("Between() = %v, want 15.0", got)
}
if got := Between(5.0, 5.0, 15.0); got != 5.0 {
t.Errorf("Between() = %v, want 5.0", got)
}
if got := Between(15.0, 5.0, 15.0); got != 15.0 {
t.Errorf("Between() = %v, want 15.0", got)
}
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/proba.go | core/mathx/proba.go | package mathx
import (
"math/rand"
"sync"
"time"
)
// A Proba is used to test if true on given probability.
type Proba struct {
// rand.New(...) returns a non thread safe object
r *rand.Rand
lock sync.Mutex
}
// NewProba returns a Proba.
func NewProba() *Proba {
return &Proba{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
// TrueOnProba checks if true on given probability.
func (p *Proba) TrueOnProba(proba float64) (truth bool) {
p.lock.Lock()
truth = p.r.Float64() < proba
p.lock.Unlock()
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/entropy.go | core/mathx/entropy.go | package mathx
import "math"
const epsilon = 1e-6
// CalcEntropy calculates the entropy of m.
func CalcEntropy(m map[any]int) float64 {
if len(m) == 0 || len(m) == 1 {
return 1
}
var entropy float64
var total int
for _, v := range m {
total += v
}
for _, v := range m {
proba := float64(v) / float64(total)
if proba < epsilon {
proba = epsilon
}
entropy -= proba * math.Log2(proba)
}
return entropy / math.Log2(float64(len(m)))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/entropy_test.go | core/mathx/entropy_test.go | package mathx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCalcEntropy(t *testing.T) {
const total = 1000
const count = 100
m := make(map[any]int, total)
for i := 0; i < total; i++ {
m[i] = count
}
assert.True(t, CalcEntropy(m) > .99)
}
func TestCalcEmptyEntropy(t *testing.T) {
m := make(map[any]int)
assert.Equal(t, float64(1), CalcEntropy(m))
}
func TestCalcDiffEntropy(t *testing.T) {
const total = 1000
m := make(map[any]int, total)
for i := 0; i < total; i++ {
m[i] = i
}
assert.True(t, CalcEntropy(m) < .99)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/unstable.go | core/mathx/unstable.go | package mathx
import (
"math/rand"
"sync"
"time"
)
// An Unstable is used to generate random value around the mean value based on given deviation.
type Unstable struct {
deviation float64
r *rand.Rand
lock *sync.Mutex
}
// NewUnstable returns an Unstable.
func NewUnstable(deviation float64) Unstable {
if deviation < 0 {
deviation = 0
}
if deviation > 1 {
deviation = 1
}
return Unstable{
deviation: deviation,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
}
}
// AroundDuration returns a random duration with given base and deviation.
func (u Unstable) AroundDuration(base time.Duration) time.Duration {
u.lock.Lock()
val := time.Duration((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}
// AroundInt returns a random int64 with given base and deviation.
func (u Unstable) AroundInt(base int64) int64 {
u.lock.Lock()
val := int64((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/int_test.go | core/mathx/int_test.go | package mathx
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestMaxInt(t *testing.T) {
cases := []struct {
a int
b int
expect int
}{
{
a: 0,
b: 1,
expect: 1,
},
{
a: 0,
b: -1,
expect: 0,
},
{
a: 1,
b: 1,
expect: 1,
},
}
for _, each := range cases {
each := each
t.Run(stringx.Rand(), func(t *testing.T) {
actual := MaxInt(each.a, each.b)
assert.Equal(t, each.expect, actual)
})
}
}
func TestMinInt(t *testing.T) {
cases := []struct {
a int
b int
expect int
}{
{
a: 0,
b: 1,
expect: 0,
},
{
a: 0,
b: -1,
expect: -1,
},
{
a: 1,
b: 1,
expect: 1,
},
}
for _, each := range cases {
t.Run(stringx.Rand(), func(t *testing.T) {
actual := MinInt(each.a, each.b)
assert.Equal(t, each.expect, actual)
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/proba_test.go | core/mathx/proba_test.go | package mathx
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTrueOnProba(t *testing.T) {
const proba = math.Pi / 10
const total = 100000
const epsilon = 0.05
var count int
p := NewProba()
for i := 0; i < total; i++ {
if p.TrueOnProba(proba) {
count++
}
}
ratio := float64(count) / float64(total)
assert.InEpsilon(t, proba, ratio, epsilon)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/int.go | core/mathx/int.go | package mathx
// MaxInt returns the larger one of a and b.
// Deprecated: use builtin max instead.
func MaxInt(a, b int) int {
return max(a, b)
}
// MinInt returns the smaller one of a and b.
// Deprecated: use builtin min instead.
func MinInt(a, b int) int {
return min(a, b)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/unstable_test.go | core/mathx/unstable_test.go | package mathx
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestUnstable_AroundDuration(t *testing.T) {
unstable := NewUnstable(0.05)
for i := 0; i < 1000; i++ {
val := unstable.AroundDuration(time.Second)
assert.True(t, float64(time.Second)*0.95 <= float64(val))
assert.True(t, float64(val) <= float64(time.Second)*1.05)
}
}
func TestUnstable_AroundInt(t *testing.T) {
const target = 10000
unstable := NewUnstable(0.05)
for i := 0; i < 1000; i++ {
val := unstable.AroundInt(target)
assert.True(t, float64(target)*0.95 <= float64(val))
assert.True(t, float64(val) <= float64(target)*1.05)
}
}
func TestUnstable_AroundIntLarge(t *testing.T) {
const target int64 = 10000
unstable := NewUnstable(5)
for i := 0; i < 1000; i++ {
val := unstable.AroundInt(target)
assert.True(t, 0 <= val)
assert.True(t, val <= 2*target)
}
}
func TestUnstable_AroundIntNegative(t *testing.T) {
const target int64 = 10000
unstable := NewUnstable(-0.05)
for i := 0; i < 1000; i++ {
val := unstable.AroundInt(target)
assert.Equal(t, target, val)
}
}
func TestUnstable_Distribution(t *testing.T) {
const (
seconds = 10000
total = 10000
)
m := make(map[int]int)
expiry := NewUnstable(0.05)
for i := 0; i < total; i++ {
val := int(expiry.AroundInt(seconds))
m[val]++
}
_, ok := m[0]
assert.False(t, ok)
mi := make(map[any]int, len(m))
for k, v := range m {
mi[k] = v
}
entropy := CalcEntropy(mi)
assert.True(t, len(m) > 1)
assert.True(t, entropy > 0.95)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/mathx/range.go | core/mathx/range.go | package mathx
type Numerical interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
// AtLeast returns the greater of x or lower.
func AtLeast[T Numerical](x, lower T) T {
if x < lower {
return lower
}
return x
}
// AtMost returns the smaller of x or upper.
func AtMost[T Numerical](x, upper T) T {
if x > upper {
return upper
}
return x
}
// Between returns the value of x clamped to the range [lower, upper].
func Between[T Numerical](x, lower, upper T) T {
if x < lower {
return lower
}
if x > upper {
return upper
}
return x
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/accountregistry_test.go | core/discov/accountregistry_test.go | package discov
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/discov/internal"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestRegisterAccount(t *testing.T) {
endpoints := []string{
"localhost:2379",
}
user := "foo" + stringx.Rand()
RegisterAccount(endpoints, user, "bar")
account, ok := internal.GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, user, account.User)
assert.Equal(t, "bar", account.Pass)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/config.go | core/discov/config.go | package discov
import "errors"
var (
// errEmptyEtcdHosts indicates that etcd hosts are empty.
errEmptyEtcdHosts = errors.New("empty etcd hosts")
// errEmptyEtcdKey indicates that etcd key is empty.
errEmptyEtcdKey = errors.New("empty etcd key")
)
// EtcdConf is the config item with the given key on etcd.
type EtcdConf struct {
Hosts []string
Key string
ID int64 `json:",optional"`
User string `json:",optional"`
Pass string `json:",optional"`
CertFile string `json:",optional"`
CertKeyFile string `json:",optional=CertFile"`
CACertFile string `json:",optional=CertFile"`
InsecureSkipVerify bool `json:",optional"`
}
// HasAccount returns if account provided.
func (c EtcdConf) HasAccount() bool {
return len(c.User) > 0 && len(c.Pass) > 0
}
// HasID returns if ID provided.
func (c EtcdConf) HasID() bool {
return c.ID > 0
}
// HasTLS returns if TLS CertFile/CertKeyFile/CACertFile are provided.
func (c EtcdConf) HasTLS() bool {
return len(c.CertFile) > 0 && len(c.CertKeyFile) > 0 && len(c.CACertFile) > 0
}
// Validate validates c.
func (c EtcdConf) Validate() error {
if len(c.Hosts) == 0 {
return errEmptyEtcdHosts
} else if len(c.Key) == 0 {
return errEmptyEtcdKey
} else {
return nil
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/publisher_test.go | core/discov/publisher_test.go | package discov
import (
"context"
"errors"
"net"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/discov/internal"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stringx"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/mock/gomock"
"golang.org/x/net/http2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
)
const (
certContent = `-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUEg9GVO2oaPn+YSmiqmFIuAo10WIwDQYJKoZIhvcNAQEM
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yMzAzMTExMzIxMjNaGA8yMTIz
MDIxNTEzMjEyM1owRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBALplXlWsIf0O/IgnIplmiZHKGnxyfyufyE2FBRNk
OofRqbKuPH8GNqbkvZm7N29fwTDAQ+mViAggCkDht4hOzoWJMA7KYJt8JnTSWL48
M1lcrpc9DL2gszC/JF/FGvyANbBtLklkZPFBGdHUX14pjrT937wqPtm+SqUHSvRT
B7bmwmm2drRcmhpVm98LSlV7uQ2EgnJgsLjBPITKUejLmVLHfgX0RwQ2xIpX9pS4
FCe1BTacwl2gGp7Mje7y4Mfv3o0ArJW6Tuwbjx59ZXwb1KIP71b7bT04AVS8ZeYO
UMLKKuB5UR9x9Rn6cLXOTWBpcMVyzDgrAFLZjnE9LPUolZMCAwEAAaNRME8wHwYD
VR0jBBgwFoAUeW8w8pmhncbRgTsl48k4/7wnfx8wCQYDVR0TBAIwADALBgNVHQ8E
BAMCBPAwFAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBDAUAA4IBAQAI
y9xaoS88CLPBsX6mxfcTAFVfGNTRW9VN9Ng1cCnUR+YGoXGM/l+qP4f7p8ocdGwK
iYZErVTzXYIn+D27//wpY3klJk3gAnEUBT3QRkStBw7XnpbeZ2oPBK+cmDnCnZPS
BIF1wxPX7vIgaxs5Zsdqwk3qvZ4Djr2wP7LabNWTLSBKgQoUY45Liw6pffLwcGF9
UKlu54bvGze2SufISCR3ib+I+FLvqpvJhXToZWYb/pfI/HccuCL1oot1x8vx6DQy
U+TYxlZsKS5mdNxAX3dqEkEMsgEi+g/tzDPXJImfeCGGBhIOXLm8SRypiuGdEbc9
xkWYxRPegajuEZGvCqVs
-----END CERTIFICATE-----`
keyContent = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAumVeVawh/Q78iCcimWaJkcoafHJ/K5/ITYUFE2Q6h9Gpsq48
fwY2puS9mbs3b1/BMMBD6ZWICCAKQOG3iE7OhYkwDspgm3wmdNJYvjwzWVyulz0M
vaCzML8kX8Ua/IA1sG0uSWRk8UEZ0dRfXimOtP3fvCo+2b5KpQdK9FMHtubCabZ2
tFyaGlWb3wtKVXu5DYSCcmCwuME8hMpR6MuZUsd+BfRHBDbEilf2lLgUJ7UFNpzC
XaAansyN7vLgx+/ejQCslbpO7BuPHn1lfBvUog/vVvttPTgBVLxl5g5Qwsoq4HlR
H3H1Gfpwtc5NYGlwxXLMOCsAUtmOcT0s9SiVkwIDAQABAoIBAD5meTJNMgO55Kjg
ESExxpRcCIno+tHr5+6rvYtEXqPheOIsmmwb9Gfi4+Z3WpOaht5/Pz0Ppj6yGzyl
U//6AgGKb+BDuBvVcDpjwPnOxZIBCSHwejdxeQu0scSuA97MPS0XIAvJ5FEv7ijk
5Bht6SyGYURpECltHygoTNuGgGqmO+McCJRLE9L09lTBI6UQ/JQwWJqSr7wx6iPU
M1Ze/srIV+7cyEPu6i0DGjS1gSQKkX68Lqn1w6oE290O+OZvleO0gZ02fLDWCZke
aeD9+EU/Pw+rqm3H6o0szOFIpzhRp41FUdW9sybB3Yp3u7c/574E+04Z/e30LMKs
TCtE1QECgYEA3K7KIpw0NH2HXL5C3RHcLmr204xeBfS70riBQQuVUgYdmxak2ima
80RInskY8hRhSGTg0l+VYIH8cmjcUyqMSOELS5XfRH99r4QPiK8AguXg80T4VumY
W3Pf+zEC2ssgP/gYthV0g0Xj5m2QxktOF9tRw5nkg739ZR4dI9lm/iECgYEA2Dnf
uwEDGqHiQRF6/fh5BG/nGVMvrefkqx6WvTJQ3k/M/9WhxB+lr/8yH46TuS8N2b29
FoTf3Mr9T7pr/PWkOPzoY3P56nYbKU8xSwCim9xMzhBMzj8/N9ukJvXy27/VOz56
eQaKqnvdXNGtPJrIMDGHps2KKWlKLyAlapzjVTMCgYAA/W++tACv85g13EykfT4F
n0k4LbsGP9DP4zABQLIMyiY72eAncmRVjwrcW36XJ2xATOONTgx3gF3HjZzfaqNy
eD/6uNNllUTVEryXGmHgNHPL45VRnn6memCY2eFvZdXhM5W4y2PYaunY0MkDercA
+GTngbs6tBF88KOk04bYwQKBgFl68cRgsdkmnwwQYNaTKfmVGYzYaQXNzkqmWPko
xmCJo6tHzC7ubdG8iRCYHzfmahPuuj6EdGPZuSRyYFgJi5Ftz/nAN+84OxtIQ3zn
YWOgskQgaLh9YfsKsQ7Sf1NDOsnOnD5TX7UXl07fEpLe9vNCvAFiU8e5Y9LGudU5
4bYTAoGBAMdX3a3bXp4cZvXNBJ/QLVyxC6fP1Q4haCR1Od3m+T00Jth2IX2dk/fl
p6xiJT1av5JtYabv1dFKaXOS5s1kLGGuCCSKpkvFZm826aQ2AFm0XGqEQDLeei5b
A52Kpy/YJ+RkG4BTFtAooFq6DmA0cnoP6oPvG2h6XtDJwDTPInJb
-----END RSA PRIVATE KEY-----`
caContent = `-----BEGIN CERTIFICATE-----
MIIDbTCCAlWgAwIBAgIUBJvFoCowKich7MMfseJ+DYzzirowDQYJKoZIhvcNAQEM
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yMzAzMTExMzIxMDNaGA8yMTIz
MDIxNTEzMjEwM1owRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAO4to2YMYj0bxgr2FCiweSTSFuPx33zSw2x/s9Wf
OR41bm2DFsyYT5f3sOIKlXZEdLmOKty2e3ho3yC0EyNpVHdykkkHT3aDI17quZax
kYi/URqqtl1Z08A22txolc04hAZisg2BypGi3vql81UW1t3zyloGnJoIAeXR9uca
ljP6Bk3bwsxoVBLi1JtHrO0hHLQaeHmKhAyrys06X0LRdn7Px48yRZlt6FaLSa8X
YiRM0G44bVy/h6BkoQjMYGwVmCVk6zjJ9U7ZPFqdnDMNxAfR+hjDnYodqdLDMTTR
1NPVrnEnNwFx0AMLvgt/ba/45vZCEAmSZnFXFAJJcM7ai9ECAwEAAaNTMFEwHQYD
VR0OBBYEFHlvMPKZoZ3G0YE7JePJOP+8J38fMB8GA1UdIwQYMBaAFHlvMPKZoZ3G
0YE7JePJOP+8J38fMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggEB
AMX8dNulADOo9uQgBMyFb9TVra7iY0zZjzv4GY5XY7scd52n6CnfAPvYBBDnTr/O
BgNp5jaujb4+9u/2qhV3f9n+/3WOb2CmPehBgVSzlXqHeQ9lshmgwZPeem2T+8Tm
Nnc/xQnsUfCFszUDxpkr55+aLVM22j02RWqcZ4q7TAaVYL+kdFVMc8FoqG/0ro6A
BjE/Qn0Nn7ciX1VUjDt8l+k7ummPJTmzdi6i6E4AwO9dzrGNgGJ4aWL8cC6xYcIX
goVIRTFeONXSDno/oPjWHpIPt7L15heMpKBHNuzPkKx2YVqPHE5QZxWfS+Lzgx+Q
E2oTTM0rYKOZ8p6000mhvKI=
-----END CERTIFICATE-----`
)
func init() {
logx.Disable()
}
func TestPublisher_register(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().Grant(gomock.Any(), timeToLive).Return(&clientv3.LeaseGrantResponse{
ID: id,
}, nil)
cli.EXPECT().Put(gomock.Any(), makeEtcdKey("thekey", id), "thevalue", gomock.Any())
pub := NewPublisher(nil, "thekey", "thevalue",
WithPubEtcdAccount(stringx.Rand(), "bar"))
_, err := pub.register(cli)
assert.Nil(t, err)
}
func TestPublisher_registerWithOptions(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id = 2
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().Grant(gomock.Any(), timeToLive).Return(&clientv3.LeaseGrantResponse{
ID: 1,
}, nil)
cli.EXPECT().Put(gomock.Any(), makeEtcdKey("thekey", id), "thevalue", gomock.Any())
certFile := createTempFile(t, []byte(certContent))
defer os.Remove(certFile)
keyFile := createTempFile(t, []byte(keyContent))
defer os.Remove(keyFile)
caFile := createTempFile(t, []byte(caContent))
defer os.Remove(caFile)
pub := NewPublisher(nil, "thekey", "thevalue", WithId(id),
WithPubEtcdTLS(certFile, keyFile, caFile, true))
_, err := pub.register(cli)
assert.Nil(t, err)
}
func TestPublisher_registerError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().Grant(gomock.Any(), timeToLive).Return(nil, errors.New("error"))
pub := NewPublisher(nil, "thekey", "thevalue")
val, err := pub.register(cli)
assert.NotNil(t, err)
assert.Equal(t, clientv3.NoLease, val)
}
func TestPublisher_revoke(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().Revoke(gomock.Any(), id)
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
pub.revoke(cli)
}
func TestPublisher_revokeError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().Revoke(gomock.Any(), id).Return(nil, errors.New("error"))
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
pub.revoke(cli)
}
func TestPublisher_keepAliveAsyncError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id).Return(nil, errors.New("error"))
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
assert.NotNil(t, pub.keepAliveAsync(cli))
}
func TestPublisher_keepAliveAsyncQuit(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
cli.EXPECT().ActiveConnection()
cli.EXPECT().Close()
defer cli.Close()
cli.ActiveConnection()
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id)
// Add Watch expectation for the new watch mechanism
watchChan := make(<-chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), gomock.Any(), gomock.Any()).Return(watchChan)
var wg sync.WaitGroup
wg.Add(1)
cli.EXPECT().Revoke(gomock.Any(), id).Do(func(_, _ any) {
wg.Done()
})
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
pub.Stop()
assert.Nil(t, pub.keepAliveAsync(cli))
wg.Wait()
}
func TestPublisher_keepAliveAsyncPause(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id)
// Add Watch expectation for the new watch mechanism
watchChan := make(<-chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), gomock.Any(), gomock.Any()).Return(watchChan)
pub := NewPublisher(nil, "thekey", "thevalue")
var wg sync.WaitGroup
wg.Add(1)
cli.EXPECT().Revoke(gomock.Any(), id).Do(func(_, _ any) {
pub.Stop()
wg.Done()
})
pub.lease = id
assert.Nil(t, pub.keepAliveAsync(cli))
pub.Pause()
wg.Wait()
}
// Test case for key deletion and re-registration (covers lines 148-155)
func TestPublisher_keepAliveAsyncKeyDeletion(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id)
// Create a watch channel that will send a delete event
watchChan := make(chan clientv3.WatchResponse, 1)
watchResp := clientv3.WatchResponse{
Events: []*clientv3.Event{{
Type: clientv3.EventTypeDelete,
Kv: &mvccpb.KeyValue{
Key: []byte("thekey"),
},
}},
}
watchChan <- watchResp
cli.EXPECT().Watch(gomock.Any(), gomock.Any(), gomock.Any()).Return((<-chan clientv3.WatchResponse)(watchChan))
var wg sync.WaitGroup
wg.Add(1) // Only wait for Revoke call
// Use a channel to signal when Put has been called
putCalled := make(chan struct{})
// Expect the re-put operation when key is deleted
cli.EXPECT().Put(gomock.Any(), "thekey", "thevalue", gomock.Any()).Do(func(_, _, _, _ any) {
close(putCalled) // Signal that Put has been called
}).Return(nil, nil)
// Expect revoke when Stop is called
cli.EXPECT().Revoke(gomock.Any(), id).Do(func(_, _ any) {
wg.Done()
})
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
pub.fullKey = "thekey"
assert.Nil(t, pub.keepAliveAsync(cli))
// Wait for Put to be called, then stop
<-putCalled
pub.Stop()
wg.Wait()
}
// Test case for key deletion with re-put error (covers error branch in lines 151-152)
func TestPublisher_keepAliveAsyncKeyDeletionPutError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
cli := internal.NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id)
// Create a watch channel that will send a delete event
watchChan := make(chan clientv3.WatchResponse, 1)
watchResp := clientv3.WatchResponse{
Events: []*clientv3.Event{{
Type: clientv3.EventTypeDelete,
Kv: &mvccpb.KeyValue{
Key: []byte("thekey"),
},
}},
}
watchChan <- watchResp
cli.EXPECT().Watch(gomock.Any(), gomock.Any(), gomock.Any()).Return((<-chan clientv3.WatchResponse)(watchChan))
var wg sync.WaitGroup
wg.Add(1) // Only wait for Revoke call
// Use a channel to signal when Put has been called
putCalled := make(chan struct{})
// Expect the re-put operation to fail
cli.EXPECT().Put(gomock.Any(), "thekey", "thevalue", gomock.Any()).Do(func(_, _, _, _ any) {
close(putCalled) // Signal that Put has been called
}).Return(nil, errors.New("put error"))
// Expect revoke when Stop is called
cli.EXPECT().Revoke(gomock.Any(), id).Do(func(_, _ any) {
wg.Done()
})
pub := NewPublisher(nil, "thekey", "thevalue")
pub.lease = id
pub.fullKey = "thekey"
assert.Nil(t, pub.keepAliveAsync(cli))
// Wait for Put to be called, then stop
<-putCalled
pub.Stop()
wg.Wait()
}
func TestPublisher_Resume(t *testing.T) {
publisher := new(Publisher)
publisher.resumeChan = make(chan lang.PlaceholderType)
go func() {
publisher.Resume()
}()
go func() {
time.Sleep(time.Minute)
t.Fail()
}()
<-publisher.resumeChan
}
func TestPublisher_keepAliveAsync(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
const id clientv3.LeaseID = 1
conn := createMockConn(t)
defer conn.Close()
cli := internal.NewMockEtcdClient(ctrl)
cli.EXPECT().ActiveConnection().Return(conn).AnyTimes()
cli.EXPECT().Close()
defer cli.Close()
cli.ActiveConnection()
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Ctx().AnyTimes()
cli.EXPECT().KeepAlive(gomock.Any(), id)
// Add Watch expectation for the new watch mechanism
watchChan := make(<-chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), gomock.Any(), gomock.Any()).Return(watchChan)
cli.EXPECT().Grant(gomock.Any(), timeToLive).Return(&clientv3.LeaseGrantResponse{
ID: 1,
}, nil)
cli.EXPECT().Put(gomock.Any(), makeEtcdKey("thekey", int64(id)), "thevalue", gomock.Any())
var wg sync.WaitGroup
wg.Add(1)
cli.EXPECT().Revoke(gomock.Any(), id).Do(func(_, _ any) {
wg.Done()
})
pub := NewPublisher([]string{"the-endpoint"}, "thekey", "thevalue")
pub.lease = id
assert.Nil(t, pub.KeepAlive())
pub.Stop()
wg.Wait()
}
func createMockConn(t *testing.T) *grpc.ClientConn {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error while listening. Err: %v", err)
}
defer lis.Close()
lisAddr := resolver.Address{Addr: lis.Addr().String()}
lisDone := make(chan struct{})
dialDone := make(chan struct{})
// 1st listener accepts the connection and then does nothing
go func() {
defer close(lisDone)
conn, err := lis.Accept()
if err != nil {
t.Errorf("Error while accepting. Err: %v", err)
return
}
framer := http2.NewFramer(conn, conn)
if err := framer.WriteSettings(http2.Setting{}); err != nil {
t.Errorf("Error while writing settings. Err: %v", err)
return
}
<-dialDone // Close conn only after dial returns.
}()
r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{lisAddr}})
client, err := grpc.DialContext(context.Background(), r.Scheme()+":///test.server",
grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithResolvers(r))
close(dialDone)
if err != nil {
t.Fatalf("Dial failed. Err: %v", err)
}
timeout := time.After(1 * time.Second)
select {
case <-timeout:
t.Fatal("timed out waiting for server to finish")
case <-lisDone:
}
return client
}
func createTempFile(t *testing.T, body []byte) string {
tmpFile, err := os.CreateTemp(os.TempDir(), "go-unit-*.tmp")
if err != nil {
t.Fatal(err)
}
tmpFile.Close()
if err = os.WriteFile(tmpFile.Name(), body, os.ModePerm); err != nil {
t.Fatal(err)
}
return tmpFile.Name()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/subscriber.go | core/discov/subscriber.go | package discov
import (
"sync"
"sync/atomic"
"github.com/zeromicro/go-zero/core/discov/internal"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
)
type (
// SubOption defines the method to customize a Subscriber.
SubOption func(sub *Subscriber)
// A Subscriber is used to subscribe the given key on an etcd cluster.
Subscriber struct {
endpoints []string
exclusive bool
key string
exactMatch bool
items Container
}
KV = internal.KV
)
// NewSubscriber returns a Subscriber.
// endpoints is the hosts of the etcd cluster.
// key is the key to subscribe.
// opts are used to customize the Subscriber.
func NewSubscriber(endpoints []string, key string, opts ...SubOption) (*Subscriber, error) {
sub := &Subscriber{
endpoints: endpoints,
key: key,
}
for _, opt := range opts {
opt(sub)
}
if sub.items == nil {
sub.items = newContainer(sub.exclusive)
}
if err := internal.GetRegistry().Monitor(endpoints, key, sub.exactMatch, sub.items); err != nil {
return nil, err
}
return sub, nil
}
// AddListener adds listener to s.
func (s *Subscriber) AddListener(listener func()) {
s.items.AddListener(listener)
}
// Close closes the subscriber.
func (s *Subscriber) Close() {
internal.GetRegistry().Unmonitor(s.endpoints, s.key, s.exactMatch, s.items)
}
// Values returns all the subscription values.
func (s *Subscriber) Values() []string {
return s.items.GetValues()
}
// Exclusive means that key value can only be 1:1,
// which means later added value will remove the keys associated with the same value previously.
func Exclusive() SubOption {
return func(sub *Subscriber) {
sub.exclusive = true
}
}
// WithExactMatch turn off querying using key prefixes.
func WithExactMatch() SubOption {
return func(sub *Subscriber) {
sub.exactMatch = true
}
}
// WithSubEtcdAccount provides the etcd username/password.
func WithSubEtcdAccount(user, pass string) SubOption {
return func(sub *Subscriber) {
RegisterAccount(sub.endpoints, user, pass)
}
}
// WithSubEtcdTLS provides the etcd CertFile/CertKeyFile/CACertFile.
func WithSubEtcdTLS(certFile, certKeyFile, caFile string, insecureSkipVerify bool) SubOption {
return func(sub *Subscriber) {
logx.Must(RegisterTLS(sub.endpoints, certFile, certKeyFile, caFile, insecureSkipVerify))
}
}
// WithContainer provides a custom container to the subscriber.
func WithContainer(container Container) SubOption {
return func(sub *Subscriber) {
sub.items = container
}
}
type (
Container interface {
OnAdd(kv internal.KV)
OnDelete(kv internal.KV)
AddListener(listener func())
GetValues() []string
}
container struct {
exclusive bool
values map[string][]string
mapping map[string]string
snapshot atomic.Value
dirty *syncx.AtomicBool
listeners []func()
lock sync.Mutex
}
)
func newContainer(exclusive bool) *container {
return &container{
exclusive: exclusive,
values: make(map[string][]string),
mapping: make(map[string]string),
dirty: syncx.ForAtomicBool(true),
}
}
func (c *container) OnAdd(kv internal.KV) {
c.addKv(kv.Key, kv.Val)
c.notifyChange()
}
func (c *container) OnDelete(kv internal.KV) {
c.removeKey(kv.Key)
c.notifyChange()
}
// addKv adds the kv, returns if there are already other keys associate with the value
func (c *container) addKv(key, value string) ([]string, bool) {
c.lock.Lock()
defer c.lock.Unlock()
c.dirty.Set(true)
keys := c.values[value]
previous := append([]string(nil), keys...)
early := len(keys) > 0
if c.exclusive && early {
for _, each := range keys {
c.doRemoveKey(each)
}
}
c.values[value] = append(c.values[value], key)
c.mapping[key] = value
if early {
return previous, true
}
return nil, false
}
func (c *container) AddListener(listener func()) {
c.lock.Lock()
c.listeners = append(c.listeners, listener)
c.lock.Unlock()
}
func (c *container) doRemoveKey(key string) {
server, ok := c.mapping[key]
if !ok {
return
}
delete(c.mapping, key)
keys := c.values[server]
remain := keys[:0]
for _, k := range keys {
if k != key {
remain = append(remain, k)
}
}
if len(remain) > 0 {
c.values[server] = remain
} else {
delete(c.values, server)
}
}
func (c *container) GetValues() []string {
if !c.dirty.True() {
return c.snapshot.Load().([]string)
}
c.lock.Lock()
defer c.lock.Unlock()
var vals []string
for each := range c.values {
vals = append(vals, each)
}
c.snapshot.Store(vals)
c.dirty.Set(false)
return vals
}
func (c *container) notifyChange() {
c.lock.Lock()
listeners := append(([]func())(nil), c.listeners...)
c.lock.Unlock()
for _, listener := range listeners {
listener()
}
}
// removeKey removes the kv, returns true if there are still other keys associate with the value
func (c *container) removeKey(key string) {
c.lock.Lock()
defer c.lock.Unlock()
c.dirty.Set(true)
c.doRemoveKey(key)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/config_test.go | core/discov/config_test.go | package discov
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConfig(t *testing.T) {
tests := []struct {
EtcdConf
pass bool
}{
{
EtcdConf: EtcdConf{},
pass: false,
},
{
EtcdConf: EtcdConf{
Key: "any",
},
pass: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
},
pass: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
Key: "key",
},
pass: true,
},
}
for _, test := range tests {
if test.pass {
assert.Nil(t, test.EtcdConf.Validate())
} else {
assert.NotNil(t, test.EtcdConf.Validate())
}
}
}
func TestEtcdConf_HasAccount(t *testing.T) {
tests := []struct {
EtcdConf
hasAccount bool
}{
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
Key: "key",
},
hasAccount: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
Key: "key",
User: "foo",
},
hasAccount: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
Key: "key",
User: "foo",
Pass: "bar",
},
hasAccount: true,
},
}
for _, test := range tests {
assert.Equal(t, test.hasAccount, test.EtcdConf.HasAccount())
}
}
func TestEtcdConf_HasID(t *testing.T) {
tests := []struct {
EtcdConf
hasServerID bool
}{
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
ID: -1,
},
hasServerID: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
ID: 0,
},
hasServerID: false,
},
{
EtcdConf: EtcdConf{
Hosts: []string{"any"},
ID: 10000,
},
hasServerID: true,
},
}
for _, test := range tests {
assert.Equal(t, test.hasServerID, test.EtcdConf.HasID())
}
}
func TestEtcdConf_HasTLS(t *testing.T) {
tests := []struct {
name string
conf EtcdConf
want bool
}{
{
name: "empty config",
conf: EtcdConf{},
want: false,
},
{
name: "missing CertFile",
conf: EtcdConf{
CertKeyFile: "key",
CACertFile: "ca",
},
want: false,
},
{
name: "missing CertKeyFile",
conf: EtcdConf{
CertFile: "cert",
CACertFile: "ca",
},
want: false,
},
{
name: "missing CACertFile",
conf: EtcdConf{
CertFile: "cert",
CertKeyFile: "key",
},
want: false,
},
{
name: "valid config",
conf: EtcdConf{
CertFile: "cert",
CertKeyFile: "key",
CACertFile: "ca",
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.conf.HasTLS()
assert.Equal(t, tt.want, got)
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/publisher.go | core/discov/publisher.go | package discov
import (
"time"
"github.com/zeromicro/go-zero/core/discov/internal"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/threading"
clientv3 "go.etcd.io/etcd/client/v3"
)
type (
// PubOption defines the method to customize a Publisher.
PubOption func(client *Publisher)
// A Publisher can be used to publish the value to an etcd cluster on the given key.
Publisher struct {
endpoints []string
key string
fullKey string
id int64
value string
lease clientv3.LeaseID
quit *syncx.DoneChan
pauseChan chan lang.PlaceholderType
resumeChan chan lang.PlaceholderType
}
)
// NewPublisher returns a Publisher.
// endpoints is the hosts of the etcd cluster.
// key:value are a pair to be published.
// opts are used to customize the Publisher.
func NewPublisher(endpoints []string, key, value string, opts ...PubOption) *Publisher {
publisher := &Publisher{
endpoints: endpoints,
key: key,
value: value,
quit: syncx.NewDoneChan(),
pauseChan: make(chan lang.PlaceholderType),
resumeChan: make(chan lang.PlaceholderType),
}
for _, opt := range opts {
opt(publisher)
}
return publisher
}
// KeepAlive keeps key:value alive.
func (p *Publisher) KeepAlive() error {
cli, err := p.doRegister()
if err != nil {
return err
}
proc.AddWrapUpListener(func() {
p.Stop()
})
return p.keepAliveAsync(cli)
}
// Pause pauses the renewing of key:value.
func (p *Publisher) Pause() {
p.pauseChan <- lang.Placeholder
}
// Resume resumes the renewing of key:value.
func (p *Publisher) Resume() {
p.resumeChan <- lang.Placeholder
}
// Stop stops the renewing and revokes the registration.
func (p *Publisher) Stop() {
p.quit.Close()
}
func (p *Publisher) doKeepAlive() error {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
select {
case <-p.quit.Done():
return nil
default:
cli, err := p.doRegister()
if err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher doRegister: %v", err)
break
}
if err := p.keepAliveAsync(cli); err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher keepAliveAsync: %v", err)
break
}
return nil
}
}
return nil
}
func (p *Publisher) doRegister() (internal.EtcdClient, error) {
cli, err := internal.GetRegistry().GetConn(p.endpoints)
if err != nil {
return nil, err
}
p.lease, err = p.register(cli)
return cli, err
}
func (p *Publisher) keepAliveAsync(cli internal.EtcdClient) error {
ch, err := cli.KeepAlive(cli.Ctx(), p.lease)
if err != nil {
return err
}
threading.GoSafe(func() {
wch := cli.Watch(cli.Ctx(), p.fullKey, clientv3.WithFilterPut())
for {
select {
case _, ok := <-ch:
if !ok {
p.revoke(cli)
if err := p.doKeepAlive(); err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher KeepAlive: %v", err)
}
return
}
case c := <-wch:
if c.Err() != nil {
logc.Errorf(cli.Ctx(), "etcd publisher watch: %v", c.Err())
if err := p.doKeepAlive(); err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher KeepAlive: %v", err)
}
return
}
for _, evt := range c.Events {
if evt.Type == clientv3.EventTypeDelete {
logc.Infof(cli.Ctx(), "etcd publisher watch: %s, event: %v",
evt.Kv.Key, evt.Type)
_, err := cli.Put(cli.Ctx(), p.fullKey, p.value, clientv3.WithLease(p.lease))
if err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher re-put key: %v", err)
} else {
logc.Infof(cli.Ctx(), "etcd publisher re-put key: %s, value: %s",
p.fullKey, p.value)
}
}
}
case <-p.pauseChan:
logc.Infof(cli.Ctx(), "paused etcd renew, key: %s, value: %s", p.key, p.value)
p.revoke(cli)
select {
case <-p.resumeChan:
if err := p.doKeepAlive(); err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher KeepAlive: %v", err)
}
return
case <-p.quit.Done():
return
}
case <-p.quit.Done():
p.revoke(cli)
return
}
}
})
return nil
}
func (p *Publisher) register(client internal.EtcdClient) (clientv3.LeaseID, error) {
resp, err := client.Grant(client.Ctx(), TimeToLive)
if err != nil {
return clientv3.NoLease, err
}
lease := resp.ID
if p.id > 0 {
p.fullKey = makeEtcdKey(p.key, p.id)
} else {
p.fullKey = makeEtcdKey(p.key, int64(lease))
}
_, err = client.Put(client.Ctx(), p.fullKey, p.value, clientv3.WithLease(lease))
return lease, err
}
func (p *Publisher) revoke(cli internal.EtcdClient) {
if _, err := cli.Revoke(cli.Ctx(), p.lease); err != nil {
logc.Errorf(cli.Ctx(), "etcd publisher revoke: %v", err)
}
}
// WithId customizes a Publisher with the id.
func WithId(id int64) PubOption {
return func(publisher *Publisher) {
publisher.id = id
}
}
// WithPubEtcdAccount provides the etcd username/password.
func WithPubEtcdAccount(user, pass string) PubOption {
return func(pub *Publisher) {
RegisterAccount(pub.endpoints, user, pass)
}
}
// WithPubEtcdTLS provides the etcd CertFile/CertKeyFile/CACertFile.
func WithPubEtcdTLS(certFile, certKeyFile, caFile string, insecureSkipVerify bool) PubOption {
return func(pub *Publisher) {
logx.Must(RegisterTLS(pub.endpoints, certFile, certKeyFile, caFile, insecureSkipVerify))
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/clients_test.go | core/discov/clients_test.go | package discov
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/discov/internal"
)
var mockLock sync.Mutex
func setMockClient(cli internal.EtcdClient) func() {
mockLock.Lock()
internal.NewClient = func([]string) (internal.EtcdClient, error) {
return cli, nil
}
return func() {
internal.NewClient = internal.DialClient
mockLock.Unlock()
}
}
func TestExtract(t *testing.T) {
id, ok := extractId("key/123/val")
assert.True(t, ok)
assert.Equal(t, "123", id)
_, ok = extract("any", -1)
assert.False(t, ok)
_, ok = extract("any", 10)
assert.False(t, ok)
}
func TestMakeKey(t *testing.T) {
assert.Equal(t, "key/123", makeEtcdKey("key", 123))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/accountregistry.go | core/discov/accountregistry.go | package discov
import "github.com/zeromicro/go-zero/core/discov/internal"
// RegisterAccount registers the username/password to the given etcd cluster.
func RegisterAccount(endpoints []string, user, pass string) {
internal.AddAccount(endpoints, user, pass)
}
// RegisterTLS registers the CertFile/CertKeyFile/CACertFile to the given etcd.
func RegisterTLS(endpoints []string, certFile, certKeyFile, caFile string,
insecureSkipVerify bool) error {
return internal.AddTLS(endpoints, certFile, certKeyFile, caFile, insecureSkipVerify)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/clients.go | core/discov/clients.go | package discov
import (
"fmt"
"strings"
"github.com/zeromicro/go-zero/core/discov/internal"
)
const (
_ = iota
indexOfId
)
const timeToLive int64 = 10
// TimeToLive is seconds to live in etcd.
var TimeToLive = timeToLive
func extract(etcdKey string, index int) (string, bool) {
if index < 0 {
return "", false
}
fields := strings.FieldsFunc(etcdKey, func(ch rune) bool {
return ch == internal.Delimiter
})
if index >= len(fields) {
return "", false
}
return fields[index], true
}
func extractId(etcdKey string) (string, bool) {
return extract(etcdKey, indexOfId)
}
func makeEtcdKey(key string, id int64) string {
return fmt.Sprintf("%s%c%d", key, internal.Delimiter, id)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/subscriber_test.go | core/discov/subscriber_test.go | package discov
import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/discov/internal"
"github.com/zeromicro/go-zero/core/stringx"
)
const (
actionAdd = iota
actionDel
)
func TestContainer(t *testing.T) {
type action struct {
act int
key string
val string
}
tests := []struct {
name string
do []action
expect []string
}{
{
name: "add one",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
},
expect: []string{
"a",
},
},
{
name: "add two",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
},
expect: []string{
"a",
"b",
},
},
{
name: "add two, delete one",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionDel,
key: "first",
},
},
expect: []string{"b"},
},
{
name: "add two, delete two",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionDel,
key: "first",
},
{
act: actionDel,
key: "second",
},
},
expect: []string{},
},
{
name: "add three, dup values, delete two",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionAdd,
key: "third",
val: "a",
},
{
act: actionDel,
key: "first",
},
{
act: actionDel,
key: "second",
},
},
expect: []string{"a"},
},
{
name: "add three, dup values, delete two, delete not added",
do: []action{
{
act: actionAdd,
key: "first",
val: "a",
},
{
act: actionAdd,
key: "second",
val: "b",
},
{
act: actionAdd,
key: "third",
val: "a",
},
{
act: actionDel,
key: "first",
},
{
act: actionDel,
key: "second",
},
{
act: actionDel,
key: "forth",
},
},
expect: []string{"a"},
},
}
exclusives := []bool{true, false}
for _, test := range tests {
for _, exclusive := range exclusives {
t.Run(test.name, func(t *testing.T) {
var changed bool
c := newContainer(exclusive)
c.AddListener(func() {
changed = true
})
assert.Nil(t, c.GetValues())
assert.False(t, changed)
for _, order := range test.do {
if order.act == actionAdd {
c.OnAdd(internal.KV{
Key: order.key,
Val: order.val,
})
} else {
c.OnDelete(internal.KV{
Key: order.key,
Val: order.val,
})
}
}
assert.True(t, changed)
assert.True(t, c.dirty.True())
assert.ElementsMatch(t, test.expect, c.GetValues())
assert.False(t, c.dirty.True())
assert.ElementsMatch(t, test.expect, c.GetValues())
})
}
}
}
func TestSubscriber(t *testing.T) {
sub := new(Subscriber)
Exclusive()(sub)
c := newContainer(sub.exclusive)
WithContainer(c)(sub)
sub.items = c
var count int32
sub.AddListener(func() {
atomic.AddInt32(&count, 1)
})
c.notifyChange()
assert.Empty(t, sub.Values())
assert.Equal(t, int32(1), atomic.LoadInt32(&count))
}
func TestWithSubEtcdAccount(t *testing.T) {
endpoints := []string{"localhost:2379"}
user := stringx.Rand()
WithSubEtcdAccount(user, "bar")(&Subscriber{
endpoints: endpoints,
})
account, ok := internal.GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, user, account.User)
assert.Equal(t, "bar", account.Pass)
}
func TestWithExactMatch(t *testing.T) {
sub := new(Subscriber)
WithExactMatch()(sub)
c := newContainer(sub.exclusive)
sub.items = c
var count int32
sub.AddListener(func() {
atomic.AddInt32(&count, 1)
})
c.notifyChange()
assert.Empty(t, sub.Values())
assert.Equal(t, int32(1), atomic.LoadInt32(&count))
}
func TestSubscriberClose(t *testing.T) {
l := newContainer(false)
sub := &Subscriber{
endpoints: []string{"localhost:12379"},
key: "foo",
items: l,
}
assert.NotPanics(t, func() {
sub.Close()
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/listener.go | core/discov/internal/listener.go | package internal
// Listener interface wraps the OnUpdate method.
type Listener interface {
OnUpdate(keys, values []string, newKey string)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/registry.go | core/discov/internal/registry.go | package internal
import (
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/logc"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/threading"
"go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
clientv3 "go.etcd.io/etcd/client/v3"
)
const coolDownDeviation = 0.05
var (
registry = Registry{
clusters: make(map[string]*cluster),
}
connManager = syncx.NewResourceManager()
coolDownUnstable = mathx.NewUnstable(coolDownDeviation)
errClosed = errors.New("etcd monitor chan has been closed")
)
// A Registry is a registry that manages the etcd client connections.
type Registry struct {
clusters map[string]*cluster
lock sync.RWMutex
}
// GetRegistry returns a global Registry.
func GetRegistry() *Registry {
return ®istry
}
// GetConn returns an etcd client connection associated with given endpoints.
func (r *Registry) GetConn(endpoints []string) (EtcdClient, error) {
c, _ := r.getOrCreateCluster(endpoints)
return c.getClient()
}
// Monitor monitors the key on given etcd endpoints, notify with the given UpdateListener.
func (r *Registry) Monitor(endpoints []string, key string, exactMatch bool, l UpdateListener) error {
wkey := watchKey{
key: key,
exactMatch: exactMatch,
}
c, exists := r.getOrCreateCluster(endpoints)
// if exists, the existing values should be updated to the listener.
if exists {
c.lock.Lock()
watcher, ok := c.watchers[wkey]
if ok {
watcher.listeners = append(watcher.listeners, l)
}
c.lock.Unlock()
if ok {
kvs := c.getCurrent(wkey)
for _, kv := range kvs {
l.OnAdd(kv)
}
return nil
}
}
return c.monitor(wkey, l)
}
func (r *Registry) Unmonitor(endpoints []string, key string, exactMatch bool, l UpdateListener) {
c, exists := r.getCluster(endpoints)
if !exists {
return
}
wkey := watchKey{
key: key,
exactMatch: exactMatch,
}
c.lock.Lock()
defer c.lock.Unlock()
watcher, ok := c.watchers[wkey]
if !ok {
return
}
for i, listener := range watcher.listeners {
if listener == l {
watcher.listeners = append(watcher.listeners[:i], watcher.listeners[i+1:]...)
break
}
}
if len(watcher.listeners) == 0 {
if watcher.cancel != nil {
watcher.cancel()
}
delete(c.watchers, wkey)
}
}
func (r *Registry) getCluster(endpoints []string) (*cluster, bool) {
clusterKey := getClusterKey(endpoints)
r.lock.RLock()
c, ok := r.clusters[clusterKey]
r.lock.RUnlock()
return c, ok
}
func (r *Registry) getOrCreateCluster(endpoints []string) (c *cluster, exists bool) {
c, exists = r.getCluster(endpoints)
if !exists {
clusterKey := getClusterKey(endpoints)
r.lock.Lock()
defer r.lock.Unlock()
// double-check locking
c, exists = r.clusters[clusterKey]
if !exists {
c = newCluster(endpoints)
r.clusters[clusterKey] = c
}
}
return
}
type (
watchKey struct {
key string
exactMatch bool
}
watchValue struct {
listeners []UpdateListener
values map[string]string
cancel context.CancelFunc
}
cluster struct {
endpoints []string
key string
watchers map[watchKey]*watchValue
watchGroup *threading.RoutineGroup
done chan lang.PlaceholderType
lock sync.RWMutex
}
)
func newCluster(endpoints []string) *cluster {
return &cluster{
endpoints: endpoints,
key: getClusterKey(endpoints),
watchers: make(map[watchKey]*watchValue),
watchGroup: threading.NewRoutineGroup(),
done: make(chan lang.PlaceholderType),
}
}
func (c *cluster) addListener(key watchKey, l UpdateListener) {
c.lock.Lock()
defer c.lock.Unlock()
watcher, ok := c.watchers[key]
if ok {
watcher.listeners = append(watcher.listeners, l)
return
}
val := newWatchValue()
val.listeners = []UpdateListener{l}
c.watchers[key] = val
}
func (c *cluster) getClient() (EtcdClient, error) {
val, err := connManager.GetResource(c.key, func() (io.Closer, error) {
return c.newClient()
})
if err != nil {
return nil, err
}
return val.(EtcdClient), nil
}
func (c *cluster) getCurrent(key watchKey) []KV {
c.lock.RLock()
defer c.lock.RUnlock()
watcher, ok := c.watchers[key]
if !ok {
return nil
}
kvs := make([]KV, 0, len(watcher.values))
for k, v := range watcher.values {
kvs = append(kvs, KV{
Key: k,
Val: v,
})
}
return kvs
}
func (c *cluster) handleChanges(key watchKey, kvs []KV) {
c.lock.Lock()
watcher, ok := c.watchers[key]
if !ok {
c.lock.Unlock()
return
}
listeners := append([]UpdateListener(nil), watcher.listeners...)
// watcher.values cannot be nil
vals := watcher.values
newVals := make(map[string]string, len(kvs)+len(vals))
for _, kv := range kvs {
newVals[kv.Key] = kv.Val
}
add, remove := calculateChanges(vals, newVals)
watcher.values = newVals
c.lock.Unlock()
for _, kv := range add {
for _, l := range listeners {
l.OnAdd(kv)
}
}
for _, kv := range remove {
for _, l := range listeners {
l.OnDelete(kv)
}
}
}
func (c *cluster) handleWatchEvents(ctx context.Context, key watchKey, events []*clientv3.Event) {
c.lock.RLock()
watcher, ok := c.watchers[key]
if !ok {
c.lock.RUnlock()
return
}
listeners := append([]UpdateListener(nil), watcher.listeners...)
c.lock.RUnlock()
for _, ev := range events {
switch ev.Type {
case clientv3.EventTypePut:
c.lock.Lock()
watcher.values[string(ev.Kv.Key)] = string(ev.Kv.Value)
c.lock.Unlock()
for _, l := range listeners {
l.OnAdd(KV{
Key: string(ev.Kv.Key),
Val: string(ev.Kv.Value),
})
}
case clientv3.EventTypeDelete:
c.lock.Lock()
delete(watcher.values, string(ev.Kv.Key))
c.lock.Unlock()
for _, l := range listeners {
l.OnDelete(KV{
Key: string(ev.Kv.Key),
Val: string(ev.Kv.Value),
})
}
default:
logc.Errorf(ctx, "Unknown event type: %v", ev.Type)
}
}
}
func (c *cluster) load(cli EtcdClient, key watchKey) int64 {
var resp *clientv3.GetResponse
for {
var err error
ctx, cancel := context.WithTimeout(cli.Ctx(), RequestTimeout)
if key.exactMatch {
resp, err = cli.Get(ctx, key.key)
} else {
resp, err = cli.Get(ctx, makeKeyPrefix(key.key), clientv3.WithPrefix())
}
cancel()
if err == nil {
break
}
logc.Errorf(cli.Ctx(), "%s, key: %s, exactMatch: %t", err.Error(), key.key, key.exactMatch)
time.Sleep(coolDownUnstable.AroundDuration(coolDownInterval))
}
kvs := make([]KV, 0, len(resp.Kvs))
for _, ev := range resp.Kvs {
kvs = append(kvs, KV{
Key: string(ev.Key),
Val: string(ev.Value),
})
}
c.handleChanges(key, kvs)
return resp.Header.Revision
}
func (c *cluster) monitor(key watchKey, l UpdateListener) error {
cli, err := c.getClient()
if err != nil {
return err
}
c.addListener(key, l)
rev := c.load(cli, key)
c.watchGroup.Run(func() {
c.watch(cli, key, rev)
})
return nil
}
func (c *cluster) newClient() (EtcdClient, error) {
cli, err := NewClient(c.endpoints)
if err != nil {
return nil, err
}
go c.watchConnState(cli)
return cli, nil
}
func (c *cluster) reload(cli EtcdClient) {
c.lock.Lock()
// cancel the previous watches
close(c.done)
c.watchGroup.Wait()
keys := make([]watchKey, 0, len(c.watchers))
for wk, wval := range c.watchers {
keys = append(keys, wk)
if wval.cancel != nil {
wval.cancel()
}
}
c.done = make(chan lang.PlaceholderType)
c.watchGroup = threading.NewRoutineGroup()
c.lock.Unlock()
// start new watches
for _, key := range keys {
k := key
c.watchGroup.Run(func() {
rev := c.load(cli, k)
c.watch(cli, k, rev)
})
}
}
func (c *cluster) watch(cli EtcdClient, key watchKey, rev int64) {
for {
err := c.watchStream(cli, key, rev)
if err == nil {
return
}
if rev != 0 && errors.Is(err, rpctypes.ErrCompacted) {
logc.Errorf(cli.Ctx(), "etcd watch stream has been compacted, try to reload, rev %d", rev)
rev = c.load(cli, key)
}
// log the error and retry with cooldown to prevent CPU/disk exhaustion
logc.Error(cli.Ctx(), err)
time.Sleep(coolDownUnstable.AroundDuration(coolDownInterval))
}
}
func (c *cluster) watchStream(cli EtcdClient, key watchKey, rev int64) error {
ctx, rch := c.setupWatch(cli, key, rev)
for {
select {
case wresp, ok := <-rch:
if !ok {
return errClosed
}
if wresp.Canceled {
return fmt.Errorf("etcd monitor chan has been canceled, error: %w", wresp.Err())
}
if wresp.Err() != nil {
return fmt.Errorf("etcd monitor chan error: %w", wresp.Err())
}
c.handleWatchEvents(ctx, key, wresp.Events)
case <-ctx.Done():
return nil
case <-c.done:
return nil
}
}
}
func (c *cluster) setupWatch(cli EtcdClient, key watchKey, rev int64) (context.Context, clientv3.WatchChan) {
var (
rch clientv3.WatchChan
ops []clientv3.OpOption
wkey = key.key
)
if !key.exactMatch {
wkey = makeKeyPrefix(key.key)
ops = append(ops, clientv3.WithPrefix())
}
if rev != 0 {
ops = append(ops, clientv3.WithRev(rev+1))
}
ctx, cancel := context.WithCancel(cli.Ctx())
if watcher, ok := c.watchers[key]; ok {
watcher.cancel = cancel
} else {
val := newWatchValue()
val.cancel = cancel
c.lock.Lock()
c.watchers[key] = val
c.lock.Unlock()
}
rch = cli.Watch(clientv3.WithRequireLeader(ctx), wkey, ops...)
return ctx, rch
}
func (c *cluster) watchConnState(cli EtcdClient) {
watcher := newStateWatcher()
watcher.addListener(func() {
go c.reload(cli)
})
watcher.watch(cli.ActiveConnection())
}
// DialClient dials an etcd cluster with given endpoints.
func DialClient(endpoints []string) (EtcdClient, error) {
cfg := clientv3.Config{
Endpoints: endpoints,
AutoSyncInterval: autoSyncInterval,
DialTimeout: DialTimeout,
RejectOldCluster: true,
PermitWithoutStream: true,
}
if account, ok := GetAccount(endpoints); ok {
cfg.Username = account.User
cfg.Password = account.Pass
}
if tlsCfg, ok := GetTLS(endpoints); ok {
cfg.TLS = tlsCfg
}
return clientv3.New(cfg)
}
func calculateChanges(oldVals, newVals map[string]string) (add, remove []KV) {
for k, v := range newVals {
if val, ok := oldVals[k]; !ok || v != val {
add = append(add, KV{
Key: k,
Val: v,
})
}
}
for k, v := range oldVals {
if val, ok := newVals[k]; !ok || v != val {
remove = append(remove, KV{
Key: k,
Val: v,
})
}
}
return add, remove
}
func getClusterKey(endpoints []string) string {
sort.Strings(endpoints)
return strings.Join(endpoints, endpointsSeparator)
}
func makeKeyPrefix(key string) string {
return fmt.Sprintf("%s%c", key, Delimiter)
}
// NewClient returns a watchValue that make sure values are not nil.
func newWatchValue() *watchValue {
return &watchValue{
values: make(map[string]string),
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/accountmanager_test.go | core/discov/internal/accountmanager_test.go | package internal
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stringx"
)
const (
certContent = `-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUEg9GVO2oaPn+YSmiqmFIuAo10WIwDQYJKoZIhvcNAQEM
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yMzAzMTExMzIxMjNaGA8yMTIz
MDIxNTEzMjEyM1owRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBALplXlWsIf0O/IgnIplmiZHKGnxyfyufyE2FBRNk
OofRqbKuPH8GNqbkvZm7N29fwTDAQ+mViAggCkDht4hOzoWJMA7KYJt8JnTSWL48
M1lcrpc9DL2gszC/JF/FGvyANbBtLklkZPFBGdHUX14pjrT937wqPtm+SqUHSvRT
B7bmwmm2drRcmhpVm98LSlV7uQ2EgnJgsLjBPITKUejLmVLHfgX0RwQ2xIpX9pS4
FCe1BTacwl2gGp7Mje7y4Mfv3o0ArJW6Tuwbjx59ZXwb1KIP71b7bT04AVS8ZeYO
UMLKKuB5UR9x9Rn6cLXOTWBpcMVyzDgrAFLZjnE9LPUolZMCAwEAAaNRME8wHwYD
VR0jBBgwFoAUeW8w8pmhncbRgTsl48k4/7wnfx8wCQYDVR0TBAIwADALBgNVHQ8E
BAMCBPAwFAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBDAUAA4IBAQAI
y9xaoS88CLPBsX6mxfcTAFVfGNTRW9VN9Ng1cCnUR+YGoXGM/l+qP4f7p8ocdGwK
iYZErVTzXYIn+D27//wpY3klJk3gAnEUBT3QRkStBw7XnpbeZ2oPBK+cmDnCnZPS
BIF1wxPX7vIgaxs5Zsdqwk3qvZ4Djr2wP7LabNWTLSBKgQoUY45Liw6pffLwcGF9
UKlu54bvGze2SufISCR3ib+I+FLvqpvJhXToZWYb/pfI/HccuCL1oot1x8vx6DQy
U+TYxlZsKS5mdNxAX3dqEkEMsgEi+g/tzDPXJImfeCGGBhIOXLm8SRypiuGdEbc9
xkWYxRPegajuEZGvCqVs
-----END CERTIFICATE-----`
keyContent = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAumVeVawh/Q78iCcimWaJkcoafHJ/K5/ITYUFE2Q6h9Gpsq48
fwY2puS9mbs3b1/BMMBD6ZWICCAKQOG3iE7OhYkwDspgm3wmdNJYvjwzWVyulz0M
vaCzML8kX8Ua/IA1sG0uSWRk8UEZ0dRfXimOtP3fvCo+2b5KpQdK9FMHtubCabZ2
tFyaGlWb3wtKVXu5DYSCcmCwuME8hMpR6MuZUsd+BfRHBDbEilf2lLgUJ7UFNpzC
XaAansyN7vLgx+/ejQCslbpO7BuPHn1lfBvUog/vVvttPTgBVLxl5g5Qwsoq4HlR
H3H1Gfpwtc5NYGlwxXLMOCsAUtmOcT0s9SiVkwIDAQABAoIBAD5meTJNMgO55Kjg
ESExxpRcCIno+tHr5+6rvYtEXqPheOIsmmwb9Gfi4+Z3WpOaht5/Pz0Ppj6yGzyl
U//6AgGKb+BDuBvVcDpjwPnOxZIBCSHwejdxeQu0scSuA97MPS0XIAvJ5FEv7ijk
5Bht6SyGYURpECltHygoTNuGgGqmO+McCJRLE9L09lTBI6UQ/JQwWJqSr7wx6iPU
M1Ze/srIV+7cyEPu6i0DGjS1gSQKkX68Lqn1w6oE290O+OZvleO0gZ02fLDWCZke
aeD9+EU/Pw+rqm3H6o0szOFIpzhRp41FUdW9sybB3Yp3u7c/574E+04Z/e30LMKs
TCtE1QECgYEA3K7KIpw0NH2HXL5C3RHcLmr204xeBfS70riBQQuVUgYdmxak2ima
80RInskY8hRhSGTg0l+VYIH8cmjcUyqMSOELS5XfRH99r4QPiK8AguXg80T4VumY
W3Pf+zEC2ssgP/gYthV0g0Xj5m2QxktOF9tRw5nkg739ZR4dI9lm/iECgYEA2Dnf
uwEDGqHiQRF6/fh5BG/nGVMvrefkqx6WvTJQ3k/M/9WhxB+lr/8yH46TuS8N2b29
FoTf3Mr9T7pr/PWkOPzoY3P56nYbKU8xSwCim9xMzhBMzj8/N9ukJvXy27/VOz56
eQaKqnvdXNGtPJrIMDGHps2KKWlKLyAlapzjVTMCgYAA/W++tACv85g13EykfT4F
n0k4LbsGP9DP4zABQLIMyiY72eAncmRVjwrcW36XJ2xATOONTgx3gF3HjZzfaqNy
eD/6uNNllUTVEryXGmHgNHPL45VRnn6memCY2eFvZdXhM5W4y2PYaunY0MkDercA
+GTngbs6tBF88KOk04bYwQKBgFl68cRgsdkmnwwQYNaTKfmVGYzYaQXNzkqmWPko
xmCJo6tHzC7ubdG8iRCYHzfmahPuuj6EdGPZuSRyYFgJi5Ftz/nAN+84OxtIQ3zn
YWOgskQgaLh9YfsKsQ7Sf1NDOsnOnD5TX7UXl07fEpLe9vNCvAFiU8e5Y9LGudU5
4bYTAoGBAMdX3a3bXp4cZvXNBJ/QLVyxC6fP1Q4haCR1Od3m+T00Jth2IX2dk/fl
p6xiJT1av5JtYabv1dFKaXOS5s1kLGGuCCSKpkvFZm826aQ2AFm0XGqEQDLeei5b
A52Kpy/YJ+RkG4BTFtAooFq6DmA0cnoP6oPvG2h6XtDJwDTPInJb
-----END RSA PRIVATE KEY-----`
caContent = `-----BEGIN CERTIFICATE-----
MIIDbTCCAlWgAwIBAgIUBJvFoCowKich7MMfseJ+DYzzirowDQYJKoZIhvcNAQEM
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yMzAzMTExMzIxMDNaGA8yMTIz
MDIxNTEzMjEwM1owRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAO4to2YMYj0bxgr2FCiweSTSFuPx33zSw2x/s9Wf
OR41bm2DFsyYT5f3sOIKlXZEdLmOKty2e3ho3yC0EyNpVHdykkkHT3aDI17quZax
kYi/URqqtl1Z08A22txolc04hAZisg2BypGi3vql81UW1t3zyloGnJoIAeXR9uca
ljP6Bk3bwsxoVBLi1JtHrO0hHLQaeHmKhAyrys06X0LRdn7Px48yRZlt6FaLSa8X
YiRM0G44bVy/h6BkoQjMYGwVmCVk6zjJ9U7ZPFqdnDMNxAfR+hjDnYodqdLDMTTR
1NPVrnEnNwFx0AMLvgt/ba/45vZCEAmSZnFXFAJJcM7ai9ECAwEAAaNTMFEwHQYD
VR0OBBYEFHlvMPKZoZ3G0YE7JePJOP+8J38fMB8GA1UdIwQYMBaAFHlvMPKZoZ3G
0YE7JePJOP+8J38fMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggEB
AMX8dNulADOo9uQgBMyFb9TVra7iY0zZjzv4GY5XY7scd52n6CnfAPvYBBDnTr/O
BgNp5jaujb4+9u/2qhV3f9n+/3WOb2CmPehBgVSzlXqHeQ9lshmgwZPeem2T+8Tm
Nnc/xQnsUfCFszUDxpkr55+aLVM22j02RWqcZ4q7TAaVYL+kdFVMc8FoqG/0ro6A
BjE/Qn0Nn7ciX1VUjDt8l+k7ummPJTmzdi6i6E4AwO9dzrGNgGJ4aWL8cC6xYcIX
goVIRTFeONXSDno/oPjWHpIPt7L15heMpKBHNuzPkKx2YVqPHE5QZxWfS+Lzgx+Q
E2oTTM0rYKOZ8p6000mhvKI=
-----END CERTIFICATE-----`
)
func TestAccount(t *testing.T) {
endpoints := []string{
"192.168.0.2:2379",
"192.168.0.3:2379",
"192.168.0.4:2379",
}
username := "foo" + stringx.Rand()
password := "bar"
anotherPassword := "any"
_, ok := GetAccount(endpoints)
assert.False(t, ok)
AddAccount(endpoints, username, password)
account, ok := GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, username, account.User)
assert.Equal(t, password, account.Pass)
AddAccount(endpoints, username, anotherPassword)
account, ok = GetAccount(endpoints)
assert.True(t, ok)
assert.Equal(t, username, account.User)
assert.Equal(t, anotherPassword, account.Pass)
}
func TestTLSMethods(t *testing.T) {
certFile := createTempFile(t, []byte(certContent))
defer os.Remove(certFile)
keyFile := createTempFile(t, []byte(keyContent))
defer os.Remove(keyFile)
caFile := createTempFile(t, []byte(caContent))
defer os.Remove(caFile)
assert.NoError(t, AddTLS([]string{"foo"}, certFile, keyFile, caFile, false))
cfg, ok := GetTLS([]string{"foo"})
assert.True(t, ok)
assert.NotNil(t, cfg)
assert.Error(t, AddTLS([]string{"bar"}, "bad-file", keyFile, caFile, false))
assert.Error(t, AddTLS([]string{"bar"}, certFile, keyFile, "bad-file", false))
}
func createTempFile(t *testing.T, body []byte) string {
tmpFile, err := os.CreateTemp(os.TempDir(), "go-unit-*.tmp")
if err != nil {
t.Fatal(err)
}
tmpFile.Close()
if err = os.WriteFile(tmpFile.Name(), body, os.ModePerm); err != nil {
t.Fatal(err)
}
return tmpFile.Name()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/updatelistener_mock.go | core/discov/internal/updatelistener_mock.go | // Code generated by MockGen. DO NOT EDIT.
// Source: updatelistener.go
//
// Generated by this command:
//
// mockgen -package internal -destination updatelistener_mock.go -source updatelistener.go UpdateListener
//
// Package internal is a generated GoMock package.
package internal
import (
reflect "reflect"
gomock "go.uber.org/mock/gomock"
)
// MockUpdateListener is a mock of UpdateListener interface.
type MockUpdateListener struct {
ctrl *gomock.Controller
recorder *MockUpdateListenerMockRecorder
isgomock struct{}
}
// MockUpdateListenerMockRecorder is the mock recorder for MockUpdateListener.
type MockUpdateListenerMockRecorder struct {
mock *MockUpdateListener
}
// NewMockUpdateListener creates a new mock instance.
func NewMockUpdateListener(ctrl *gomock.Controller) *MockUpdateListener {
mock := &MockUpdateListener{ctrl: ctrl}
mock.recorder = &MockUpdateListenerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockUpdateListener) EXPECT() *MockUpdateListenerMockRecorder {
return m.recorder
}
// OnAdd mocks base method.
func (m *MockUpdateListener) OnAdd(kv KV) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "OnAdd", kv)
}
// OnAdd indicates an expected call of OnAdd.
func (mr *MockUpdateListenerMockRecorder) OnAdd(kv any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnAdd", reflect.TypeOf((*MockUpdateListener)(nil).OnAdd), kv)
}
// OnDelete mocks base method.
func (m *MockUpdateListener) OnDelete(kv KV) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "OnDelete", kv)
}
// OnDelete indicates an expected call of OnDelete.
func (mr *MockUpdateListenerMockRecorder) OnDelete(kv any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnDelete", reflect.TypeOf((*MockUpdateListener)(nil).OnDelete), kv)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/statewatcher_test.go | core/discov/internal/statewatcher_test.go | package internal
import (
"sync"
"testing"
"go.uber.org/mock/gomock"
"google.golang.org/grpc/connectivity"
)
func TestStateWatcher_watch(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
watcher := newStateWatcher()
var wg sync.WaitGroup
wg.Add(1)
watcher.addListener(func() {
wg.Done()
})
conn := NewMocketcdConn(ctrl)
conn.EXPECT().GetState().Return(connectivity.Ready)
conn.EXPECT().GetState().Return(connectivity.TransientFailure)
conn.EXPECT().GetState().Return(connectivity.Ready).AnyTimes()
conn.EXPECT().WaitForStateChange(gomock.Any(), gomock.Any()).Return(true).AnyTimes()
go watcher.watch(conn)
wg.Wait()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/etcdclient.go | core/discov/internal/etcdclient.go | //go:generate mockgen -package internal -destination etcdclient_mock.go -source etcdclient.go EtcdClient
package internal
import (
"context"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
)
// EtcdClient interface represents an etcd client.
type EtcdClient interface {
ActiveConnection() *grpc.ClientConn
Close() error
Ctx() context.Context
Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error)
Grant(ctx context.Context, ttl int64) (*clientv3.LeaseGrantResponse, error)
KeepAlive(ctx context.Context, id clientv3.LeaseID) (<-chan *clientv3.LeaseKeepAliveResponse, error)
Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error)
Revoke(ctx context.Context, id clientv3.LeaseID) (*clientv3.LeaseRevokeResponse, error)
Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/updatelistener.go | core/discov/internal/updatelistener.go | //go:generate mockgen -package internal -destination updatelistener_mock.go -source updatelistener.go UpdateListener
package internal
type (
// A KV is used to store an etcd entry with key and value.
KV struct {
Key string
Val string
}
// UpdateListener wraps the OnAdd and OnDelete methods.
// The implementation should be thread-safe and idempotent.
UpdateListener interface {
OnAdd(kv KV)
OnDelete(kv KV)
}
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/statewatcher.go | core/discov/internal/statewatcher.go | //go:generate mockgen -package internal -destination statewatcher_mock.go -source statewatcher.go etcdConn
package internal
import (
"context"
"sync"
"google.golang.org/grpc/connectivity"
)
type (
etcdConn interface {
GetState() connectivity.State
WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool
}
stateWatcher struct {
disconnected bool
currentState connectivity.State
listeners []func()
// lock only guards listeners, because only listens can be accessed by other goroutines.
lock sync.Mutex
}
)
func newStateWatcher() *stateWatcher {
return new(stateWatcher)
}
func (sw *stateWatcher) addListener(l func()) {
sw.lock.Lock()
sw.listeners = append(sw.listeners, l)
sw.lock.Unlock()
}
func (sw *stateWatcher) notifyListeners() {
sw.lock.Lock()
defer sw.lock.Unlock()
for _, l := range sw.listeners {
l()
}
}
func (sw *stateWatcher) updateState(conn etcdConn) {
sw.currentState = conn.GetState()
switch sw.currentState {
case connectivity.TransientFailure, connectivity.Shutdown:
sw.disconnected = true
case connectivity.Ready:
if sw.disconnected {
sw.disconnected = false
sw.notifyListeners()
}
}
}
func (sw *stateWatcher) watch(conn etcdConn) {
sw.currentState = conn.GetState()
for {
if conn.WaitForStateChange(context.Background(), sw.currentState) {
sw.updateState(conn)
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/vars.go | core/discov/internal/vars.go | package internal
import "time"
const (
// Delimiter is a separator that separates the etcd path.
Delimiter = '/'
autoSyncInterval = time.Minute
coolDownInterval = time.Second
dialTimeout = 5 * time.Second
requestTimeout = 3 * time.Second
endpointsSeparator = ","
)
var (
// DialTimeout is the dial timeout.
DialTimeout = dialTimeout
// RequestTimeout is the request timeout.
RequestTimeout = requestTimeout
// NewClient is used to create etcd clients.
NewClient = DialClient
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/statewatcher_mock.go | core/discov/internal/statewatcher_mock.go | // Code generated by MockGen. DO NOT EDIT.
// Source: statewatcher.go
//
// Generated by this command:
//
// mockgen -package internal -destination statewatcher_mock.go -source statewatcher.go etcdConn
//
// Package internal is a generated GoMock package.
package internal
import (
context "context"
reflect "reflect"
gomock "go.uber.org/mock/gomock"
connectivity "google.golang.org/grpc/connectivity"
)
// MocketcdConn is a mock of etcdConn interface.
type MocketcdConn struct {
ctrl *gomock.Controller
recorder *MocketcdConnMockRecorder
isgomock struct{}
}
// MocketcdConnMockRecorder is the mock recorder for MocketcdConn.
type MocketcdConnMockRecorder struct {
mock *MocketcdConn
}
// NewMocketcdConn creates a new mock instance.
func NewMocketcdConn(ctrl *gomock.Controller) *MocketcdConn {
mock := &MocketcdConn{ctrl: ctrl}
mock.recorder = &MocketcdConnMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MocketcdConn) EXPECT() *MocketcdConnMockRecorder {
return m.recorder
}
// GetState mocks base method.
func (m *MocketcdConn) GetState() connectivity.State {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetState")
ret0, _ := ret[0].(connectivity.State)
return ret0
}
// GetState indicates an expected call of GetState.
func (mr *MocketcdConnMockRecorder) GetState() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*MocketcdConn)(nil).GetState))
}
// WaitForStateChange mocks base method.
func (m *MocketcdConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WaitForStateChange", ctx, sourceState)
ret0, _ := ret[0].(bool)
return ret0
}
// WaitForStateChange indicates an expected call of WaitForStateChange.
func (mr *MocketcdConnMockRecorder) WaitForStateChange(ctx, sourceState any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForStateChange", reflect.TypeOf((*MocketcdConn)(nil).WaitForStateChange), ctx, sourceState)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/etcdclient_mock.go | core/discov/internal/etcdclient_mock.go | // Code generated by MockGen. DO NOT EDIT.
// Source: etcdclient.go
//
// Generated by this command:
//
// mockgen -package internal -destination etcdclient_mock.go -source etcdclient.go EtcdClient
//
// Package internal is a generated GoMock package.
package internal
import (
context "context"
reflect "reflect"
clientv3 "go.etcd.io/etcd/client/v3"
gomock "go.uber.org/mock/gomock"
grpc "google.golang.org/grpc"
)
// MockEtcdClient is a mock of EtcdClient interface.
type MockEtcdClient struct {
ctrl *gomock.Controller
recorder *MockEtcdClientMockRecorder
isgomock struct{}
}
// MockEtcdClientMockRecorder is the mock recorder for MockEtcdClient.
type MockEtcdClientMockRecorder struct {
mock *MockEtcdClient
}
// NewMockEtcdClient creates a new mock instance.
func NewMockEtcdClient(ctrl *gomock.Controller) *MockEtcdClient {
mock := &MockEtcdClient{ctrl: ctrl}
mock.recorder = &MockEtcdClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockEtcdClient) EXPECT() *MockEtcdClientMockRecorder {
return m.recorder
}
// ActiveConnection mocks base method.
func (m *MockEtcdClient) ActiveConnection() *grpc.ClientConn {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ActiveConnection")
ret0, _ := ret[0].(*grpc.ClientConn)
return ret0
}
// ActiveConnection indicates an expected call of ActiveConnection.
func (mr *MockEtcdClientMockRecorder) ActiveConnection() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ActiveConnection", reflect.TypeOf((*MockEtcdClient)(nil).ActiveConnection))
}
// Close mocks base method.
func (m *MockEtcdClient) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *MockEtcdClientMockRecorder) Close() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockEtcdClient)(nil).Close))
}
// Ctx mocks base method.
func (m *MockEtcdClient) Ctx() context.Context {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Ctx")
ret0, _ := ret[0].(context.Context)
return ret0
}
// Ctx indicates an expected call of Ctx.
func (mr *MockEtcdClientMockRecorder) Ctx() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ctx", reflect.TypeOf((*MockEtcdClient)(nil).Ctx))
}
// Get mocks base method.
func (m *MockEtcdClient) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) {
m.ctrl.T.Helper()
varargs := []any{ctx, key}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Get", varargs...)
ret0, _ := ret[0].(*clientv3.GetResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockEtcdClientMockRecorder) Get(ctx, key any, opts ...any) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, key}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockEtcdClient)(nil).Get), varargs...)
}
// Grant mocks base method.
func (m *MockEtcdClient) Grant(ctx context.Context, ttl int64) (*clientv3.LeaseGrantResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Grant", ctx, ttl)
ret0, _ := ret[0].(*clientv3.LeaseGrantResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Grant indicates an expected call of Grant.
func (mr *MockEtcdClientMockRecorder) Grant(ctx, ttl any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Grant", reflect.TypeOf((*MockEtcdClient)(nil).Grant), ctx, ttl)
}
// KeepAlive mocks base method.
func (m *MockEtcdClient) KeepAlive(ctx context.Context, id clientv3.LeaseID) (<-chan *clientv3.LeaseKeepAliveResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "KeepAlive", ctx, id)
ret0, _ := ret[0].(<-chan *clientv3.LeaseKeepAliveResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// KeepAlive indicates an expected call of KeepAlive.
func (mr *MockEtcdClientMockRecorder) KeepAlive(ctx, id any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KeepAlive", reflect.TypeOf((*MockEtcdClient)(nil).KeepAlive), ctx, id)
}
// Put mocks base method.
func (m *MockEtcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {
m.ctrl.T.Helper()
varargs := []any{ctx, key, val}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Put", varargs...)
ret0, _ := ret[0].(*clientv3.PutResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Put indicates an expected call of Put.
func (mr *MockEtcdClientMockRecorder) Put(ctx, key, val any, opts ...any) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, key, val}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockEtcdClient)(nil).Put), varargs...)
}
// Revoke mocks base method.
func (m *MockEtcdClient) Revoke(ctx context.Context, id clientv3.LeaseID) (*clientv3.LeaseRevokeResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Revoke", ctx, id)
ret0, _ := ret[0].(*clientv3.LeaseRevokeResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Revoke indicates an expected call of Revoke.
func (mr *MockEtcdClientMockRecorder) Revoke(ctx, id any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Revoke", reflect.TypeOf((*MockEtcdClient)(nil).Revoke), ctx, id)
}
// Watch mocks base method.
func (m *MockEtcdClient) Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan {
m.ctrl.T.Helper()
varargs := []any{ctx, key}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Watch", varargs...)
ret0, _ := ret[0].(clientv3.WatchChan)
return ret0
}
// Watch indicates an expected call of Watch.
func (mr *MockEtcdClientMockRecorder) Watch(ctx, key any, opts ...any) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, key}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockEtcdClient)(nil).Watch), varargs...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/registry_test.go | core/discov/internal/registry_test.go | package internal
import (
"context"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/contextx"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stringx"
"github.com/zeromicro/go-zero/core/threading"
"go.etcd.io/etcd/api/v3/etcdserverpb"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/mock/mockserver"
"go.uber.org/mock/gomock"
)
var mockLock sync.Mutex
func init() {
logx.Disable()
}
func setMockClient(cli EtcdClient) func() {
mockLock.Lock()
NewClient = func([]string) (EtcdClient, error) {
return cli, nil
}
return func() {
NewClient = DialClient
mockLock.Unlock()
}
}
func TestGetCluster(t *testing.T) {
AddAccount([]string{"first"}, "foo", "bar")
c1, _ := GetRegistry().getOrCreateCluster([]string{"first"})
c2, _ := GetRegistry().getOrCreateCluster([]string{"second"})
c3, _ := GetRegistry().getOrCreateCluster([]string{"first"})
assert.Equal(t, c1, c3)
assert.NotEqual(t, c1, c2)
}
func TestGetClusterKey(t *testing.T) {
assert.Equal(t, getClusterKey([]string{"localhost:1234", "remotehost:5678"}),
getClusterKey([]string{"remotehost:5678", "localhost:1234"}))
}
func TestUnmonitor(t *testing.T) {
t.Run("no listener", func(t *testing.T) {
reg := &Registry{
clusters: map[string]*cluster{},
}
assert.NotPanics(t, func() {
reg.Unmonitor([]string{"any"}, "any", false, nil)
})
})
t.Run("no value", func(t *testing.T) {
reg := &Registry{
clusters: map[string]*cluster{
"any": {
watchers: map[watchKey]*watchValue{
{
key: "any",
}: {
values: map[string]string{},
},
},
},
},
}
assert.NotPanics(t, func() {
reg.Unmonitor([]string{"any"}, "another", false, nil)
})
})
}
func TestCluster_HandleChanges(t *testing.T) {
ctrl := gomock.NewController(t)
l := NewMockUpdateListener(ctrl)
l.EXPECT().OnAdd(KV{
Key: "first",
Val: "1",
})
l.EXPECT().OnAdd(KV{
Key: "second",
Val: "2",
})
l.EXPECT().OnDelete(KV{
Key: "first",
Val: "1",
})
l.EXPECT().OnDelete(KV{
Key: "second",
Val: "2",
})
l.EXPECT().OnAdd(KV{
Key: "third",
Val: "3",
})
l.EXPECT().OnAdd(KV{
Key: "fourth",
Val: "4",
})
c := newCluster([]string{"any"})
key := watchKey{
key: "any",
exactMatch: false,
}
c.watchers[key] = &watchValue{
listeners: []UpdateListener{l},
}
c.handleChanges(key, []KV{
{
Key: "first",
Val: "1",
},
{
Key: "second",
Val: "2",
},
})
assert.EqualValues(t, map[string]string{
"first": "1",
"second": "2",
}, c.watchers[key].values)
c.handleChanges(key, []KV{
{
Key: "third",
Val: "3",
},
{
Key: "fourth",
Val: "4",
},
})
assert.EqualValues(t, map[string]string{
"third": "3",
"fourth": "4",
}, c.watchers[key].values)
}
func TestCluster_Load(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
cli.EXPECT().Get(gomock.Any(), "any/", gomock.Any()).Return(&clientv3.GetResponse{
Header: &etcdserverpb.ResponseHeader{},
Kvs: []*mvccpb.KeyValue{
{
Key: []byte("hello"),
Value: []byte("world"),
},
},
}, nil)
cli.EXPECT().Ctx().Return(context.Background())
c := &cluster{
watchers: make(map[watchKey]*watchValue),
}
c.load(cli, watchKey{
key: "any",
})
}
func TestCluster_Watch(t *testing.T) {
tests := []struct {
name string
method int
eventType mvccpb.Event_EventType
}{
{
name: "add",
eventType: clientv3.EventTypePut,
},
{
name: "delete",
eventType: clientv3.EventTypeDelete,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
ch := make(chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), "any/", gomock.Any()).Return(ch)
cli.EXPECT().Ctx().Return(context.Background())
var wg sync.WaitGroup
wg.Add(1)
c := &cluster{
watchers: make(map[watchKey]*watchValue),
}
key := watchKey{
key: "any",
}
listener := NewMockUpdateListener(ctrl)
c.watchers[key] = &watchValue{
listeners: []UpdateListener{listener},
values: make(map[string]string),
}
listener.EXPECT().OnAdd(gomock.Any()).Do(func(kv KV) {
assert.Equal(t, "hello", kv.Key)
assert.Equal(t, "world", kv.Val)
wg.Done()
}).MaxTimes(1)
listener.EXPECT().OnDelete(gomock.Any()).Do(func(_ any) {
wg.Done()
}).MaxTimes(1)
go c.watch(cli, key, 0)
ch <- clientv3.WatchResponse{
Events: []*clientv3.Event{
{
Type: test.eventType,
Kv: &mvccpb.KeyValue{
Key: []byte("hello"),
Value: []byte("world"),
},
},
},
}
wg.Wait()
})
}
}
func TestClusterWatch_RespFailures(t *testing.T) {
resps := []clientv3.WatchResponse{
{
Canceled: true,
},
{
// cause resp.Err() != nil
CompactRevision: 1,
},
}
for _, resp := range resps {
t.Run(stringx.Rand(), func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
ch := make(chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), "any/", gomock.Any()).Return(ch).AnyTimes()
cli.EXPECT().Ctx().Return(context.Background()).AnyTimes()
c := &cluster{
watchers: make(map[watchKey]*watchValue),
}
c.done = make(chan lang.PlaceholderType)
go func() {
ch <- resp
close(c.done)
}()
key := watchKey{
key: "any",
}
c.watch(cli, key, 0)
})
}
}
func TestCluster_getCurrent(t *testing.T) {
t.Run("no value", func(t *testing.T) {
c := &cluster{
watchers: map[watchKey]*watchValue{
{
key: "any",
}: {
values: map[string]string{},
},
},
}
assert.Nil(t, c.getCurrent(watchKey{
key: "another",
}))
})
}
func TestCluster_handleWatchEvents(t *testing.T) {
t.Run("no value", func(t *testing.T) {
c := &cluster{
watchers: map[watchKey]*watchValue{
{
key: "any",
}: {
values: map[string]string{},
},
},
}
assert.NotPanics(t, func() {
c.handleWatchEvents(context.Background(), watchKey{
key: "another",
}, nil)
})
})
}
func TestCluster_addListener(t *testing.T) {
t.Run("has listener", func(t *testing.T) {
c := &cluster{
watchers: map[watchKey]*watchValue{
{
key: "any",
}: {
listeners: make([]UpdateListener, 0),
},
},
}
assert.NotPanics(t, func() {
c.addListener(watchKey{
key: "any",
}, nil)
})
})
t.Run("no listener", func(t *testing.T) {
c := &cluster{
watchers: map[watchKey]*watchValue{
{
key: "any",
}: {
listeners: make([]UpdateListener, 0),
},
},
}
assert.NotPanics(t, func() {
c.addListener(watchKey{
key: "another",
}, nil)
})
})
}
func TestCluster_reload(t *testing.T) {
c := &cluster{
watchers: map[watchKey]*watchValue{},
watchGroup: threading.NewRoutineGroup(),
done: make(chan lang.PlaceholderType),
}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
assert.NotPanics(t, func() {
c.reload(cli)
})
}
func TestClusterWatch_CloseChan(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cli := NewMockEtcdClient(ctrl)
restore := setMockClient(cli)
defer restore()
ch := make(chan clientv3.WatchResponse)
cli.EXPECT().Watch(gomock.Any(), "any/", gomock.Any()).Return(ch).AnyTimes()
cli.EXPECT().Ctx().Return(context.Background()).AnyTimes()
c := &cluster{
watchers: make(map[watchKey]*watchValue),
}
c.done = make(chan lang.PlaceholderType)
go func() {
close(ch)
close(c.done)
}()
c.watch(cli, watchKey{
key: "any",
}, 0)
}
func TestValueOnlyContext(t *testing.T) {
ctx := contextx.ValueOnlyFrom(context.Background())
ctx.Done()
assert.Nil(t, ctx.Err())
}
func TestDialClient(t *testing.T) {
svr, err := mockserver.StartMockServers(1)
assert.NoError(t, err)
svr.StartAt(0)
certFile := createTempFile(t, []byte(certContent))
defer os.Remove(certFile)
keyFile := createTempFile(t, []byte(keyContent))
defer os.Remove(keyFile)
caFile := createTempFile(t, []byte(caContent))
defer os.Remove(caFile)
endpoints := []string{svr.Servers[0].Address}
AddAccount(endpoints, "foo", "bar")
assert.NoError(t, AddTLS(endpoints, certFile, keyFile, caFile, false))
old := DialTimeout
DialTimeout = time.Millisecond
defer func() {
DialTimeout = old
}()
_, err = DialClient(endpoints)
assert.Error(t, err)
}
func TestRegistry_Monitor(t *testing.T) {
svr, err := mockserver.StartMockServers(1)
assert.NoError(t, err)
svr.StartAt(0)
endpoints := []string{svr.Servers[0].Address}
GetRegistry().lock.Lock()
GetRegistry().clusters = map[string]*cluster{
getClusterKey(endpoints): {
watchers: map[watchKey]*watchValue{
{
key: "foo",
exactMatch: true,
}: {
values: map[string]string{
"bar": "baz",
},
},
},
},
}
GetRegistry().lock.Unlock()
assert.Error(t, GetRegistry().Monitor(endpoints, "foo", false, new(mockListener)))
}
func TestRegistry_Unmonitor(t *testing.T) {
svr, err := mockserver.StartMockServers(1)
assert.NoError(t, err)
svr.StartAt(0)
_, cancel := context.WithCancel(context.Background())
endpoints := []string{svr.Servers[0].Address}
GetRegistry().lock.Lock()
GetRegistry().clusters = map[string]*cluster{
getClusterKey(endpoints): {
watchers: map[watchKey]*watchValue{
{
key: "foo",
exactMatch: true,
}: {
values: map[string]string{
"bar": "baz",
},
cancel: cancel,
},
},
},
}
GetRegistry().lock.Unlock()
l := new(mockListener)
assert.NoError(t, GetRegistry().Monitor(endpoints, "foo", true, l))
watchVals := GetRegistry().clusters[getClusterKey(endpoints)].watchers[watchKey{
key: "foo",
exactMatch: true,
}]
assert.Equal(t, 1, len(watchVals.listeners))
GetRegistry().Unmonitor(endpoints, "foo", true, l)
watchVals = GetRegistry().clusters[getClusterKey(endpoints)].watchers[watchKey{
key: "foo",
exactMatch: true,
}]
assert.Nil(t, watchVals)
}
type mockListener struct {
}
func (m *mockListener) OnAdd(_ KV) {
}
func (m *mockListener) OnDelete(_ KV) {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/discov/internal/accountmanager.go | core/discov/internal/accountmanager.go | package internal
import (
"crypto/tls"
"crypto/x509"
"os"
"sync"
)
var (
accounts = make(map[string]Account)
tlsConfigs = make(map[string]*tls.Config)
lock sync.RWMutex
)
// Account holds the username/password for an etcd cluster.
type Account struct {
User string
Pass string
}
// AddAccount adds the username/password for the given etcd cluster.
func AddAccount(endpoints []string, user, pass string) {
lock.Lock()
defer lock.Unlock()
accounts[getClusterKey(endpoints)] = Account{
User: user,
Pass: pass,
}
}
// AddTLS adds the tls cert files for the given etcd cluster.
func AddTLS(endpoints []string, certFile, certKeyFile, caFile string, insecureSkipVerify bool) error {
cert, err := tls.LoadX509KeyPair(certFile, certKeyFile)
if err != nil {
return err
}
caData, err := os.ReadFile(caFile)
if err != nil {
return err
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caData)
lock.Lock()
defer lock.Unlock()
tlsConfigs[getClusterKey(endpoints)] = &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
InsecureSkipVerify: insecureSkipVerify,
}
return nil
}
// GetAccount gets the username/password for the given etcd cluster.
func GetAccount(endpoints []string) (Account, bool) {
lock.RLock()
defer lock.RUnlock()
account, ok := accounts[getClusterKey(endpoints)]
return account, ok
}
// GetTLS gets the tls config for the given etcd cluster.
func GetTLS(endpoints []string) (*tls.Config, bool) {
lock.RLock()
defer lock.RUnlock()
cfg, ok := tlsConfigs[getClusterKey(endpoints)]
return cfg, ok
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/goroutines.go | core/proc/goroutines.go | //go:build linux || darwin || freebsd
package proc
import (
"fmt"
"os"
"path"
"runtime/pprof"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
const (
goroutineProfile = "goroutine"
debugLevel = 2
)
type creator interface {
Create(name string) (file *os.File, err error)
}
func dumpGoroutines(ctor creator) {
command := path.Base(os.Args[0])
pid := syscall.Getpid()
dumpFile := path.Join(os.TempDir(), fmt.Sprintf("%s-%d-goroutines-%s.dump",
command, pid, time.Now().Format(timeFormat)))
logx.Infof("Got dump goroutine signal, printing goroutine profile to %s", dumpFile)
if f, err := ctor.Create(dumpFile); err != nil {
logx.Errorf("Failed to dump goroutine profile, error: %v", err)
} else {
defer f.Close()
pprof.Lookup(goroutineProfile).WriteTo(f, debugLevel)
}
}
type fileCreator struct{}
func (fc fileCreator) Create(name string) (file *os.File, err error) {
return os.Create(name)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/process_test.go | core/proc/process_test.go | package proc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestProcessName(t *testing.T) {
assert.True(t, len(ProcessName()) > 0)
}
func TestPid(t *testing.T) {
assert.True(t, Pid() > 0)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/profile.go | core/proc/profile.go | //go:build linux || darwin || freebsd
package proc
import (
"fmt"
"os"
"os/signal"
"path"
"runtime"
"runtime/pprof"
"runtime/trace"
"sync/atomic"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/runtime/#pkg-variables
const DefaultMemProfileRate = 4096
// started is non zero if a profile is running.
var started uint32
// Profile represents an active profiling session.
type Profile struct {
// closers holds cleanup functions that run after each profile
closers []func()
// stopped records if a call to profile.Stop has been made
stopped uint32
}
func (p *Profile) close() {
for _, closer := range p.closers {
closer()
}
}
func (p *Profile) startBlockProfile() {
fn := createDumpFile("block")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create block profile %q: %v", fn, err)
return
}
runtime.SetBlockProfileRate(1)
logx.Infof("profile: block profiling enabled, %s", fn)
p.closers = append(p.closers, func() {
pprof.Lookup("block").WriteTo(f, 0)
f.Close()
runtime.SetBlockProfileRate(0)
logx.Infof("profile: block profiling disabled, %s", fn)
})
}
func (p *Profile) startCpuProfile() {
fn := createDumpFile("cpu")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create cpu profile %q: %v", fn, err)
return
}
logx.Infof("profile: cpu profiling enabled, %s", fn)
pprof.StartCPUProfile(f)
p.closers = append(p.closers, func() {
pprof.StopCPUProfile()
f.Close()
logx.Infof("profile: cpu profiling disabled, %s", fn)
})
}
func (p *Profile) startMemProfile() {
fn := createDumpFile("mem")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create memory profile %q: %v", fn, err)
return
}
old := runtime.MemProfileRate
runtime.MemProfileRate = DefaultMemProfileRate
logx.Infof("profile: memory profiling enabled (rate %d), %s", runtime.MemProfileRate, fn)
p.closers = append(p.closers, func() {
pprof.Lookup("heap").WriteTo(f, 0)
f.Close()
runtime.MemProfileRate = old
logx.Infof("profile: memory profiling disabled, %s", fn)
})
}
func (p *Profile) startMutexProfile() {
fn := createDumpFile("mutex")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create mutex profile %q: %v", fn, err)
return
}
runtime.SetMutexProfileFraction(1)
logx.Infof("profile: mutex profiling enabled, %s", fn)
p.closers = append(p.closers, func() {
if mp := pprof.Lookup("mutex"); mp != nil {
mp.WriteTo(f, 0)
}
f.Close()
runtime.SetMutexProfileFraction(0)
logx.Infof("profile: mutex profiling disabled, %s", fn)
})
}
func (p *Profile) startThreadCreateProfile() {
fn := createDumpFile("threadcreate")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create threadcreate profile %q: %v", fn, err)
return
}
logx.Infof("profile: threadcreate profiling enabled, %s", fn)
p.closers = append(p.closers, func() {
if mp := pprof.Lookup("threadcreate"); mp != nil {
mp.WriteTo(f, 0)
}
f.Close()
logx.Infof("profile: threadcreate profiling disabled, %s", fn)
})
}
func (p *Profile) startTraceProfile() {
fn := createDumpFile("trace")
f, err := os.Create(fn)
if err != nil {
logx.Errorf("profile: could not create trace output file %q: %v", fn, err)
return
}
if err := trace.Start(f); err != nil {
logx.Errorf("profile: could not start trace: %v", err)
return
}
logx.Infof("profile: trace enabled, %s", fn)
p.closers = append(p.closers, func() {
trace.Stop()
logx.Infof("profile: trace disabled, %s", fn)
})
}
// Stop stops the profile and flushes any unwritten data.
func (p *Profile) Stop() {
if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
// someone has already called close
return
}
p.close()
atomic.StoreUint32(&started, 0)
}
// StartProfile starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func StartProfile() Stopper {
if !atomic.CompareAndSwapUint32(&started, 0, 1) {
logx.Error("profile: Start() already called")
return noopStopper
}
var prof Profile
prof.startCpuProfile()
prof.startMemProfile()
prof.startMutexProfile()
prof.startBlockProfile()
prof.startTraceProfile()
prof.startThreadCreateProfile()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
<-c
logx.Info("profile: caught interrupt, stopping profiles")
prof.Stop()
signal.Reset()
syscall.Kill(os.Getpid(), syscall.SIGINT)
}()
return &prof
}
func createDumpFile(kind string) string {
command := path.Base(os.Args[0])
pid := syscall.Getpid()
return path.Join(os.TempDir(), fmt.Sprintf("%s-%d-%s-%s.pprof",
command, pid, kind, time.Now().Format(timeFormat)))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/signals.go | core/proc/signals.go | //go:build linux || darwin || freebsd
package proc
import (
"os"
"os/signal"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
const (
profileDuration = time.Minute
timeFormat = "0102150405"
)
var done = make(chan struct{})
func init() {
go func() {
// https://golang.org/pkg/os/signal/#Notify
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTERM, syscall.SIGINT)
for {
v := <-signals
switch v {
case syscall.SIGUSR1:
dumpGoroutines(fileCreator{})
case syscall.SIGUSR2:
profiler := StartProfile()
time.AfterFunc(profileDuration, profiler.Stop)
case syscall.SIGTERM:
stopOnSignal()
gracefulStop(signals, syscall.SIGTERM)
case syscall.SIGINT:
stopOnSignal()
gracefulStop(signals, syscall.SIGINT)
default:
logx.Error("Got unregistered signal:", v)
}
}
}()
}
// Done returns the channel that notifies the process quitting.
func Done() <-chan struct{} {
return done
}
func stopOnSignal() {
select {
case <-done:
// already closed
default:
close(done)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/signals+polyfill.go | core/proc/signals+polyfill.go | //go:build windows
package proc
import "context"
func Done() <-chan struct{} {
return context.Background().Done()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/env_test.go | core/proc/env_test.go | package proc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestEnv(t *testing.T) {
assert.True(t, len(Env("any")) == 0)
envLock.RLock()
val, ok := envs["any"]
envLock.RUnlock()
assert.True(t, len(val) == 0)
assert.True(t, ok)
assert.True(t, len(Env("any")) == 0)
}
func TestEnvInt(t *testing.T) {
val, ok := EnvInt("any")
assert.Equal(t, 0, val)
assert.False(t, ok)
t.Setenv("anyInt", "10")
val, ok = EnvInt("anyInt")
assert.Equal(t, 10, val)
assert.True(t, ok)
t.Setenv("anyString", "a")
val, ok = EnvInt("anyString")
assert.Equal(t, 0, val)
assert.False(t, ok)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/shutdown+polyfill.go | core/proc/shutdown+polyfill.go | //go:build windows
package proc
import "time"
// ShutdownConf is empty on windows.
type ShutdownConf struct{}
// AddShutdownListener returns fn itself on windows, lets callers call fn on their own.
func AddShutdownListener(fn func()) func() {
return fn
}
// AddWrapUpListener returns fn itself on windows, lets callers call fn on their own.
func AddWrapUpListener(fn func()) func() {
return fn
}
// SetTimeToForceQuit does nothing on windows.
func SetTimeToForceQuit(duration time.Duration) {
}
// Setup does nothing on windows.
func Setup(conf ShutdownConf) {
}
// Shutdown does nothing on windows.
func Shutdown() {
}
// WrapUp does nothing on windows.
func WrapUp() {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/process.go | core/proc/process.go | package proc
import (
"os"
"path/filepath"
)
var (
procName string
pid int
)
func init() {
procName = filepath.Base(os.Args[0])
pid = os.Getpid()
}
// Pid returns pid of current process.
func Pid() int {
return pid
}
// ProcessName returns the processname, same as the command name.
func ProcessName() string {
return procName
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/stopper_test.go | core/proc/stopper_test.go | package proc
import "testing"
func TestNopStopper(t *testing.T) {
// no panic
noopStopper.Stop()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/env.go | core/proc/env.go | package proc
import (
"os"
"strconv"
"sync"
)
var (
envs = make(map[string]string)
envLock sync.RWMutex
)
// Env returns the value of the given environment variable.
func Env(name string) string {
envLock.RLock()
val, ok := envs[name]
envLock.RUnlock()
if ok {
return val
}
val = os.Getenv(name)
envLock.Lock()
envs[name] = val
envLock.Unlock()
return val
}
// EnvInt returns an int value of the given environment variable.
func EnvInt(name string) (int, bool) {
val := Env(name)
if len(val) == 0 {
return 0, false
}
n, err := strconv.Atoi(val)
if err != nil {
return 0, false
}
return n, true
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/profile_test.go | core/proc/profile_test.go | package proc
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestProfile(t *testing.T) {
c := logtest.NewCollector(t)
profiler := StartProfile()
// start again should not work
assert.NotNil(t, StartProfile())
profiler.Stop()
// stop twice
profiler.Stop()
assert.True(t, strings.Contains(c.String(), ".pprof"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/profile+polyfill.go | core/proc/profile+polyfill.go | //go:build windows
package proc
func StartProfile() Stopper {
return noopStopper
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/shutdown.go | core/proc/shutdown.go | //go:build linux || darwin || freebsd
package proc
import (
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/threading"
)
const (
// defaultWrapUpTime is the default time to wait before calling wrap up listeners.
defaultWrapUpTime = time.Second
// defaultWaitTime is the default time to wait before force quitting.
// why we use 5500 milliseconds is because most of our queues are blocking mode with 5 seconds
defaultWaitTime = 5500 * time.Millisecond
)
var (
wrapUpListeners = new(listenerManager)
shutdownListeners = new(listenerManager)
wrapUpTime = defaultWrapUpTime
waitTime = defaultWaitTime
shutdownLock sync.Mutex
)
// ShutdownConf defines the shutdown configuration for the process.
type ShutdownConf struct {
// WrapUpTime is the time to wait before calling shutdown listeners.
WrapUpTime time.Duration `json:",default=1s"`
// WaitTime is the time to wait before force quitting.
WaitTime time.Duration `json:",default=5.5s"`
}
// AddShutdownListener adds fn as a shutdown listener.
// The returned func can be used to wait for fn getting called.
func AddShutdownListener(fn func()) (waitForCalled func()) {
return shutdownListeners.addListener(fn)
}
// AddWrapUpListener adds fn as a wrap up listener.
// The returned func can be used to wait for fn getting called.
func AddWrapUpListener(fn func()) (waitForCalled func()) {
return wrapUpListeners.addListener(fn)
}
// SetTimeToForceQuit sets the waiting time before force quitting.
func SetTimeToForceQuit(duration time.Duration) {
shutdownLock.Lock()
defer shutdownLock.Unlock()
waitTime = duration
}
func Setup(conf ShutdownConf) {
shutdownLock.Lock()
defer shutdownLock.Unlock()
if conf.WrapUpTime > 0 {
wrapUpTime = conf.WrapUpTime
}
if conf.WaitTime > 0 {
waitTime = conf.WaitTime
}
}
// Shutdown calls the registered shutdown listeners, only for test purpose.
func Shutdown() {
shutdownListeners.notifyListeners()
}
// WrapUp wraps up the process, only for test purpose.
func WrapUp() {
wrapUpListeners.notifyListeners()
}
func gracefulStop(signals chan os.Signal, sig syscall.Signal) {
signal.Stop(signals)
logx.Infof("Got signal %d, shutting down...", sig)
go wrapUpListeners.notifyListeners()
time.Sleep(wrapUpTime)
go shutdownListeners.notifyListeners()
shutdownLock.Lock()
remainingTime := waitTime - wrapUpTime
shutdownLock.Unlock()
time.Sleep(remainingTime)
logx.Infof("Still alive after %v, going to force kill the process...", waitTime)
_ = syscall.Kill(syscall.Getpid(), sig)
}
type listenerManager struct {
lock sync.Mutex
waitGroup sync.WaitGroup
listeners []func()
}
func (lm *listenerManager) addListener(fn func()) (waitForCalled func()) {
lm.waitGroup.Add(1)
lm.lock.Lock()
lm.listeners = append(lm.listeners, func() {
defer lm.waitGroup.Done()
fn()
})
lm.lock.Unlock()
// we can return lm.waitGroup.Wait directly,
// but we want to make the returned func more readable.
// creating an extra closure would be negligible in practice.
return func() {
lm.waitGroup.Wait()
}
}
func (lm *listenerManager) notifyListeners() {
lm.lock.Lock()
defer lm.lock.Unlock()
group := threading.NewRoutineGroup()
for _, listener := range lm.listeners {
group.RunSafe(listener)
}
group.Wait()
lm.listeners = nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/stopper.go | core/proc/stopper.go | package proc
var noopStopper nilStopper
type (
// Stopper interface wraps the method Stop.
Stopper interface {
Stop()
}
nilStopper struct{}
)
func (ns nilStopper) Stop() {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/goroutines_test.go | core/proc/goroutines_test.go | //go:build linux || darwin || freebsd
package proc
import (
"errors"
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestDumpGoroutines(t *testing.T) {
t.Run("real file", func(t *testing.T) {
buf := logtest.NewCollector(t)
dumpGoroutines(fileCreator{})
assert.True(t, strings.Contains(buf.String(), ".dump"))
})
t.Run("fake file", func(t *testing.T) {
const msg = "any message"
buf := logtest.NewCollector(t)
err := errors.New(msg)
dumpGoroutines(fakeCreator{
file: &os.File{},
err: err,
})
assert.True(t, strings.Contains(buf.String(), msg))
})
}
type fakeCreator struct {
file *os.File
err error
}
func (fc fakeCreator) Create(_ string) (file *os.File, err error) {
return fc.file, fc.err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/shutdown_test.go | core/proc/shutdown_test.go | //go:build linux || darwin || freebsd
package proc
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestShutdown(t *testing.T) {
t.Cleanup(restoreSettings)
SetTimeToForceQuit(time.Hour)
shutdownLock.Lock()
assert.Equal(t, time.Hour, waitTime)
shutdownLock.Unlock()
var val int
called := AddWrapUpListener(func() {
val++
})
WrapUp()
called()
assert.Equal(t, 1, val)
called = AddShutdownListener(func() {
val += 2
})
Shutdown()
called()
assert.Equal(t, 3, val)
}
func TestShutdownWithMultipleServices(t *testing.T) {
t.Cleanup(restoreSettings)
SetTimeToForceQuit(time.Hour)
shutdownLock.Lock()
assert.Equal(t, time.Hour, waitTime)
shutdownLock.Unlock()
var val int32
called1 := AddShutdownListener(func() {
atomic.AddInt32(&val, 1)
})
called2 := AddShutdownListener(func() {
atomic.AddInt32(&val, 2)
})
Shutdown()
called1()
called2()
assert.Equal(t, int32(3), atomic.LoadInt32(&val))
}
func TestWrapUpWithMultipleServices(t *testing.T) {
t.Cleanup(restoreSettings)
SetTimeToForceQuit(time.Hour)
shutdownLock.Lock()
assert.Equal(t, time.Hour, waitTime)
shutdownLock.Unlock()
var val int32
called1 := AddWrapUpListener(func() {
atomic.AddInt32(&val, 1)
})
called2 := AddWrapUpListener(func() {
atomic.AddInt32(&val, 2)
})
WrapUp()
called1()
called2()
assert.Equal(t, int32(3), atomic.LoadInt32(&val))
}
func TestNotifyMoreThanOnce(t *testing.T) {
t.Cleanup(restoreSettings)
ch := make(chan struct{}, 1)
go func() {
var val int
called := AddWrapUpListener(func() {
val++
})
WrapUp()
WrapUp()
called()
assert.Equal(t, 1, val)
called = AddShutdownListener(func() {
val += 2
})
Shutdown()
Shutdown()
called()
assert.Equal(t, 3, val)
ch <- struct{}{}
}()
select {
case <-ch:
case <-time.After(time.Second):
t.Fatal("timeout, check error logs")
}
}
func TestSetup(t *testing.T) {
t.Run("valid time", func(t *testing.T) {
defer restoreSettings()
Setup(ShutdownConf{
WrapUpTime: time.Second * 2,
WaitTime: time.Second * 30,
})
shutdownLock.Lock()
assert.Equal(t, time.Second*2, wrapUpTime)
assert.Equal(t, time.Second*30, waitTime)
shutdownLock.Unlock()
})
t.Run("valid time", func(t *testing.T) {
defer restoreSettings()
Setup(ShutdownConf{})
shutdownLock.Lock()
assert.Equal(t, defaultWrapUpTime, wrapUpTime)
assert.Equal(t, defaultWaitTime, waitTime)
shutdownLock.Unlock()
})
}
func restoreSettings() {
shutdownLock.Lock()
defer shutdownLock.Unlock()
wrapUpTime = defaultWrapUpTime
waitTime = defaultWaitTime
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/proc/signals_test.go | core/proc/signals_test.go | //go:build linux || darwin || freebsd
package proc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDone(t *testing.T) {
select {
case <-Done():
assert.Fail(t, "should run")
default:
}
assert.NotNil(t, Done())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/metrics.go | core/stat/metrics.go | package stat
import (
"os"
"sync"
"time"
"github.com/zeromicro/go-zero/core/executors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
)
var (
logInterval = time.Minute
writerLock sync.Mutex
reportWriter Writer = nil
logEnabled = syncx.ForAtomicBool(true)
)
type (
// Writer interface wraps the Write method.
Writer interface {
Write(report *StatReport) error
}
// A StatReport is a stat report entry.
StatReport struct {
Name string `json:"name"`
Timestamp int64 `json:"tm"`
Pid int `json:"pid"`
ReqsPerSecond float32 `json:"qps"`
Drops int `json:"drops"`
Average float32 `json:"avg"`
Median float32 `json:"med"`
Top90th float32 `json:"t90"`
Top99th float32 `json:"t99"`
Top99p9th float32 `json:"t99p9"`
}
// A Metrics is used to log and report stat reports.
Metrics struct {
executor *executors.PeriodicalExecutor
container *metricsContainer
}
)
// DisableLog disables logs of stats.
func DisableLog() {
logEnabled.Set(false)
}
// SetReportWriter sets the report writer.
func SetReportWriter(writer Writer) {
writerLock.Lock()
reportWriter = writer
writerLock.Unlock()
}
// NewMetrics returns a Metrics.
func NewMetrics(name string) *Metrics {
container := &metricsContainer{
name: name,
pid: os.Getpid(),
}
return &Metrics{
executor: executors.NewPeriodicalExecutor(logInterval, container),
container: container,
}
}
// Add adds task to m.
func (m *Metrics) Add(task Task) {
m.executor.Add(task)
}
// AddDrop adds a drop to m.
func (m *Metrics) AddDrop() {
m.executor.Add(Task{
Drop: true,
})
}
// SetName sets the name of m.
func (m *Metrics) SetName(name string) {
m.executor.Sync(func() {
m.container.name = name
})
}
type (
tasksDurationPair struct {
tasks []Task
duration time.Duration
drops int
}
metricsContainer struct {
name string
pid int
tasks []Task
duration time.Duration
drops int
}
)
func (c *metricsContainer) AddTask(v any) bool {
if task, ok := v.(Task); ok {
if task.Drop {
c.drops++
} else {
c.tasks = append(c.tasks, task)
c.duration += task.Duration
}
}
return false
}
func (c *metricsContainer) Execute(v any) {
pair := v.(tasksDurationPair)
tasks := pair.tasks
duration := pair.duration
drops := pair.drops
size := len(tasks)
report := &StatReport{
Name: c.name,
Timestamp: time.Now().Unix(),
Pid: c.pid,
ReqsPerSecond: float32(size) / float32(logInterval/time.Second),
Drops: drops,
}
if size > 0 {
report.Average = float32(duration/time.Millisecond) / float32(size)
fiftyPercent := size >> 1
if fiftyPercent > 0 {
top50pTasks := topK(tasks, fiftyPercent)
medianTask := top50pTasks[0]
report.Median = float32(medianTask.Duration) / float32(time.Millisecond)
tenPercent := fiftyPercent / 5
if tenPercent > 0 {
top10pTasks := topK(top50pTasks, tenPercent)
task90th := top10pTasks[0]
report.Top90th = float32(task90th.Duration) / float32(time.Millisecond)
onePercent := tenPercent / 10
if onePercent > 0 {
top1pTasks := topK(top10pTasks, onePercent)
task99th := top1pTasks[0]
report.Top99th = float32(task99th.Duration) / float32(time.Millisecond)
pointOnePercent := onePercent / 10
if pointOnePercent > 0 {
topPointOneTasks := topK(top1pTasks, pointOnePercent)
task99Point9th := topPointOneTasks[0]
report.Top99p9th = float32(task99Point9th.Duration) / float32(time.Millisecond)
} else {
report.Top99p9th = getTopDuration(top1pTasks)
}
} else {
mostDuration := getTopDuration(top10pTasks)
report.Top99th = mostDuration
report.Top99p9th = mostDuration
}
} else {
mostDuration := getTopDuration(top50pTasks)
report.Top90th = mostDuration
report.Top99th = mostDuration
report.Top99p9th = mostDuration
}
} else {
mostDuration := getTopDuration(tasks)
report.Median = mostDuration
report.Top90th = mostDuration
report.Top99th = mostDuration
report.Top99p9th = mostDuration
}
}
log(report)
}
func (c *metricsContainer) RemoveAll() any {
tasks := c.tasks
duration := c.duration
drops := c.drops
c.tasks = nil
c.duration = 0
c.drops = 0
return tasksDurationPair{
tasks: tasks,
duration: duration,
drops: drops,
}
}
func getTopDuration(tasks []Task) float32 {
top := topK(tasks, 1)
if len(top) < 1 {
return 0
}
return float32(top[0].Duration) / float32(time.Millisecond)
}
func log(report *StatReport) {
writeReport(report)
if logEnabled.True() {
logx.Statf("(%s) - qps: %.1f/s, drops: %d, avg time: %.1fms, med: %.1fms, "+
"90th: %.1fms, 99th: %.1fms, 99.9th: %.1fms",
report.Name, report.ReqsPerSecond, report.Drops, report.Average, report.Median,
report.Top90th, report.Top99th, report.Top99p9th)
}
}
func writeReport(report *StatReport) {
writerLock.Lock()
defer writerLock.Unlock()
if reportWriter != nil {
if err := reportWriter.Write(report); err != nil {
logx.Error(err)
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/remotewriter.go | core/stat/remotewriter.go | package stat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
const (
httpTimeout = time.Second * 5
jsonContentType = "application/json; charset=utf-8"
)
// ErrWriteFailed is an error that indicates failed to submit a StatReport.
var ErrWriteFailed = errors.New("submit failed")
// A RemoteWriter is a writer to write StatReport.
type RemoteWriter struct {
endpoint string
}
// NewRemoteWriter returns a RemoteWriter.
func NewRemoteWriter(endpoint string) Writer {
return &RemoteWriter{
endpoint: endpoint,
}
}
func (rw *RemoteWriter) Write(report *StatReport) error {
bs, err := json.Marshal(report)
if err != nil {
return err
}
client := &http.Client{
Timeout: httpTimeout,
}
resp, err := client.Post(rw.endpoint, jsonContentType, bytes.NewReader(bs))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logx.Errorf("write report failed, code: %d, reason: %s", resp.StatusCode, resp.Status)
return ErrWriteFailed
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/usage_test.go | core/stat/usage_test.go | package stat
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
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) {
c := logtest.NewCollector(t)
printUsage()
output := c.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)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/topk.go | core/stat/topk.go | package stat
import "container/heap"
type taskHeap []Task
func (h *taskHeap) Len() int {
return len(*h)
}
func (h *taskHeap) Less(i, j int) bool {
return (*h)[i].Duration < (*h)[j].Duration
}
func (h *taskHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *taskHeap) Push(x any) {
*h = append(*h, x.(Task))
}
func (h *taskHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func topK(all []Task, k int) []Task {
h := new(taskHeap)
heap.Init(h)
for _, each := range all {
if h.Len() < k {
heap.Push(h, each)
} else if (*h)[0].Duration < each.Duration {
heap.Pop(h)
heap.Push(h, each)
}
}
return *h
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/topk_test.go | core/stat/topk_test.go | package stat
import (
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
const (
numSamples = 10000
topNum = 100
)
var samples []Task
func init() {
for i := 0; i < numSamples; i++ {
task := Task{
Duration: time.Duration(rand.Int63()),
}
samples = append(samples, task)
}
}
func TestTopK(t *testing.T) {
tasks := []Task{
{false, 1, "a"},
{false, 4, "a"},
{false, 2, "a"},
{false, 5, "a"},
{false, 9, "a"},
{false, 10, "a"},
{false, 12, "a"},
{false, 3, "a"},
{false, 6, "a"},
{false, 11, "a"},
{false, 8, "a"},
}
result := topK(tasks, 3)
if len(result) != 3 {
t.Fail()
}
set := make(map[time.Duration]struct{})
for _, each := range result {
set[each.Duration] = struct{}{}
}
for _, v := range []time.Duration{10, 11, 12} {
_, ok := set[v]
assert.True(t, ok)
}
}
func BenchmarkTopkHeap(b *testing.B) {
for i := 0; i < b.N; i++ {
topK(samples, topNum)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/alert_test.go | core/stat/alert_test.go | //go:build linux
package stat
import (
"strconv"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestReport(t *testing.T) {
t.Setenv(clusterNameKey, "test-cluster")
var count int32
SetReporter(func(s string) {
atomic.AddInt32(&count, 1)
})
for i := 0; i < 10; i++ {
Report(strconv.Itoa(i))
}
assert.Equal(t, int32(1), count)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/alert.go | core/stat/alert.go | //go:build linux
package stat
import (
"flag"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/executors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/sysx"
)
const (
clusterNameKey = "CLUSTER_NAME"
testEnv = "test.v"
)
var (
reporter = logx.Alert
lock sync.RWMutex
lessExecutor = executors.NewLessExecutor(time.Minute * 5)
dropped int32
clusterName = proc.Env(clusterNameKey)
)
func init() {
if flag.Lookup(testEnv) != nil {
SetReporter(nil)
}
}
// Report reports given message.
func Report(msg string) {
lock.RLock()
fn := reporter
lock.RUnlock()
if fn != nil {
reported := lessExecutor.DoOrDiscard(func() {
var builder strings.Builder
builder.WriteString(fmt.Sprintln(time.Now().Format(time.DateTime)))
if len(clusterName) > 0 {
builder.WriteString(fmt.Sprintf("cluster: %s\n", clusterName))
}
builder.WriteString(fmt.Sprintf("host: %s\n", sysx.Hostname()))
dp := atomic.SwapInt32(&dropped, 0)
if dp > 0 {
builder.WriteString(fmt.Sprintf("dropped: %d\n", dp))
}
builder.WriteString(strings.TrimSpace(msg))
fn(builder.String())
})
if !reported {
atomic.AddInt32(&dropped, 1)
}
}
}
// SetReporter sets the given reporter.
func SetReporter(fn func(string)) {
lock.Lock()
defer lock.Unlock()
reporter = fn
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/remotewriter_test.go | core/stat/remotewriter_test.go | package stat
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestRemoteWriter(t *testing.T) {
defer gock.Off()
gock.New("http://foo.com").Reply(200).BodyString("foo")
writer := NewRemoteWriter("http://foo.com")
err := writer.Write(&StatReport{
Name: "bar",
})
assert.Nil(t, err)
}
func TestRemoteWriterFail(t *testing.T) {
defer gock.Off()
gock.New("http://foo.com").Reply(503).BodyString("foo")
writer := NewRemoteWriter("http://foo.com")
err := writer.Write(&StatReport{
Name: "bar",
})
assert.NotNil(t, err)
}
func TestRemoteWriterError(t *testing.T) {
defer gock.Off()
gock.New("http://foo.com").ReplyError(errors.New("foo"))
writer := NewRemoteWriter("http://foo.com")
err := writer.Write(&StatReport{
Name: "bar",
})
assert.NotNil(t, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/task.go | core/stat/task.go | package stat
import "time"
// A Task is a task reported to Metrics.
type Task struct {
Drop bool
Duration time.Duration
Description string
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/usage.go | core/stat/usage.go | package stat
import (
"runtime/debug"
"runtime/metrics"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stat/internal"
"github.com/zeromicro/go-zero/core/threading"
)
const (
// 250ms and 0.95 as beta will count the average cpu load for past 5 seconds
cpuRefreshInterval = time.Millisecond * 250
allRefreshInterval = time.Minute
// moving average beta hyperparameter
beta = 0.95
)
var cpuUsage int64
func init() {
go func() {
cpuTicker := time.NewTicker(cpuRefreshInterval)
defer cpuTicker.Stop()
allTicker := time.NewTicker(allRefreshInterval)
defer allTicker.Stop()
for {
select {
case <-cpuTicker.C:
threading.RunSafe(func() {
curUsage := internal.RefreshCpu()
prevUsage := atomic.LoadInt64(&cpuUsage)
// cpu = cpuᵗ⁻¹ * beta + cpuᵗ * (1 - beta)
usage := int64(float64(prevUsage)*beta + float64(curUsage)*(1-beta))
atomic.StoreInt64(&cpuUsage, usage)
})
case <-allTicker.C:
if logEnabled.True() {
printUsage()
}
}
}
}()
}
// CpuUsage returns current cpu usage.
func CpuUsage() int64 {
return atomic.LoadInt64(&cpuUsage)
}
func bToMb(b uint64) float32 {
return float32(b) / 1024 / 1024
}
func printUsage() {
var (
alloc, totalAlloc, sys uint64
samples = []metrics.Sample{
{Name: "/memory/classes/heap/objects:bytes"},
{Name: "/gc/heap/allocs:bytes"},
{Name: "/memory/classes/total:bytes"},
}
stats debug.GCStats
)
metrics.Read(samples)
if samples[0].Value.Kind() == metrics.KindUint64 {
alloc = samples[0].Value.Uint64()
}
if samples[1].Value.Kind() == metrics.KindUint64 {
totalAlloc = samples[1].Value.Uint64()
}
if samples[2].Value.Kind() == metrics.KindUint64 {
sys = samples[2].Value.Uint64()
}
debug.ReadGCStats(&stats)
logx.Statf("CPU: %dm, MEMORY: Alloc=%.1fMi, TotalAlloc=%.1fMi, Sys=%.1fMi, NumGC=%d",
CpuUsage(), bToMb(alloc), bToMb(totalAlloc), bToMb(sys), stats.NumGC)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/alert+polyfill.go | core/stat/alert+polyfill.go | //go:build !linux
package stat
// Report reports given message.
func Report(string) {
}
// SetReporter sets the given reporter.
func SetReporter(func(string)) {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/metrics_test.go | core/stat/metrics_test.go | package stat
import (
"errors"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestMetrics(t *testing.T) {
DisableLog()
defer logEnabled.Set(true)
counts := []int{1, 5, 10, 100, 1000, 1000}
for _, count := range counts {
m := NewMetrics("foo")
m.SetName("bar")
for i := 0; i < count; i++ {
m.Add(Task{
Duration: time.Millisecond * time.Duration(i),
Description: strconv.Itoa(i),
})
}
m.AddDrop()
var writer mockedWriter
SetReportWriter(&writer)
m.executor.Flush()
assert.Equal(t, "bar", writer.report.Name)
}
}
func TestTopDurationWithEmpty(t *testing.T) {
assert.Equal(t, float32(0), getTopDuration(nil))
assert.Equal(t, float32(0), getTopDuration([]Task{}))
}
func TestLogAndReport(t *testing.T) {
buf := logtest.NewCollector(t)
old := logEnabled.True()
logEnabled.Set(true)
t.Cleanup(func() {
logEnabled.Set(old)
})
log(&StatReport{})
assert.NotEmpty(t, buf.String())
writerLock.Lock()
writer := reportWriter
writerLock.Unlock()
buf = logtest.NewCollector(t)
t.Cleanup(func() {
SetReportWriter(writer)
})
SetReportWriter(&badWriter{})
writeReport(&StatReport{})
assert.NotEmpty(t, buf.String())
}
type mockedWriter struct {
report *StatReport
}
func (m *mockedWriter) Write(report *StatReport) error {
m.report = report
return nil
}
type badWriter struct{}
func (b *badWriter) Write(_ *StatReport) error {
return errors.New("bad")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/internal/cpu_linux_test.go | core/stat/internal/cpu_linux_test.go | package internal
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRefreshCpu(t *testing.T) {
assert.NotPanics(t, func() {
RefreshCpu()
})
}
func BenchmarkRefreshCpu(b *testing.B) {
for i := 0; i < b.N; i++ {
RefreshCpu()
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/internal/cpu_linux.go | core/stat/internal/cpu_linux.go | package internal
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
)
const (
cpuTicks = 100
cpuFields = 8
cpuMax = 1000
statFile = "/proc/stat"
)
var (
preSystem uint64
preTotal uint64
limit float64
cores uint64
noCgroup bool
initOnce sync.Once
)
// RefreshCpu refreshes cpu usage and returns.
func RefreshCpu() uint64 {
initializeOnce()
if noCgroup {
return 0
}
total, err := cpuUsage()
if err != nil {
return 0
}
system, err := systemCpuUsage()
if err != nil {
return 0
}
var usage uint64
cpuDelta := total - preTotal
systemDelta := system - preSystem
if cpuDelta > 0 && systemDelta > 0 {
usage = uint64(float64(cpuDelta*cores*cpuMax) / (float64(systemDelta) * limit))
if usage > cpuMax {
usage = cpuMax
}
}
preSystem = system
preTotal = total
return usage
}
func cpuQuota() (float64, error) {
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuQuota()
}
func cpuUsage() (uint64, error) {
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuUsage()
}
func effectiveCpus() (int, error) {
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.effectiveCpus()
}
// if /proc not present, ignore the cpu calculation, like wsl linux
func initialize() error {
cpus, err := effectiveCpus()
if err != nil {
return err
}
cores = uint64(cpus)
limit = float64(cpus)
quota, err := cpuQuota()
if err == nil && quota > 0 {
if quota < limit {
limit = quota
}
}
preSystem, err = systemCpuUsage()
if err != nil {
return err
}
preTotal, err = cpuUsage()
return err
}
func initializeOnce() {
initOnce.Do(func() {
defer func() {
if p := recover(); p != nil {
noCgroup = true
logx.Error(p)
}
}()
if err := initialize(); err != nil {
noCgroup = true
logx.Error(err)
}
})
}
func systemCpuUsage() (uint64, error) {
lines, err := iox.ReadTextLines(statFile, iox.WithoutBlank())
if err != nil {
return 0, err
}
for _, line := range lines {
fields := strings.Fields(line)
if fields[0] == "cpu" {
if len(fields) < cpuFields {
return 0, fmt.Errorf("bad format of cpu stats")
}
var totalClockTicks uint64
for _, i := range fields[1:cpuFields] {
v, err := parseUint(i)
if err != nil {
return 0, err
}
totalClockTicks += v
}
return (totalClockTicks * uint64(time.Second)) / cpuTicks, nil
}
}
return 0, errors.New("bad stats format")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/internal/cpu_other.go | core/stat/internal/cpu_other.go | //go:build !linux
package internal
// RefreshCpu returns cpu usage, always returns 0 on systems other than linux.
func RefreshCpu() uint64 {
return 0
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stat/internal/cgroup_linux_test.go | core/stat/internal/cgroup_linux_test.go | package internal
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunningInUserNS(t *testing.T) {
// should be false in docker
assert.False(t, runningInUserNS())
}
func TestCgroups(t *testing.T) {
// test cgroup legacy(v1) & hybrid
if !isCgroup2UnifiedMode() {
cg, err := currentCgroupV1()
assert.NoError(t, err)
_, err = cg.effectiveCpus()
assert.NoError(t, err)
_, err = cg.cpuQuota()
assert.NoError(t, err)
_, err = cg.cpuUsage()
assert.NoError(t, err)
}
// test cgroup v2
if isCgroup2UnifiedMode() {
cg, err := currentCgroupV2()
assert.NoError(t, err)
_, err = cg.effectiveCpus()
assert.NoError(t, err)
_, err = cg.cpuQuota()
assert.Error(t, err)
_, err = cg.cpuUsage()
assert.NoError(t, err)
}
}
func TestParseUint(t *testing.T) {
tests := []struct {
input string
want uint64
err error
}{
{"0", 0, nil},
{"123", 123, nil},
{"-1", 0, nil},
{"-18446744073709551616", 0, nil},
{"foo", 0, fmt.Errorf("cgroup: bad int format: foo")},
}
for _, tt := range tests {
got, err := parseUint(tt.input)
assert.Equal(t, tt.err, err)
assert.Equal(t, tt.want, got)
}
}
func TestParseUints(t *testing.T) {
tests := []struct {
input string
want []uint64
err error
}{
{"", nil, nil},
{"1,2,3", []uint64{1, 2, 3}, nil},
{"1-3", []uint64{1, 2, 3}, nil},
{"1-3,5,7-9", []uint64{1, 2, 3, 5, 7, 8, 9}, nil},
{"foo", nil, fmt.Errorf("cgroup: bad int format: foo")},
{"1-bar", nil, fmt.Errorf("cgroup: bad int list format: 1-bar")},
{"bar-3", nil, fmt.Errorf("cgroup: bad int list format: bar-3")},
{"3-1", nil, fmt.Errorf("cgroup: bad int list format: 3-1")},
}
for _, tt := range tests {
got, err := parseUints(tt.input)
assert.Equal(t, tt.err, err)
assert.Equal(t, tt.want, got)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.