Compare commits
75 Commits
Author | SHA1 | Date | |
---|---|---|---|
f4d0237785 | |||
0f343dad0b | |||
7c29afba0b | |||
8159b9d233 | |||
45cdac5c29 | |||
98db0dc8bc | |||
453d2232bd | |||
9b387312da | |||
84024f7713 | |||
5a554f9f0c | |||
9c33cbc8e2 | |||
848fe1c0d4 | |||
6cbf23fec5 | |||
7462b0b53c | |||
cb743cee3f | |||
d18952951c | |||
|
f6b7f1b4bc | ||
|
33fa702104 | ||
4debc392d1 | |||
7137d99102 | |||
f76b3171d9 | |||
db3fc42204 | |||
f59023d741 | |||
6f17fd891a | |||
fd93308e8e | |||
2aaa0a74d8 | |||
ccbf23688b | |||
3bd6db79cb | |||
9347bb0651 | |||
0d63723ed3 | |||
a7f84e0baa | |||
c209892ce8 | |||
421842315f | |||
25350a6531 | |||
5e47cc7e8c | |||
1687b98b11 | |||
a81649d2a2 | |||
b48faa3b2b | |||
0be584ef0d | |||
26a2d18766 | |||
25a796fe4f | |||
d23de14769 | |||
2fb108519c | |||
c7ce238da3 | |||
|
67aa79f18a | ||
e6c3d734a3 | |||
1374e27531 | |||
1060f6a4c3 | |||
7d72ab05c6 | |||
42864ff1c6 | |||
49978b75c0 | |||
|
20770b6e30 | ||
b38c6106b2 | |||
|
138c4a0888 | ||
|
22f66fc258 | ||
18fafbbbab | |||
59c08c1d9a | |||
5fbb1a923e | |||
396387d1e8 | |||
|
4c2f12a419 | ||
b2abb86971 | |||
e546eef96c | |||
91701e7a45 | |||
817bf1f4d0 | |||
4120f79b55 | |||
d659db69ff | |||
416bb313fc | |||
ec43cfea6b | |||
|
60194fb42e | ||
|
945d9d16a5 | ||
1c0e5e1a85 | |||
33591e0bc9 | |||
|
75cbaf2612 | ||
f4aee3414b | |||
9f7b61eb17 |
2
.github/workflows/autoapprove.yml
vendored
2
.github/workflows/autoapprove.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: approve
|
||||
uses: hmarr/auto-approve-action@v2
|
||||
uses: hmarr/auto-approve-action@v3
|
||||
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
|
||||
id: approve
|
||||
with:
|
||||
|
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v3.2.0
|
||||
uses: golangci/golangci-lint-action@v3.4.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
|
2
.github/workflows/codecov.yml
vendored
2
.github/workflows/codecov.yml
vendored
@@ -36,4 +36,4 @@ jobs:
|
||||
- name: Run coverage
|
||||
run: go test -v -race -coverprofile=coverage.out -covermode=atomic ./...
|
||||
- name: codecov
|
||||
uses: codecov/codecov-action@v3.1.0
|
||||
uses: codecov/codecov-action@v3.1.1
|
||||
|
2
.github/workflows/dependabot-automerge.yml
vendored
2
.github/workflows/dependabot-automerge.yml
vendored
@@ -15,7 +15,7 @@ jobs:
|
||||
steps:
|
||||
- name: metadata
|
||||
id: metadata
|
||||
uses: dependabot/fetch-metadata@v1.3.1
|
||||
uses: dependabot/fetch-metadata@v1.3.6
|
||||
with:
|
||||
github-token: "${{ secrets.TOKEN }}"
|
||||
- name: merge
|
||||
|
2
.github/workflows/pr.yml
vendored
2
.github/workflows/pr.yml
vendored
@@ -34,7 +34,7 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v3.2.0
|
||||
uses: golangci/golangci-lint-action@v3.4.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
|
@@ -13,7 +13,7 @@ var (
|
||||
// DefaultClient is the global default client
|
||||
DefaultClient = NewClient()
|
||||
// DefaultContentType is the default content-type if not specified
|
||||
DefaultContentType = "application/json"
|
||||
DefaultContentType = ""
|
||||
// DefaultBackoff is the default backoff function for retries (minimum 10 millisecond and maximum 5 second)
|
||||
DefaultBackoff = BackoffInterval(10*time.Millisecond, 5*time.Second)
|
||||
// DefaultRetry is the default check-for-retry function for retries
|
||||
@@ -74,7 +74,7 @@ type Request interface {
|
||||
type Response interface {
|
||||
// Read the response
|
||||
Codec() codec.Codec
|
||||
// read the header
|
||||
// Header data
|
||||
Header() metadata.Metadata
|
||||
// Read the undecoded response
|
||||
Read() ([]byte, error)
|
||||
|
@@ -3,6 +3,7 @@ package client
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"go.unistack.org/micro/v3/broker"
|
||||
@@ -56,6 +57,8 @@ type Options struct {
|
||||
PoolSize int
|
||||
// PoolTTL connection pool ttl
|
||||
PoolTTL time.Duration
|
||||
// ContextDialer used to connect
|
||||
ContextDialer func(context.Context, string) (net.Conn, error)
|
||||
}
|
||||
|
||||
// NewCallOptions creates new call options struct
|
||||
@@ -95,10 +98,23 @@ type CallOptions struct {
|
||||
StreamTimeout time.Duration
|
||||
// RequestTimeout request timeout
|
||||
RequestTimeout time.Duration
|
||||
// RequestMetadata holds additional metadata for call
|
||||
RequestMetadata metadata.Metadata
|
||||
// ResponseMetadata holds additional metadata from call
|
||||
ResponseMetadata *metadata.Metadata
|
||||
// DialTimeout dial timeout
|
||||
DialTimeout time.Duration
|
||||
// Retries specifies retries num
|
||||
Retries int
|
||||
// ContextDialer used to connect
|
||||
ContextDialer func(context.Context, string) (net.Conn, error)
|
||||
}
|
||||
|
||||
// ContextDialer pass ContextDialer to client
|
||||
func ContextDialer(fn func(context.Context, string) (net.Conn, error)) Option {
|
||||
return func(o *Options) {
|
||||
o.ContextDialer = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Context pass context to client
|
||||
@@ -413,6 +429,13 @@ func PublishContext(ctx context.Context) PublishOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithContextDialer pass ContextDialer to client call
|
||||
func WithContextDialer(fn func(context.Context, string) (net.Conn, error)) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
o.ContextDialer = fn
|
||||
}
|
||||
}
|
||||
|
||||
// WithContentType specifies call content type
|
||||
func WithContentType(ct string) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
@@ -458,6 +481,20 @@ func WithRetries(i int) CallOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithResponseMetadata is a CallOption which adds metadata.Metadata to Options.CallOptions
|
||||
func WithResponseMetadata(md *metadata.Metadata) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
o.ResponseMetadata = md
|
||||
}
|
||||
}
|
||||
|
||||
// WithRequestMetadata is a CallOption which adds metadata.Metadata to Options.CallOptions
|
||||
func WithRequestMetadata(md metadata.Metadata) CallOption {
|
||||
return func(o *CallOptions) {
|
||||
o.RequestMetadata = md
|
||||
}
|
||||
}
|
||||
|
||||
// WithRequestTimeout is a CallOption which overrides that which
|
||||
// set in Options.CallOptions
|
||||
func WithRequestTimeout(d time.Duration) CallOption {
|
||||
|
@@ -106,6 +106,9 @@ func (c *noopCodec) Unmarshal(d []byte, v interface{}, opts ...Option) error {
|
||||
case *string:
|
||||
*ve = string(d)
|
||||
return nil
|
||||
case []byte:
|
||||
copy(ve, d)
|
||||
return nil
|
||||
case *[]byte:
|
||||
*ve = d
|
||||
return nil
|
||||
|
@@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNoopBytes(t *testing.T) {
|
||||
func TestNoopBytesPtr(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
rsp := make([]byte, len(req))
|
||||
|
||||
@@ -19,6 +19,20 @@ func TestNoopBytes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoopBytes(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
var rsp []byte
|
||||
|
||||
nc := NewCodec()
|
||||
if err := nc.Unmarshal(req, &rsp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(req, rsp) {
|
||||
t.Fatalf("req not eq rsp: %s != %s", req, rsp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoopString(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
var rsp string
|
||||
|
@@ -5,9 +5,11 @@ import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/imdario/mergo"
|
||||
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||
mtime "go.unistack.org/micro/v3/util/time"
|
||||
)
|
||||
|
||||
type defaultConfig struct {
|
||||
@@ -75,6 +77,7 @@ func fillValue(value reflect.Value, val string) error {
|
||||
if !rutil.IsEmpty(value) {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch value.Kind() {
|
||||
case reflect.Map:
|
||||
t := value.Type()
|
||||
@@ -151,11 +154,26 @@ func fillValue(value reflect.Value, val string) error {
|
||||
}
|
||||
value.Set(reflect.ValueOf(int32(v)))
|
||||
case reflect.Int64:
|
||||
v, err := strconv.ParseInt(val, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
switch {
|
||||
case value.Type().String() == "time.Duration" && value.Type().PkgPath() == "time":
|
||||
v, err := time.ParseDuration(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case value.Type().String() == "time.Duration" && value.Type().PkgPath() == "go.unistack.org/micro/v3/util/time":
|
||||
v, err := mtime.ParseDuration(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.SetInt(int64(v))
|
||||
default:
|
||||
v, err := strconv.ParseInt(val, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(v))
|
||||
}
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case reflect.Uint:
|
||||
v, err := strconv.ParseUint(val, 10, 0)
|
||||
if err != nil {
|
||||
|
@@ -4,15 +4,19 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.unistack.org/micro/v3/config"
|
||||
mtime "go.unistack.org/micro/v3/util/time"
|
||||
)
|
||||
|
||||
type cfg struct {
|
||||
StringValue string `default:"string_value"`
|
||||
IgnoreValue string `json:"-"`
|
||||
StructValue *cfgStructValue
|
||||
IntValue int `default:"99"`
|
||||
StringValue string `default:"string_value"`
|
||||
IgnoreValue string `json:"-"`
|
||||
StructValue *cfgStructValue
|
||||
IntValue int `default:"99"`
|
||||
DurationValue time.Duration `default:"10s"`
|
||||
MDurationValue mtime.Duration `default:"10s"`
|
||||
}
|
||||
|
||||
type cfgStructValue struct {
|
||||
|
@@ -7,6 +7,55 @@ import (
|
||||
"github.com/silas/dag"
|
||||
)
|
||||
|
||||
func TestDeps(t *testing.T) {
|
||||
d := &dag.AcyclicGraph{}
|
||||
|
||||
v0 := d.Add(&node{"v0"})
|
||||
v1 := d.Add(&node{"v1"})
|
||||
v2 := d.Add(&node{"v2"})
|
||||
v3 := d.Add(&node{"v3"})
|
||||
v4 := d.Add(&node{"v4"})
|
||||
|
||||
d.Connect(dag.BasicEdge(v0, v1))
|
||||
d.Connect(dag.BasicEdge(v1, v2))
|
||||
d.Connect(dag.BasicEdge(v2, v4))
|
||||
d.Connect(dag.BasicEdge(v0, v3))
|
||||
d.Connect(dag.BasicEdge(v3, v4))
|
||||
|
||||
if err := d.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d.TransitiveReduction()
|
||||
|
||||
var steps [][]string
|
||||
fn := func(n dag.Vertex, idx int) error {
|
||||
if idx == 0 {
|
||||
steps = make([][]string, 1)
|
||||
steps[0] = make([]string, 0, 1)
|
||||
} else if idx >= len(steps) {
|
||||
tsteps := make([][]string, idx+1)
|
||||
copy(tsteps, steps)
|
||||
steps = tsteps
|
||||
steps[idx] = make([]string, 0, 1)
|
||||
}
|
||||
steps[idx] = append(steps[idx], fmt.Sprintf("%s", n))
|
||||
return nil
|
||||
}
|
||||
|
||||
start := &node{"v0"}
|
||||
err := d.SortedDepthFirstWalk([]dag.Vertex{start}, fn)
|
||||
checkErr(t, err)
|
||||
|
||||
for idx, steps := range steps {
|
||||
fmt.Printf("level %d steps %#+v\n", idx, steps)
|
||||
}
|
||||
|
||||
if len(steps[2]) != 1 {
|
||||
t.Logf("invalid steps %#+v", steps[2])
|
||||
}
|
||||
}
|
||||
|
||||
func checkErr(t *testing.T, err error) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
@@ -3,7 +3,6 @@ package flow
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/silas/dag"
|
||||
@@ -150,17 +149,17 @@ func (w *microWorkflow) getSteps(start string, reverse bool) ([][]Step, error) {
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Abort(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, "workflows"+w.opts.Store.Options().Separator+id)
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusAborted.String())})
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Suspend(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, "workflows"+w.opts.Store.Options().Separator+id)
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusSuspend.String())})
|
||||
}
|
||||
|
||||
func (w *microWorkflow) Resume(ctx context.Context, id string) error {
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", id))
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, "workflows"+w.opts.Store.Options().Separator+id)
|
||||
return workflowStore.Write(ctx, "status", &codec.Frame{Data: []byte(StatusRunning.String())})
|
||||
}
|
||||
|
||||
@@ -181,8 +180,8 @@ func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...Execu
|
||||
return "", err
|
||||
}
|
||||
|
||||
stepStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("steps", eid))
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, filepath.Join("workflows", eid))
|
||||
stepStore := store.NewNamespaceStore(w.opts.Store, "steps"+w.opts.Store.Options().Separator+eid)
|
||||
workflowStore := store.NewNamespaceStore(w.opts.Store, "workflows"+w.opts.Store.Options().Separator+eid)
|
||||
|
||||
options := NewExecuteOptions(opts...)
|
||||
|
||||
@@ -219,7 +218,7 @@ func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...Execu
|
||||
for idx := range steps {
|
||||
for nidx := range steps[idx] {
|
||||
cstep := steps[idx][nidx]
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusPending.String())}); werr != nil {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusPending.String())}); werr != nil {
|
||||
return eid, werr
|
||||
}
|
||||
}
|
||||
@@ -246,32 +245,32 @@ func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...Execu
|
||||
wg.Add(1)
|
||||
go func(step Step) {
|
||||
defer wg.Done()
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "req"), req); werr != nil {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"req", req); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
rsp, serr := step.Execute(nctx, req, nopts...)
|
||||
if serr != nil {
|
||||
step.SetStatus(StatusFailure)
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "rsp"), serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"rsp", serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
cherr <- serr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "rsp"), rsp); werr != nil {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"rsp", rsp); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(step.ID(), "status"), &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
if werr := stepStore.Write(ctx, step.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
@@ -279,32 +278,32 @@ func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...Execu
|
||||
}(cstep)
|
||||
wg.Wait()
|
||||
} else {
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "req"), req); werr != nil {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"req", req); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusRunning.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
rsp, serr := cstep.Execute(nctx, req, nopts...)
|
||||
if serr != nil {
|
||||
cstep.SetStatus(StatusFailure)
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "rsp"), serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"rsp", serr); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusFailure.String())}); werr != nil && w.opts.Logger.V(logger.ErrorLevel) {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
}
|
||||
cherr <- serr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "rsp"), rsp); werr != nil {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"rsp", rsp); werr != nil {
|
||||
w.opts.Logger.Errorf(ctx, "store write error: %v", werr)
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
if werr := stepStore.Write(ctx, filepath.Join(cstep.ID(), "status"), &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
if werr := stepStore.Write(ctx, cstep.ID()+w.opts.Store.Options().Separator+"status", &codec.Frame{Data: []byte(StatusSuccess.String())}); werr != nil {
|
||||
cherr <- werr
|
||||
return
|
||||
}
|
||||
|
126
fsm/default.go
Normal file
126
fsm/default.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package fsm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type state struct {
|
||||
body interface{}
|
||||
name string
|
||||
}
|
||||
|
||||
var _ State = &state{}
|
||||
|
||||
func (s *state) Name() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func (s *state) Body() interface{} {
|
||||
return s.body
|
||||
}
|
||||
|
||||
// fsm is a finite state machine
|
||||
type fsm struct {
|
||||
statesMap map[string]StateFunc
|
||||
current string
|
||||
statesOrder []string
|
||||
opts Options
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewFSM creates a new finite state machine having the specified initial state
|
||||
// with specified options
|
||||
func NewFSM(opts ...Option) *fsm {
|
||||
return &fsm{
|
||||
statesMap: map[string]StateFunc{},
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
// Current returns the current state
|
||||
func (f *fsm) Current() string {
|
||||
f.mu.Lock()
|
||||
s := f.current
|
||||
f.mu.Unlock()
|
||||
return s
|
||||
}
|
||||
|
||||
// Current returns the current state
|
||||
func (f *fsm) Reset() {
|
||||
f.mu.Lock()
|
||||
f.current = f.opts.Initial
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// State adds state to fsm
|
||||
func (f *fsm) State(state string, fn StateFunc) {
|
||||
f.mu.Lock()
|
||||
f.statesMap[state] = fn
|
||||
f.statesOrder = append(f.statesOrder, state)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// Start runs state machine with provided data
|
||||
func (f *fsm) Start(ctx context.Context, args interface{}, opts ...Option) (interface{}, error) {
|
||||
var err error
|
||||
|
||||
f.mu.Lock()
|
||||
options := f.opts
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
sopts := []StateOption{StateDryRun(options.DryRun)}
|
||||
|
||||
cstate := options.Initial
|
||||
states := make(map[string]StateFunc, len(f.statesMap))
|
||||
for k, v := range f.statesMap {
|
||||
states[k] = v
|
||||
}
|
||||
f.current = cstate
|
||||
f.mu.Unlock()
|
||||
|
||||
var s State
|
||||
s = &state{name: cstate, body: args}
|
||||
nstate := s.Name()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
fn, ok := states[nstate]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf(`state "%s" %w`, nstate, ErrInvalidState)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.current = nstate
|
||||
f.mu.Unlock()
|
||||
|
||||
// wrap the handler func
|
||||
for i := len(options.Wrappers); i > 0; i-- {
|
||||
fn = options.Wrappers[i-1](fn)
|
||||
}
|
||||
|
||||
s, err = fn(ctx, s, sopts...)
|
||||
|
||||
switch {
|
||||
case err != nil:
|
||||
return s.Body(), err
|
||||
case s.Name() == StateEnd:
|
||||
return s.Body(), nil
|
||||
case s.Name() == "":
|
||||
for idx := range f.statesOrder {
|
||||
if f.statesOrder[idx] == nstate && len(f.statesOrder) > idx+1 {
|
||||
nstate = f.statesOrder[idx+1]
|
||||
}
|
||||
}
|
||||
default:
|
||||
nstate = s.Name()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
174
fsm/fsm.go
174
fsm/fsm.go
@@ -3,8 +3,6 @@ package fsm // import "go.unistack.org/micro/v3/fsm"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -12,170 +10,20 @@ var (
|
||||
StateEnd = "end"
|
||||
)
|
||||
|
||||
// Options struct holding fsm options
|
||||
type Options struct {
|
||||
// DryRun mode
|
||||
DryRun bool
|
||||
// Initial state
|
||||
Initial string
|
||||
// HooksBefore func slice runs in order before state
|
||||
HooksBefore []HookBeforeFunc
|
||||
// HooksAfter func slice runs in order after state
|
||||
HooksAfter []HookAfterFunc
|
||||
type State interface {
|
||||
Name() string
|
||||
Body() interface{}
|
||||
}
|
||||
|
||||
// HookBeforeFunc func signature
|
||||
type HookBeforeFunc func(ctx context.Context, state string, args interface{})
|
||||
|
||||
// HookAfterFunc func signature
|
||||
type HookAfterFunc func(ctx context.Context, state string, args interface{})
|
||||
|
||||
// Option func signature
|
||||
type Option func(*Options)
|
||||
|
||||
// StateOptions holds state options
|
||||
type StateOptions struct {
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// StateDryRun says that state executes in dry run mode
|
||||
func StateDryRun(b bool) StateOption {
|
||||
return func(o *StateOptions) {
|
||||
o.DryRun = b
|
||||
}
|
||||
}
|
||||
|
||||
// StateOption func signature
|
||||
type StateOption func(*StateOptions)
|
||||
|
||||
// InitialState sets init state for state machine
|
||||
func InitialState(initial string) Option {
|
||||
return func(o *Options) {
|
||||
o.Initial = initial
|
||||
}
|
||||
}
|
||||
|
||||
// HookBefore provides hook func slice
|
||||
func HookBefore(fns ...HookBeforeFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.HooksBefore = fns
|
||||
}
|
||||
}
|
||||
|
||||
// HookAfter provides hook func slice
|
||||
func HookAfter(fns ...HookAfterFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.HooksAfter = fns
|
||||
}
|
||||
}
|
||||
// StateWrapper wraps the StateFunc and returns the equivalent
|
||||
type StateWrapper func(StateFunc) StateFunc
|
||||
|
||||
// StateFunc called on state transition and return next step and error
|
||||
type StateFunc func(ctx context.Context, args interface{}, opts ...StateOption) (string, interface{}, error)
|
||||
type StateFunc func(ctx context.Context, state State, opts ...StateOption) (State, error)
|
||||
|
||||
// FSM is a finite state machine
|
||||
type FSM struct {
|
||||
mu sync.Mutex
|
||||
statesMap map[string]StateFunc
|
||||
statesOrder []string
|
||||
opts *Options
|
||||
current string
|
||||
}
|
||||
|
||||
// New creates a new finite state machine having the specified initial state
|
||||
// with specified options
|
||||
func New(opts ...Option) *FSM {
|
||||
options := &Options{}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
return &FSM{
|
||||
statesMap: map[string]StateFunc{},
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
// Current returns the current state
|
||||
func (f *FSM) Current() string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.current
|
||||
}
|
||||
|
||||
// Current returns the current state
|
||||
func (f *FSM) Reset() {
|
||||
f.mu.Lock()
|
||||
f.current = f.opts.Initial
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// State adds state to fsm
|
||||
func (f *FSM) State(state string, fn StateFunc) {
|
||||
f.mu.Lock()
|
||||
f.statesMap[state] = fn
|
||||
f.statesOrder = append(f.statesOrder, state)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// Init initialize fsm and check states
|
||||
|
||||
// Start runs state machine with provided data
|
||||
func (f *FSM) Start(ctx context.Context, args interface{}, opts ...Option) (interface{}, error) {
|
||||
var err error
|
||||
var ok bool
|
||||
var fn StateFunc
|
||||
var nstate string
|
||||
|
||||
f.mu.Lock()
|
||||
options := f.opts
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
sopts := []StateOption{StateDryRun(options.DryRun)}
|
||||
|
||||
cstate := options.Initial
|
||||
states := make(map[string]StateFunc, len(f.statesMap))
|
||||
for k, v := range f.statesMap {
|
||||
states[k] = v
|
||||
}
|
||||
f.current = cstate
|
||||
f.mu.Unlock()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
fn, ok = states[cstate]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf(`state "%s" %w`, cstate, ErrInvalidState)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.current = cstate
|
||||
f.mu.Unlock()
|
||||
for _, fn := range options.HooksBefore {
|
||||
fn(ctx, cstate, args)
|
||||
}
|
||||
nstate, args, err = fn(ctx, args, sopts...)
|
||||
for _, fn := range options.HooksAfter {
|
||||
fn(ctx, cstate, args)
|
||||
}
|
||||
switch {
|
||||
case err != nil:
|
||||
return args, err
|
||||
case nstate == StateEnd:
|
||||
return args, nil
|
||||
case nstate == "":
|
||||
for idx := range f.statesOrder {
|
||||
if f.statesOrder[idx] == cstate && len(f.statesOrder) > idx+1 {
|
||||
nstate = f.statesOrder[idx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
cstate = nstate
|
||||
}
|
||||
}
|
||||
type FSM interface {
|
||||
Start(context.Context, interface{}, ...Option) (interface{}, error)
|
||||
Current() string
|
||||
Reset()
|
||||
State(string, StateFunc)
|
||||
}
|
||||
|
@@ -1,63 +1,72 @@
|
||||
package fsm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
)
|
||||
|
||||
func TestFSMStart(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
pfb := func(_ context.Context, state string, _ interface{}) {
|
||||
fmt.Fprintf(buf, "before state %s\n", state)
|
||||
|
||||
if err := logger.DefaultLogger.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pfa := func(_ context.Context, state string, _ interface{}) {
|
||||
fmt.Fprintf(buf, "after state %s\n", state)
|
||||
|
||||
wrapper := func(next StateFunc) StateFunc {
|
||||
return func(sctx context.Context, s State, opts ...StateOption) (State, error) {
|
||||
sctx = logger.NewContext(sctx, logger.Fields("state", s.Name()))
|
||||
return next(sctx, s, opts...)
|
||||
}
|
||||
}
|
||||
f := New(InitialState("1"), HookBefore(pfb), HookAfter(pfa))
|
||||
f1 := func(_ context.Context, req interface{}, _ ...StateOption) (string, interface{}, error) {
|
||||
args := req.(map[string]interface{})
|
||||
|
||||
f := NewFSM(InitialState("1"), WrapState(wrapper))
|
||||
f1 := func(sctx context.Context, s State, opts ...StateOption) (State, error) {
|
||||
_, ok := logger.FromContext(sctx)
|
||||
if !ok {
|
||||
t.Fatal("f1 context does not have logger")
|
||||
}
|
||||
args := s.Body().(map[string]interface{})
|
||||
if v, ok := args["request"].(string); !ok || v == "" {
|
||||
return "", nil, fmt.Errorf("empty request")
|
||||
return nil, fmt.Errorf("empty request")
|
||||
}
|
||||
return "2", map[string]interface{}{"response": "test2"}, nil
|
||||
return &state{name: "", body: map[string]interface{}{"response": "state1"}}, nil
|
||||
}
|
||||
f2 := func(_ context.Context, req interface{}, _ ...StateOption) (string, interface{}, error) {
|
||||
args := req.(map[string]interface{})
|
||||
if v, ok := args["response"].(string); !ok || v == "" {
|
||||
return "", nil, fmt.Errorf("empty response")
|
||||
f2 := func(sctx context.Context, s State, opts ...StateOption) (State, error) {
|
||||
_, ok := logger.FromContext(sctx)
|
||||
if !ok {
|
||||
t.Fatal("f2 context does not have logger")
|
||||
}
|
||||
return "", map[string]interface{}{"response": "test"}, nil
|
||||
args := s.Body().(map[string]interface{})
|
||||
if v, ok := args["response"].(string); !ok || v == "" {
|
||||
return nil, fmt.Errorf("empty response")
|
||||
}
|
||||
return &state{name: "", body: map[string]interface{}{"response": "state2"}}, nil
|
||||
}
|
||||
f3 := func(_ context.Context, req interface{}, _ ...StateOption) (string, interface{}, error) {
|
||||
args := req.(map[string]interface{})
|
||||
if v, ok := args["response"].(string); !ok || v == "" {
|
||||
return "", nil, fmt.Errorf("empty response")
|
||||
f3 := func(sctx context.Context, s State, opts ...StateOption) (State, error) {
|
||||
_, ok := logger.FromContext(sctx)
|
||||
if !ok {
|
||||
t.Fatal("f3 context does not have logger")
|
||||
}
|
||||
return StateEnd, map[string]interface{}{"response": "test_last"}, nil
|
||||
args := s.Body().(map[string]interface{})
|
||||
if v, ok := args["response"].(string); !ok || v == "" {
|
||||
return nil, fmt.Errorf("empty response")
|
||||
}
|
||||
return &state{name: StateEnd, body: map[string]interface{}{"response": "state3"}}, nil
|
||||
}
|
||||
f.State("1", f1)
|
||||
f.State("2", f2)
|
||||
f.State("3", f3)
|
||||
rsp, err := f.Start(ctx, map[string]interface{}{"request": "test1"})
|
||||
rsp, err := f.Start(ctx, map[string]interface{}{"request": "state"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := rsp.(map[string]interface{})
|
||||
if v, ok := args["response"].(string); !ok || v == "" {
|
||||
t.Fatalf("nil rsp: %#+v", args)
|
||||
} else if v != "test_last" {
|
||||
} else if v != "state3" {
|
||||
t.Fatalf("invalid rsp %#+v", args)
|
||||
}
|
||||
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`before state 1`)) ||
|
||||
!bytes.Contains(buf.Bytes(), []byte(`before state 2`)) ||
|
||||
!bytes.Contains(buf.Bytes(), []byte(`after state 1`)) ||
|
||||
!bytes.Contains(buf.Bytes(), []byte(`after state 2`)) ||
|
||||
!bytes.Contains(buf.Bytes(), []byte(`after state 3`)) ||
|
||||
!bytes.Contains(buf.Bytes(), []byte(`after state 3`)) {
|
||||
t.Fatalf("fsm not works properly or hooks error, buf: %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
52
fsm/options.go
Normal file
52
fsm/options.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package fsm
|
||||
|
||||
// Options struct holding fsm options
|
||||
type Options struct {
|
||||
// Initial state
|
||||
Initial string
|
||||
// Wrappers runs before state
|
||||
Wrappers []StateWrapper
|
||||
// DryRun mode
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(*Options)
|
||||
|
||||
// StateOptions holds state options
|
||||
type StateOptions struct {
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// StateDryRun says that state executes in dry run mode
|
||||
func StateDryRun(b bool) StateOption {
|
||||
return func(o *StateOptions) {
|
||||
o.DryRun = b
|
||||
}
|
||||
}
|
||||
|
||||
// StateOption func signature
|
||||
type StateOption func(*StateOptions)
|
||||
|
||||
// InitialState sets init state for state machine
|
||||
func InitialState(initial string) Option {
|
||||
return func(o *Options) {
|
||||
o.Initial = initial
|
||||
}
|
||||
}
|
||||
|
||||
// WrapState adds a state Wrapper to a list of options passed into the fsm
|
||||
func WrapState(w StateWrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Wrappers = append(o.Wrappers, w)
|
||||
}
|
||||
}
|
||||
|
||||
// NewOptions returns new Options struct filled by passed Option
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
4
go.mod
4
go.mod
@@ -3,13 +3,11 @@ module go.unistack.org/micro/v3
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/google/gnostic v0.6.8 // indirect
|
||||
github.com/google/go-cmp v0.5.7 // indirect
|
||||
github.com/imdario/mergo v0.3.13
|
||||
github.com/kr/pretty v0.2.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/silas/dag v0.0.0-20211117232152-9d50aa809f35
|
||||
go.unistack.org/micro-proto/v3 v3.2.7
|
||||
google.golang.org/protobuf v1.28.0 // indirect
|
||||
go.unistack.org/micro-proto/v3 v3.3.1
|
||||
)
|
||||
|
13
go.sum
13
go.sum
@@ -38,9 +38,8 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/gnostic v0.6.6/go.mod h1:Nm8234We1lq6iB9OmlgNv3nH91XLLVZHCDayfA3xq+E=
|
||||
github.com/google/gnostic v0.6.8 h1:bT56GPYBWh1tvBuBEd94qcS3+60b+y0HQur0ITkGuCk=
|
||||
github.com/google/gnostic v0.6.8/go.mod h1:Nm8234We1lq6iB9OmlgNv3nH91XLLVZHCDayfA3xq+E=
|
||||
github.com/google/gnostic v0.6.9 h1:ZK/5VhkoX835RikCHpSUJV9a+S3e1zLh59YnyWeBW+0=
|
||||
github.com/google/gnostic v0.6.9/go.mod h1:Nm8234We1lq6iB9OmlgNv3nH91XLLVZHCDayfA3xq+E=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
@@ -76,8 +75,8 @@ github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.unistack.org/micro-proto/v3 v3.2.7 h1:zG6d69kHc+oij2lwQ3AfrCgdjiEVRG2A7TlsxjusWs4=
|
||||
go.unistack.org/micro-proto/v3 v3.2.7/go.mod h1:ZltVWNECD5yK+40+OCONzGw4OtmSdTpVi8/KFgo9dqM=
|
||||
go.unistack.org/micro-proto/v3 v3.3.1 h1:nQ0MtWvP2G3QrpOgawVOPhpZZYkq6umTGDqs8FxJYIo=
|
||||
go.unistack.org/micro-proto/v3 v3.3.1/go.mod h1:cwRyv8uInM2I7EbU7O8Fx2Ls3N90Uw9UCCcq4olOdfE=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
@@ -146,8 +145,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
|
||||
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
|
||||
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
@@ -12,10 +12,8 @@ import (
|
||||
)
|
||||
|
||||
type defaultLogger struct {
|
||||
enc *json.Encoder
|
||||
logFunc LogFunc
|
||||
logfFunc LogfFunc
|
||||
opts Options
|
||||
enc *json.Encoder
|
||||
opts Options
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
@@ -27,10 +25,6 @@ func (l *defaultLogger) Init(opts ...Option) error {
|
||||
}
|
||||
l.enc = json.NewEncoder(l.opts.Out)
|
||||
// wrap the Log func
|
||||
for i := len(l.opts.Wrappers); i > 0; i-- {
|
||||
l.logFunc = l.opts.Wrappers[i-1].Log(l.logFunc)
|
||||
l.logfFunc = l.opts.Wrappers[i-1].Logf(l.logfFunc)
|
||||
}
|
||||
l.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -47,17 +41,10 @@ func (l *defaultLogger) Clone(opts ...Option) Logger {
|
||||
o(&oldopts)
|
||||
}
|
||||
|
||||
oldopts.Wrappers = newopts.Wrappers
|
||||
l.Lock()
|
||||
cl := &defaultLogger{opts: oldopts, logFunc: l.logFunc, logfFunc: l.logfFunc}
|
||||
cl := &defaultLogger{opts: oldopts, enc: json.NewEncoder(l.opts.Out)}
|
||||
l.Unlock()
|
||||
|
||||
// wrap the Log func
|
||||
for i := len(newopts.Wrappers); i > 0; i-- {
|
||||
cl.logFunc = newopts.Wrappers[i-1].Log(cl.logFunc)
|
||||
cl.logfFunc = newopts.Wrappers[i-1].Logf(cl.logfFunc)
|
||||
}
|
||||
|
||||
return cl
|
||||
}
|
||||
|
||||
@@ -75,15 +62,17 @@ func (l *defaultLogger) Level(level Level) {
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Fields(fields ...interface{}) Logger {
|
||||
l.RLock()
|
||||
nl := &defaultLogger{opts: l.opts, enc: l.enc}
|
||||
if len(fields) == 0 {
|
||||
l.RUnlock()
|
||||
return nl
|
||||
} else if len(fields)%2 != 0 {
|
||||
fields = fields[:len(fields)-1]
|
||||
}
|
||||
nl.logFunc = l.logFunc
|
||||
nl.logfFunc = l.logfFunc
|
||||
nl.opts.Fields = copyFields(l.opts.Fields)
|
||||
nl.opts.Fields = append(nl.opts.Fields, fields...)
|
||||
l.RUnlock()
|
||||
return nl
|
||||
}
|
||||
|
||||
@@ -143,27 +132,27 @@ func (l *defaultLogger) Fatal(ctx context.Context, args ...interface{}) {
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Infof(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, InfoLevel, msg, args...)
|
||||
l.Logf(ctx, InfoLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Errorf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, ErrorLevel, msg, args...)
|
||||
l.Logf(ctx, ErrorLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Debugf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, DebugLevel, msg, args...)
|
||||
l.Logf(ctx, DebugLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Warnf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, WarnLevel, msg, args...)
|
||||
l.Logf(ctx, WarnLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Tracef(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, TraceLevel, msg, args...)
|
||||
l.Logf(ctx, TraceLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Fatalf(ctx context.Context, msg string, args ...interface{}) {
|
||||
l.logfFunc(ctx, FatalLevel, msg, args...)
|
||||
l.Logf(ctx, FatalLevel, msg, args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -236,8 +225,6 @@ func NewLogger(opts ...Option) Logger {
|
||||
l := &defaultLogger{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
l.logFunc = l.Log
|
||||
l.logfFunc = l.Logf
|
||||
l.enc = json.NewEncoder(l.opts.Out)
|
||||
return l
|
||||
}
|
||||
|
@@ -32,7 +32,33 @@ func TestFields(t *testing.T) {
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Fields("key", "val").Info(ctx, "message")
|
||||
|
||||
nl := l.Fields("key", "val")
|
||||
|
||||
nl.Info(ctx, "message")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) {
|
||||
t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromContextWithFields(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
var ok bool
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nl := l.Fields("key", "val")
|
||||
|
||||
ctx = NewContext(ctx, nl)
|
||||
|
||||
l, ok = FromContext(ctx)
|
||||
if !ok {
|
||||
t.Fatalf("context does not have logger")
|
||||
}
|
||||
|
||||
l.Info(ctx, "message")
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) {
|
||||
t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes())
|
||||
}
|
||||
@@ -110,39 +136,3 @@ func TestLogger(t *testing.T) {
|
||||
t.Fatalf("logger error, buf %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerWrapper(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
||||
if err := l.Init(WrapLogger(NewOmitWrapper())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type secret struct {
|
||||
Name string
|
||||
Passw string `logger:"omit"`
|
||||
}
|
||||
s := &secret{Name: "name", Passw: "secret"}
|
||||
l.Errorf(ctx, "test %#+v", s)
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
||||
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmitLoggerWrapper(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
buf := bytes.NewBuffer(nil)
|
||||
l := NewOmitLogger(NewLogger(WithLevel(TraceLevel), WithOutput(buf)))
|
||||
if err := l.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type secret struct {
|
||||
Name string
|
||||
Passw string `logger:"omit"`
|
||||
}
|
||||
s := &secret{Name: "name", Passw: "secret"}
|
||||
l.Errorf(ctx, "test %#+v", s)
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
||||
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
@@ -19,8 +19,6 @@ type Options struct {
|
||||
Fields []interface{}
|
||||
// Name holds the logger name
|
||||
Name string
|
||||
// Wrappers logger wrapper that called before actual Log/Logf function
|
||||
Wrappers []Wrapper
|
||||
// The logging level the logger should log
|
||||
Level Level
|
||||
// CallerSkipCount number of frmaes to skip
|
||||
@@ -83,10 +81,3 @@ func WithName(n string) Option {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// WrapLogger adds a logger Wrapper to a list of options passed into the logger
|
||||
func WrapLogger(w Wrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Wrappers = append(o.Wrappers, w)
|
||||
}
|
||||
}
|
||||
|
681
logger/unwrap/unwrap.go
Normal file
681
logger/unwrap/unwrap.go
Normal file
@@ -0,0 +1,681 @@
|
||||
package unwrap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
)
|
||||
|
||||
const sf = "0-+# "
|
||||
|
||||
var hexDigits = "0123456789abcdef"
|
||||
|
||||
var (
|
||||
panicBytes = []byte("(PANIC=")
|
||||
plusBytes = []byte("+")
|
||||
iBytes = []byte("i")
|
||||
trueBytes = []byte("true")
|
||||
falseBytes = []byte("false")
|
||||
interfaceBytes = []byte("(interface {})")
|
||||
openBraceBytes = []byte("{")
|
||||
closeBraceBytes = []byte("}")
|
||||
asteriskBytes = []byte("*")
|
||||
ampBytes = []byte("&")
|
||||
colonBytes = []byte(":")
|
||||
openParenBytes = []byte("(")
|
||||
closeParenBytes = []byte(")")
|
||||
spaceBytes = []byte(" ")
|
||||
commaBytes = []byte(",")
|
||||
pointerChainBytes = []byte("->")
|
||||
nilAngleBytes = []byte("<nil>")
|
||||
circularShortBytes = []byte("<shown>")
|
||||
invalidAngleBytes = []byte("<invalid>")
|
||||
filteredBytes = []byte("<filtered>")
|
||||
openBracketBytes = []byte("[")
|
||||
closeBracketBytes = []byte("]")
|
||||
percentBytes = []byte("%")
|
||||
precisionBytes = []byte(".")
|
||||
openAngleBytes = []byte("<")
|
||||
closeAngleBytes = []byte(">")
|
||||
openMapBytes = []byte("{")
|
||||
closeMapBytes = []byte("}")
|
||||
)
|
||||
|
||||
type protoMessage interface {
|
||||
Reset()
|
||||
ProtoMessage()
|
||||
}
|
||||
|
||||
type Wrapper struct {
|
||||
val interface{}
|
||||
s fmt.State
|
||||
pointers map[uintptr]int
|
||||
opts *Options
|
||||
depth int
|
||||
ignoreNextType bool
|
||||
takeMap map[int]bool
|
||||
protoWrapperType bool
|
||||
sqlWrapperType bool
|
||||
}
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
Codec codec.Codec
|
||||
Indent string
|
||||
Methods bool
|
||||
Tagged bool
|
||||
}
|
||||
|
||||
// NewOptions creates new Options struct via provided args
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Indent: " ",
|
||||
Methods: false,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(*Options)
|
||||
|
||||
// Indent option specify indent level
|
||||
func Indent(f string) Option {
|
||||
return func(o *Options) {
|
||||
o.Indent = f
|
||||
}
|
||||
}
|
||||
|
||||
// Methods option toggles fmt.Stringer methods
|
||||
func Methods(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.Methods = b
|
||||
}
|
||||
}
|
||||
|
||||
// Codec option automatic marshal arg via specified codec and write it to log
|
||||
func Codec(c codec.Codec) Option {
|
||||
return func(o *Options) {
|
||||
o.Codec = c
|
||||
}
|
||||
}
|
||||
|
||||
// Tagged option toggles output only logger:"take" fields
|
||||
func Tagged(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.Tagged = b
|
||||
}
|
||||
}
|
||||
|
||||
func Unwrap(val interface{}, opts ...Option) *Wrapper {
|
||||
options := NewOptions(opts...)
|
||||
return &Wrapper{val: val, opts: &options, pointers: make(map[uintptr]int), takeMap: make(map[int]bool)}
|
||||
}
|
||||
|
||||
func (w *Wrapper) unpackValue(v reflect.Value) reflect.Value {
|
||||
if v.Kind() == reflect.Interface {
|
||||
w.ignoreNextType = false
|
||||
if !v.IsNil() {
|
||||
v = v.Elem()
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// formatPtr handles formatting of pointers by indirecting them as necessary.
|
||||
func (w *Wrapper) formatPtr(v reflect.Value) {
|
||||
// Display nil if top level pointer is nil.
|
||||
showTypes := w.s.Flag('#')
|
||||
if v.IsNil() && (!showTypes || w.ignoreNextType) {
|
||||
_, _ = w.s.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove pointers at or below the current depth from map used to detect
|
||||
// circular refs.
|
||||
for k, depth := range w.pointers {
|
||||
if depth >= w.depth {
|
||||
delete(w.pointers, k)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep list of all dereferenced pointers to possibly show later.
|
||||
pointerChain := make([]uintptr, 0)
|
||||
|
||||
// Figure out how many levels of indirection there are by derferencing
|
||||
// pointers and unpacking interfaces down the chain while detecting circular
|
||||
// references.
|
||||
nilFound := false
|
||||
cycleFound := false
|
||||
indirects := 0
|
||||
ve := v
|
||||
for ve.Kind() == reflect.Ptr {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
indirects++
|
||||
addr := ve.Pointer()
|
||||
pointerChain = append(pointerChain, addr)
|
||||
if pd, ok := w.pointers[addr]; ok && pd < w.depth {
|
||||
cycleFound = true
|
||||
indirects--
|
||||
break
|
||||
}
|
||||
w.pointers[addr] = w.depth
|
||||
|
||||
ve = ve.Elem()
|
||||
if ve.Kind() == reflect.Interface {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
ve = ve.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
// Display type or indirection level depending on flags.
|
||||
if showTypes && !w.ignoreNextType {
|
||||
if w.depth > 0 {
|
||||
_, _ = w.s.Write(openParenBytes)
|
||||
}
|
||||
if w.depth > 0 {
|
||||
_, _ = w.s.Write(bytes.Repeat(asteriskBytes, indirects))
|
||||
} else {
|
||||
_, _ = w.s.Write(bytes.Repeat(ampBytes, indirects))
|
||||
}
|
||||
_, _ = w.s.Write([]byte(ve.Type().String()))
|
||||
if w.depth > 0 {
|
||||
_, _ = w.s.Write(closeParenBytes)
|
||||
}
|
||||
} else {
|
||||
if nilFound || cycleFound {
|
||||
indirects += strings.Count(ve.Type().String(), "*")
|
||||
}
|
||||
_, _ = w.s.Write(openAngleBytes)
|
||||
_, _ = w.s.Write([]byte(strings.Repeat("*", indirects)))
|
||||
_, _ = w.s.Write(closeAngleBytes)
|
||||
}
|
||||
|
||||
// Display pointer information depending on flags.
|
||||
if w.s.Flag('+') && (len(pointerChain) > 0) {
|
||||
_, _ = w.s.Write(openParenBytes)
|
||||
for i, addr := range pointerChain {
|
||||
if i > 0 {
|
||||
_, _ = w.s.Write(pointerChainBytes)
|
||||
}
|
||||
getHexPtr(w.s, addr)
|
||||
}
|
||||
_, _ = w.s.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// Display dereferenced value.
|
||||
switch {
|
||||
case nilFound:
|
||||
_, _ = w.s.Write(nilAngleBytes)
|
||||
case cycleFound:
|
||||
_, _ = w.s.Write(circularShortBytes)
|
||||
default:
|
||||
w.ignoreNextType = true
|
||||
w.format(ve)
|
||||
}
|
||||
}
|
||||
|
||||
// format is the main workhorse for providing the Formatter interface. It
|
||||
// uses the passed reflect value to figure out what kind of object we are
|
||||
// dealing with and formats it appropriately. It is a recursive function,
|
||||
// however circular data structures are detected and handled properly.
|
||||
func (w *Wrapper) format(v reflect.Value) {
|
||||
if w.opts.Codec != nil {
|
||||
buf, err := w.opts.Codec.Marshal(v.Interface())
|
||||
if err != nil {
|
||||
_, _ = w.s.Write(invalidAngleBytes)
|
||||
return
|
||||
}
|
||||
_, _ = w.s.Write(buf)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle invalid reflect values immediately.
|
||||
kind := v.Kind()
|
||||
if kind == reflect.Invalid {
|
||||
_, _ = w.s.Write(invalidAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle pointers specially.
|
||||
switch kind {
|
||||
case reflect.Ptr:
|
||||
if !v.IsZero() {
|
||||
if strings.HasPrefix(reflect.Indirect(v).Type().String(), "wrapperspb.") {
|
||||
w.protoWrapperType = true
|
||||
} else if strings.HasPrefix(reflect.Indirect(v).Type().String(), "sql.Null") {
|
||||
w.sqlWrapperType = true
|
||||
} else if v.CanInterface() {
|
||||
if _, ok := v.Interface().(protoMessage); ok {
|
||||
w.protoWrapperType = true
|
||||
}
|
||||
}
|
||||
}
|
||||
w.formatPtr(v)
|
||||
return
|
||||
case reflect.Struct:
|
||||
if !v.IsZero() {
|
||||
if strings.HasPrefix(reflect.Indirect(v).Type().String(), "sql.Null") {
|
||||
w.sqlWrapperType = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get type information unless already handled elsewhere.
|
||||
if !w.ignoreNextType && w.s.Flag('#') {
|
||||
if v.Type().Kind() != reflect.Map &&
|
||||
v.Type().Kind() != reflect.String &&
|
||||
v.Type().Kind() != reflect.Array &&
|
||||
v.Type().Kind() != reflect.Slice {
|
||||
_, _ = w.s.Write(openParenBytes)
|
||||
}
|
||||
if v.Kind() != reflect.String {
|
||||
_, _ = w.s.Write([]byte(v.Type().String()))
|
||||
}
|
||||
if v.Type().Kind() != reflect.Map &&
|
||||
v.Type().Kind() != reflect.String &&
|
||||
v.Type().Kind() != reflect.Array &&
|
||||
v.Type().Kind() != reflect.Slice {
|
||||
_, _ = w.s.Write(closeParenBytes)
|
||||
}
|
||||
}
|
||||
w.ignoreNextType = false
|
||||
|
||||
// Call Stringer/error interfaces if they exist and the handle methods
|
||||
// flag is enabled.
|
||||
if w.opts.Methods {
|
||||
if (kind != reflect.Invalid) && (kind != reflect.Interface) {
|
||||
if handled := handleMethods(w.opts, w.s, v); handled {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case reflect.Invalid:
|
||||
_, _ = w.s.Write(invalidAngleBytes)
|
||||
case reflect.Bool:
|
||||
getBool(w.s, v.Bool())
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
getInt(w.s, v.Int(), 10)
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
getUint(w.s, v.Uint(), 10)
|
||||
case reflect.Float32:
|
||||
getFloat(w.s, v.Float(), 32)
|
||||
case reflect.Float64:
|
||||
getFloat(w.s, v.Float(), 64)
|
||||
case reflect.Complex64:
|
||||
getComplex(w.s, v.Complex(), 32)
|
||||
case reflect.Complex128:
|
||||
getComplex(w.s, v.Complex(), 64)
|
||||
case reflect.Slice:
|
||||
if v.IsNil() {
|
||||
_, _ = w.s.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
case reflect.Array:
|
||||
_, _ = w.s.Write(openBraceBytes)
|
||||
w.depth++
|
||||
numEntries := v.Len()
|
||||
for i := 0; i < numEntries; i++ {
|
||||
if i > 0 {
|
||||
_, _ = w.s.Write(commaBytes)
|
||||
_, _ = w.s.Write(spaceBytes)
|
||||
}
|
||||
w.ignoreNextType = true
|
||||
w.format(w.unpackValue(v.Index(i)))
|
||||
}
|
||||
w.depth--
|
||||
_, _ = w.s.Write(closeBraceBytes)
|
||||
case reflect.String:
|
||||
_, _ = w.s.Write([]byte(`"` + v.String() + `"`))
|
||||
case reflect.Interface:
|
||||
// The only time we should get here is for nil interfaces due to
|
||||
// unpackValue calls.
|
||||
if v.IsNil() {
|
||||
_, _ = w.s.Write(nilAngleBytes)
|
||||
}
|
||||
case reflect.Ptr:
|
||||
// Do nothing. We should never get here since pointers have already
|
||||
// been handled above.
|
||||
case reflect.Map:
|
||||
// nil maps should be indicated as different than empty maps
|
||||
if v.IsNil() {
|
||||
_, _ = w.s.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
_, _ = w.s.Write(openMapBytes)
|
||||
w.depth++
|
||||
keys := v.MapKeys()
|
||||
for i, key := range keys {
|
||||
if i > 0 {
|
||||
_, _ = w.s.Write(spaceBytes)
|
||||
}
|
||||
w.ignoreNextType = true
|
||||
w.format(w.unpackValue(key))
|
||||
_, _ = w.s.Write(colonBytes)
|
||||
w.ignoreNextType = true
|
||||
w.format(w.unpackValue(v.MapIndex(key)))
|
||||
}
|
||||
w.depth--
|
||||
_, _ = w.s.Write(closeMapBytes)
|
||||
case reflect.Struct:
|
||||
|
||||
numFields := v.NumField()
|
||||
numWritten := 0
|
||||
_, _ = w.s.Write(openBraceBytes)
|
||||
w.depth++
|
||||
|
||||
vt := v.Type()
|
||||
prevSkip := false
|
||||
|
||||
for i := 0; i < numFields; i++ {
|
||||
switch vt.Field(i).Type.PkgPath() {
|
||||
case "google.golang.org/protobuf/internal/impl", "google.golang.org/protobuf/internal/pragma":
|
||||
w.protoWrapperType = true
|
||||
prevSkip = true
|
||||
continue
|
||||
}
|
||||
if w.protoWrapperType && !vt.Field(i).IsExported() {
|
||||
prevSkip = true
|
||||
continue
|
||||
} else if w.sqlWrapperType && vt.Field(i).Name == "Valid" {
|
||||
prevSkip = true
|
||||
continue
|
||||
}
|
||||
if _, ok := vt.Field(i).Tag.Lookup("protobuf"); ok && !w.protoWrapperType {
|
||||
w.protoWrapperType = true
|
||||
}
|
||||
sv, ok := vt.Field(i).Tag.Lookup("logger")
|
||||
switch {
|
||||
case ok:
|
||||
switch sv {
|
||||
case "omit":
|
||||
prevSkip = true
|
||||
continue
|
||||
case "take":
|
||||
break
|
||||
}
|
||||
case !ok && w.opts.Tagged:
|
||||
// skip top level untagged
|
||||
if w.depth == 1 {
|
||||
prevSkip = true
|
||||
continue
|
||||
}
|
||||
if tv, ok := w.takeMap[w.depth]; ok && !tv {
|
||||
prevSkip = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if prevSkip {
|
||||
prevSkip = false
|
||||
}
|
||||
|
||||
if numWritten > 0 {
|
||||
_, _ = w.s.Write(commaBytes)
|
||||
_, _ = w.s.Write(spaceBytes)
|
||||
}
|
||||
|
||||
vt := vt.Field(i)
|
||||
if w.s.Flag('+') || w.s.Flag('#') {
|
||||
_, _ = w.s.Write([]byte(vt.Name))
|
||||
_, _ = w.s.Write(colonBytes)
|
||||
}
|
||||
w.format(w.unpackValue(v.Field(i)))
|
||||
numWritten++
|
||||
}
|
||||
w.depth--
|
||||
|
||||
if numWritten == 0 && w.depth < 0 {
|
||||
_, _ = w.s.Write(filteredBytes)
|
||||
}
|
||||
_, _ = w.s.Write(closeBraceBytes)
|
||||
case reflect.Uintptr:
|
||||
getHexPtr(w.s, uintptr(v.Uint()))
|
||||
case reflect.UnsafePointer, reflect.Chan, reflect.Func:
|
||||
getHexPtr(w.s, v.Pointer())
|
||||
// There were not any other types at the time this code was written, but
|
||||
// fall back to letting the default fmt package handle it if any get added.
|
||||
default:
|
||||
format := w.buildDefaultFormat()
|
||||
if v.CanInterface() {
|
||||
_, _ = fmt.Fprintf(w.s, format, v.Interface())
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(w.s, format, v.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Wrapper) Format(s fmt.State, verb rune) {
|
||||
w.s = s
|
||||
|
||||
// Use standard formatting for verbs that are not v.
|
||||
if verb != 'v' {
|
||||
format := w.constructOrigFormat(verb)
|
||||
_, _ = fmt.Fprintf(s, format, w.val)
|
||||
return
|
||||
}
|
||||
|
||||
if w.val == nil {
|
||||
if s.Flag('#') {
|
||||
_, _ = s.Write(interfaceBytes)
|
||||
}
|
||||
_, _ = s.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
if w.opts.Tagged {
|
||||
w.buildTakeMap(reflect.ValueOf(w.val), 1)
|
||||
}
|
||||
|
||||
w.format(reflect.ValueOf(w.val))
|
||||
}
|
||||
|
||||
// handle special methods like error.Error() or fmt.Stringer interface
|
||||
func handleMethods(_ *Options, w io.Writer, v reflect.Value) (handled bool) {
|
||||
if !v.CanInterface() {
|
||||
// not our case
|
||||
return false
|
||||
}
|
||||
|
||||
if !v.CanAddr() {
|
||||
// not our case
|
||||
return false
|
||||
}
|
||||
|
||||
if v.CanAddr() {
|
||||
v = v.Addr()
|
||||
}
|
||||
|
||||
// Is it an error or Stringer?
|
||||
switch iface := v.Interface().(type) {
|
||||
case error:
|
||||
defer catchPanic(w, v)
|
||||
_, _ = w.Write([]byte(iface.Error()))
|
||||
return true
|
||||
case fmt.Stringer:
|
||||
defer catchPanic(w, v)
|
||||
_, _ = w.Write([]byte(iface.String()))
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// getBool outputs a boolean value as true or false to Writer w.
|
||||
func getBool(w io.Writer, val bool) {
|
||||
if val {
|
||||
_, _ = w.Write(trueBytes)
|
||||
} else {
|
||||
_, _ = w.Write(falseBytes)
|
||||
}
|
||||
}
|
||||
|
||||
// getInt outputs a signed integer value to Writer w.
|
||||
func getInt(w io.Writer, val int64, base int) {
|
||||
_, _ = w.Write([]byte(strconv.FormatInt(val, base)))
|
||||
}
|
||||
|
||||
// getUint outputs an unsigned integer value to Writer w.
|
||||
func getUint(w io.Writer, val uint64, base int) {
|
||||
_, _ = w.Write([]byte(strconv.FormatUint(val, base)))
|
||||
}
|
||||
|
||||
// getFloat outputs a floating point value using the specified precision,
|
||||
// which is expected to be 32 or 64bit, to Writer w.
|
||||
func getFloat(w io.Writer, val float64, precision int) {
|
||||
_, _ = w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
|
||||
}
|
||||
|
||||
// getComplex outputs a complex value using the specified float precision
|
||||
// for the real and imaginary parts to Writer w.
|
||||
func getComplex(w io.Writer, c complex128, floatPrecision int) {
|
||||
r := real(c)
|
||||
_, _ = w.Write(openParenBytes)
|
||||
_, _ = w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
|
||||
i := imag(c)
|
||||
if i >= 0 {
|
||||
_, _ = w.Write(plusBytes)
|
||||
}
|
||||
_, _ = w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
|
||||
_, _ = w.Write(iBytes)
|
||||
_, _ = w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// getHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
|
||||
// prefix to Writer w.
|
||||
func getHexPtr(w io.Writer, p uintptr) {
|
||||
// Null pointer.
|
||||
num := uint64(p)
|
||||
if num == 0 {
|
||||
_, _ = w.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
|
||||
buf := make([]byte, 18)
|
||||
|
||||
// It's simpler to construct the hex string right to left.
|
||||
base := uint64(16)
|
||||
i := len(buf) - 1
|
||||
for num >= base {
|
||||
buf[i] = hexDigits[num%base]
|
||||
num /= base
|
||||
i--
|
||||
}
|
||||
buf[i] = hexDigits[num]
|
||||
|
||||
// Add '0x' prefix.
|
||||
i--
|
||||
buf[i] = 'x'
|
||||
i--
|
||||
buf[i] = '0'
|
||||
|
||||
// Strip unused leading bytes.
|
||||
buf = buf[i:]
|
||||
_, _ = w.Write(buf)
|
||||
}
|
||||
|
||||
func catchPanic(w io.Writer, _ reflect.Value) {
|
||||
if err := recover(); err != nil {
|
||||
_, _ = w.Write(panicBytes)
|
||||
_, _ = fmt.Fprintf(w, "%v", err)
|
||||
_, _ = w.Write(closeParenBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Wrapper) buildDefaultFormat() (format string) {
|
||||
buf := bytes.NewBuffer(percentBytes)
|
||||
|
||||
for _, flag := range sf {
|
||||
if w.s.Flag(int(flag)) {
|
||||
_, _ = buf.WriteRune(flag)
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = buf.WriteRune('v')
|
||||
|
||||
format = buf.String()
|
||||
return format
|
||||
}
|
||||
|
||||
func (w *Wrapper) constructOrigFormat(verb rune) string {
|
||||
buf := bytes.NewBuffer(percentBytes)
|
||||
|
||||
for _, flag := range sf {
|
||||
if w.s.Flag(int(flag)) {
|
||||
_, _ = buf.WriteRune(flag)
|
||||
}
|
||||
}
|
||||
|
||||
if width, ok := w.s.Width(); ok {
|
||||
_, _ = buf.WriteString(strconv.Itoa(width))
|
||||
}
|
||||
|
||||
if precision, ok := w.s.Precision(); ok {
|
||||
_, _ = buf.Write(precisionBytes)
|
||||
_, _ = buf.WriteString(strconv.Itoa(precision))
|
||||
}
|
||||
|
||||
_, _ = buf.WriteRune(verb)
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (w *Wrapper) buildTakeMap(v reflect.Value, depth int) {
|
||||
if !v.IsValid() || v.IsZero() {
|
||||
return
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Slice, reflect.Array:
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
w.buildTakeMap(v.Index(i), depth+1)
|
||||
}
|
||||
w.takeMap[depth] = true
|
||||
return
|
||||
case reflect.Struct:
|
||||
break
|
||||
case reflect.Ptr:
|
||||
v = v.Elem()
|
||||
if v.Kind() != reflect.Struct {
|
||||
w.takeMap[depth] = true
|
||||
return
|
||||
}
|
||||
default:
|
||||
w.takeMap[depth] = true
|
||||
return
|
||||
}
|
||||
|
||||
vt := v.Type()
|
||||
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
sv, ok := vt.Field(i).Tag.Lookup("logger")
|
||||
if ok && sv == "take" {
|
||||
w.takeMap[depth] = false
|
||||
}
|
||||
if v.Kind() == reflect.Struct ||
|
||||
(v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) {
|
||||
w.buildTakeMap(v.Field(i), depth+1)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := w.takeMap[depth]; !ok {
|
||||
w.takeMap[depth] = true
|
||||
}
|
||||
}
|
100
logger/unwrap/unwrap_test.go
Normal file
100
logger/unwrap/unwrap_test.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package unwrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
)
|
||||
|
||||
func TestUnwrap(t *testing.T) {
|
||||
string1 := "string1"
|
||||
string2 := "string2"
|
||||
|
||||
type val1 struct {
|
||||
mp map[string]string
|
||||
val *val1
|
||||
str *string
|
||||
ar []*string
|
||||
}
|
||||
|
||||
v1 := &val1{ar: []*string{&string1, &string2}, str: &string1, val: &val1{str: &string2}, mp: map[string]string{"key": "val"}}
|
||||
|
||||
buf := fmt.Sprintf("%#v", Unwrap(v1))
|
||||
if strings.Compare(buf, `&unwrap.val1{mp:map[string]string{"key":"val"}, val:(*unwrap.val1){mp:map[string]string<nil>, val:(*unwrap.val1)<nil>, str:(*string)"string2", ar:[]*string<nil>}, str:(*string)"string1", ar:[]*string{<*><shown>, <*>"string2"}}`) != 0 {
|
||||
t.Fatalf("not proper written %s", buf)
|
||||
}
|
||||
|
||||
type val2 struct {
|
||||
mp map[string]string
|
||||
val *val2
|
||||
str string
|
||||
ar []string
|
||||
}
|
||||
|
||||
v2 := &val2{ar: []string{string1, string2}, str: string1, val: &val2{str: string2}, mp: map[string]string{"key": "val"}}
|
||||
_ = v2
|
||||
// t.Logf("output: %#v", v2)
|
||||
}
|
||||
|
||||
func TestCodec(t *testing.T) {
|
||||
type val struct {
|
||||
MP map[string]string `json:"mp"`
|
||||
STR string `json:"str"`
|
||||
AR []string `json:"ar"`
|
||||
}
|
||||
|
||||
v1 := &val{AR: []string{"string1", "string2"}, STR: "string", MP: map[string]string{"key": "val"}}
|
||||
|
||||
buf := fmt.Sprintf("%#v", Unwrap(v1, Codec(codec.NewCodec())))
|
||||
if strings.Compare(buf, `{"mp":{"key":"val"},"str":"string","ar":["string1","string2"]}`) != 0 {
|
||||
t.Fatalf("not proper written %s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmit(t *testing.T) {
|
||||
type val struct {
|
||||
Key1 string `logger:"omit"`
|
||||
Key2 string `logger:"take"`
|
||||
Key3 string
|
||||
}
|
||||
v1 := &val{Key1: "val1", Key2: "val2", Key3: "val3"}
|
||||
buf := fmt.Sprintf("%#v", Unwrap(v1))
|
||||
if strings.Compare(buf, `&unwrap.val{Key2:"val2", Key3:"val3"}`) != 0 {
|
||||
t.Fatalf("not proper written %s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagged(t *testing.T) {
|
||||
type val struct {
|
||||
Key1 string `logger:"take"`
|
||||
Key2 string
|
||||
}
|
||||
|
||||
v1 := &val{Key1: "val1", Key2: "val2"}
|
||||
buf := fmt.Sprintf("%#v", Unwrap(v1, Tagged(true)))
|
||||
if strings.Compare(buf, `&unwrap.val{Key1:"val1"}`) != 0 {
|
||||
t.Fatalf("not proper written %s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaggedNested(t *testing.T) {
|
||||
type val struct {
|
||||
key string `logger:"take"`
|
||||
val string `logger:"omit"`
|
||||
unk string
|
||||
}
|
||||
type str struct {
|
||||
key string `logger:"omit"`
|
||||
val *val `logger:"take"`
|
||||
}
|
||||
|
||||
var iface interface{}
|
||||
v := &str{val: &val{key: "test", unk: "unk"}}
|
||||
iface = v
|
||||
buf := fmt.Sprintf("%#v", Unwrap(iface, Tagged(true)))
|
||||
if strings.Compare(buf, `&unwrap.str{val:(*unwrap.val){key:"test"}}`) != 0 {
|
||||
t.Fatalf("not proper written %s", buf)
|
||||
}
|
||||
}
|
@@ -1,166 +0,0 @@
|
||||
package logger // import "go.unistack.org/micro/v3/logger/wrapper"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
rutil "go.unistack.org/micro/v3/util/reflect"
|
||||
)
|
||||
|
||||
// LogFunc function used for Log method
|
||||
type LogFunc func(ctx context.Context, level Level, args ...interface{})
|
||||
|
||||
// LogfFunc function used for Logf method
|
||||
type LogfFunc func(ctx context.Context, level Level, msg string, args ...interface{})
|
||||
|
||||
type Wrapper interface {
|
||||
// Log logs message with needed level
|
||||
Log(LogFunc) LogFunc
|
||||
// Logf logs message with needed level
|
||||
Logf(LogfFunc) LogfFunc
|
||||
}
|
||||
|
||||
var _ Logger = &omitLogger{}
|
||||
|
||||
type omitLogger struct {
|
||||
l Logger
|
||||
}
|
||||
|
||||
func NewOmitLogger(l Logger) Logger {
|
||||
return &omitLogger{l: l}
|
||||
}
|
||||
|
||||
func (w *omitLogger) Init(opts ...Option) error {
|
||||
return w.l.Init(append(opts, WrapLogger(NewOmitWrapper()))...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) V(level Level) bool {
|
||||
return w.l.V(level)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Level(level Level) {
|
||||
w.l.Level(level)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Clone(opts ...Option) Logger {
|
||||
return w.l.Clone(opts...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Options() Options {
|
||||
return w.l.Options()
|
||||
}
|
||||
|
||||
func (w *omitLogger) Fields(fields ...interface{}) Logger {
|
||||
return w.l.Fields(fields...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Info(ctx context.Context, args ...interface{}) {
|
||||
w.l.Info(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Trace(ctx context.Context, args ...interface{}) {
|
||||
w.l.Trace(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Debug(ctx context.Context, args ...interface{}) {
|
||||
w.l.Debug(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Warn(ctx context.Context, args ...interface{}) {
|
||||
w.l.Warn(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Error(ctx context.Context, args ...interface{}) {
|
||||
w.l.Error(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Fatal(ctx context.Context, args ...interface{}) {
|
||||
w.l.Fatal(ctx, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Infof(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Infof(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Tracef(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Tracef(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Debugf(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Debugf(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Warnf(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Warnf(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Errorf(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Errorf(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Fatalf(ctx context.Context, msg string, args ...interface{}) {
|
||||
w.l.Fatalf(ctx, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Log(ctx context.Context, level Level, args ...interface{}) {
|
||||
w.l.Log(ctx, level, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) Logf(ctx context.Context, level Level, msg string, args ...interface{}) {
|
||||
w.l.Logf(ctx, level, msg, args...)
|
||||
}
|
||||
|
||||
func (w *omitLogger) String() string {
|
||||
return w.l.String()
|
||||
}
|
||||
|
||||
type omitWrapper struct{}
|
||||
|
||||
func NewOmitWrapper() Wrapper {
|
||||
return &omitWrapper{}
|
||||
}
|
||||
|
||||
func getArgs(args []interface{}) []interface{} {
|
||||
nargs := make([]interface{}, 0, len(args))
|
||||
var err error
|
||||
for _, arg := range args {
|
||||
val := reflect.ValueOf(arg)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
narg := arg
|
||||
if val.Kind() != reflect.Struct {
|
||||
nargs = append(nargs, narg)
|
||||
continue
|
||||
}
|
||||
|
||||
if narg, err = rutil.Zero(arg); err != nil {
|
||||
nargs = append(nargs, narg)
|
||||
continue
|
||||
}
|
||||
|
||||
rutil.CopyDefaults(narg, arg)
|
||||
if flds, ferr := rutil.StructFields(narg); ferr == nil {
|
||||
for _, fld := range flds {
|
||||
if tv, ok := fld.Field.Tag.Lookup("logger"); ok && tv == "omit" {
|
||||
fld.Value.Set(reflect.Zero(fld.Value.Type()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nargs = append(nargs, narg)
|
||||
}
|
||||
return nargs
|
||||
}
|
||||
|
||||
func (w *omitWrapper) Log(fn LogFunc) LogFunc {
|
||||
return func(ctx context.Context, level Level, args ...interface{}) {
|
||||
fn(ctx, level, getArgs(args)...)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *omitWrapper) Logf(fn LogfFunc) LogfFunc {
|
||||
return func(ctx context.Context, level Level, msg string, args ...interface{}) {
|
||||
fn(ctx, level, msg, getArgs(args)...)
|
||||
}
|
||||
}
|
@@ -66,7 +66,7 @@ var (
|
||||
}
|
||||
|
||||
// DefaultSkipEndpoints wrapper not called for this endpoints
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics"}
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics", "Health.Live", "Health.Ready", "Health.Version"}
|
||||
)
|
||||
|
||||
type lWrapper struct {
|
||||
@@ -228,11 +228,7 @@ func (l *lWrapper) Call(ctx context.Context, req client.Request, rsp interface{}
|
||||
for _, o := range l.opts.ClientCallObservers {
|
||||
labels = append(labels, o(ctx, req, rsp, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -255,11 +251,7 @@ func (l *lWrapper) Stream(ctx context.Context, req client.Request, opts ...clien
|
||||
for _, o := range l.opts.ClientStreamObservers {
|
||||
labels = append(labels, o(ctx, req, opts, stream, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return stream, err
|
||||
}
|
||||
@@ -282,11 +274,7 @@ func (l *lWrapper) Publish(ctx context.Context, msg client.Message, opts ...clie
|
||||
for _, o := range l.opts.ClientPublishObservers {
|
||||
labels = append(labels, o(ctx, msg, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -309,11 +297,7 @@ func (l *lWrapper) ServerHandler(ctx context.Context, req server.Request, rsp in
|
||||
for _, o := range l.opts.ServerHandlerObservers {
|
||||
labels = append(labels, o(ctx, req, rsp, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -336,11 +320,7 @@ func (l *lWrapper) ServerSubscriber(ctx context.Context, msg server.Message) err
|
||||
for _, o := range l.opts.ServerSubscriberObservers {
|
||||
labels = append(labels, o(ctx, msg, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -387,11 +367,7 @@ func (l *lWrapper) ClientCallFunc(ctx context.Context, addr string, req client.R
|
||||
for _, o := range l.opts.ClientCallFuncObservers {
|
||||
labels = append(labels, o(ctx, addr, req, rsp, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, len(labels)/2)
|
||||
for i := 0; i < len(labels); i += 2 {
|
||||
fields[labels[i]] = labels[i+1]
|
||||
}
|
||||
l.opts.Logger.Fields(fields).Log(ctx, l.opts.Level)
|
||||
l.opts.Logger.Fields(labels).Log(ctx, l.opts.Level)
|
||||
|
||||
return err
|
||||
}
|
||||
|
@@ -50,7 +50,7 @@ var (
|
||||
labelEndpoint = "endpoint"
|
||||
|
||||
// DefaultSkipEndpoints contains list of endpoints that not evaluted by wrapper
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics"}
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics", "Health.Live", "Health.Ready", "Health.Version"}
|
||||
)
|
||||
|
||||
// Options struct
|
||||
@@ -255,6 +255,7 @@ func (w *wrapper) Publish(ctx context.Context, p client.Message, opts ...client.
|
||||
}
|
||||
|
||||
// NewHandlerWrapper create new server handler wrapper
|
||||
// deprecated
|
||||
func NewHandlerWrapper(opts ...Option) server.HandlerWrapper {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
@@ -262,6 +263,14 @@ func NewHandlerWrapper(opts ...Option) server.HandlerWrapper {
|
||||
return handler.HandlerFunc
|
||||
}
|
||||
|
||||
// NewServerHandlerWrapper create new server handler wrapper
|
||||
func NewServerHandlerWrapper(opts ...Option) server.HandlerWrapper {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
return handler.HandlerFunc
|
||||
}
|
||||
|
||||
func (w *wrapper) HandlerFunc(fn server.HandlerFunc) server.HandlerFunc {
|
||||
return func(ctx context.Context, req server.Request, rsp interface{}) error {
|
||||
endpoint := req.Service() + "." + req.Endpoint()
|
||||
@@ -295,6 +304,7 @@ func (w *wrapper) HandlerFunc(fn server.HandlerFunc) server.HandlerFunc {
|
||||
}
|
||||
|
||||
// NewSubscriberWrapper create server subscribe wrapper
|
||||
// deprecated
|
||||
func NewSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
@@ -302,6 +312,13 @@ func NewSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
|
||||
return handler.SubscriberFunc
|
||||
}
|
||||
|
||||
func NewServerSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
return handler.SubscriberFunc
|
||||
}
|
||||
|
||||
func (w *wrapper) SubscriberFunc(fn server.SubscriberFunc) server.SubscriberFunc {
|
||||
return func(ctx context.Context, msg server.Message) error {
|
||||
endpoint := msg.Topic()
|
||||
|
@@ -49,12 +49,12 @@ func (p *profiler) Start() error {
|
||||
// create exit channel
|
||||
p.exit = make(chan bool)
|
||||
|
||||
cpuFile := filepath.Join("/tmp", "cpu.pprof")
|
||||
memFile := filepath.Join("/tmp", "mem.pprof")
|
||||
cpuFile := filepath.Join(string(os.PathSeparator)+"tmp", "cpu.pprof")
|
||||
memFile := filepath.Join(string(os.PathSeparator)+"tmp", "mem.pprof")
|
||||
|
||||
if len(p.opts.Name) > 0 {
|
||||
cpuFile = filepath.Join("/tmp", p.opts.Name+".cpu.pprof")
|
||||
memFile = filepath.Join("/tmp", p.opts.Name+".mem.pprof")
|
||||
cpuFile = filepath.Join(string(os.PathSeparator)+"tmp", p.opts.Name+".cpu.pprof")
|
||||
memFile = filepath.Join(string(os.PathSeparator)+"tmp", p.opts.Name+".mem.pprof")
|
||||
}
|
||||
|
||||
f1, err := os.Create(cpuFile)
|
||||
|
@@ -164,7 +164,7 @@ func (m *memory) Register(ctx context.Context, s *Service, opts ...RegisterOptio
|
||||
continue
|
||||
}
|
||||
|
||||
metadata := make(map[string]string)
|
||||
metadata := make(map[string]string, len(n.Metadata))
|
||||
|
||||
// make copy of metadata
|
||||
for k, v := range n.Metadata {
|
||||
|
@@ -301,11 +301,11 @@ func TestWatcher(t *testing.T) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
for {
|
||||
ch, err := wc.Next()
|
||||
_, err := wc.Next()
|
||||
if err != nil {
|
||||
t.Fatal("unexpected err", err)
|
||||
}
|
||||
t.Logf("changes %#+v", ch.Service)
|
||||
// t.Logf("changes %#+v", ch.Service)
|
||||
wc.Stop()
|
||||
wg.Done()
|
||||
return
|
||||
|
@@ -2,7 +2,6 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -33,12 +32,11 @@ type memoryStore struct {
|
||||
}
|
||||
|
||||
func (m *memoryStore) key(prefix, key string) string {
|
||||
return filepath.Join(prefix, key)
|
||||
return prefix + m.opts.Separator + key
|
||||
}
|
||||
|
||||
func (m *memoryStore) exists(prefix, key string) error {
|
||||
key = m.key(prefix, key)
|
||||
|
||||
_, found := m.store.Get(key)
|
||||
if !found {
|
||||
return ErrNotFound
|
||||
|
@@ -30,20 +30,25 @@ type Options struct {
|
||||
Name string
|
||||
// Namespace of the records
|
||||
Namespace string
|
||||
// Separator used as key parts separator
|
||||
Separator string
|
||||
// Addrs contains store address
|
||||
Addrs []string
|
||||
// Wrappers store wrapper that called before actual functions
|
||||
// Wrappers []Wrapper
|
||||
// Timeout specifies timeout duration for all operations
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// NewOptions creates options struct
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
Context: context.Background(),
|
||||
Codec: codec.DefaultCodec,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Meter: meter.DefaultMeter,
|
||||
Logger: logger.DefaultLogger,
|
||||
Context: context.Background(),
|
||||
Codec: codec.DefaultCodec,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Meter: meter.DefaultMeter,
|
||||
Separator: DefaultSeparator,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
@@ -96,6 +101,13 @@ func Name(n string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Separator the value used as key parts separator
|
||||
func Separator(s string) Option {
|
||||
return func(o *Options) {
|
||||
o.Separator = s
|
||||
}
|
||||
}
|
||||
|
||||
// Namespace sets namespace of the store
|
||||
func Namespace(ns string) Option {
|
||||
return func(o *Options) {
|
||||
@@ -110,6 +122,13 @@ func Tracer(t tracer.Tracer) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout sets the timeout
|
||||
func Timeout(td time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.Timeout = td
|
||||
}
|
||||
}
|
||||
|
||||
// Addrs contains the addresses or other connection information of the backing storage.
|
||||
// For example, an etcd implementation would contain the nodes of the cluster.
|
||||
// A SQL implementation could contain one or more connection strings.
|
||||
|
@@ -13,6 +13,8 @@ var (
|
||||
ErrInvalidKey = errors.New("invalid key")
|
||||
// DefaultStore is the global default store
|
||||
DefaultStore = NewStore()
|
||||
// DefaultSeparator is the gloabal default key parts separator
|
||||
DefaultSeparator = "/"
|
||||
)
|
||||
|
||||
// Store is a data storage interface
|
||||
|
@@ -46,3 +46,13 @@ func NewSpanContext(ctx context.Context, span Span) context.Context {
|
||||
}
|
||||
return context.WithValue(ctx, spanKey{}, span)
|
||||
}
|
||||
|
||||
// SetOption returns a function to setup a context with given value
|
||||
func SetOption(k, v interface{}) Option {
|
||||
return func(o *Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
o.Context = context.WithValue(o.Context, k, v)
|
||||
}
|
||||
}
|
||||
|
@@ -13,6 +13,7 @@ func (t *noopTracer) Start(ctx context.Context, name string, opts ...SpanOption)
|
||||
name: name,
|
||||
ctx: ctx,
|
||||
tracer: t,
|
||||
opts: NewSpanOptions(opts...),
|
||||
}
|
||||
if span.ctx == nil {
|
||||
span.ctx = context.Background()
|
||||
@@ -32,10 +33,12 @@ func (t *noopTracer) Name() string {
|
||||
}
|
||||
|
||||
type noopSpan struct {
|
||||
ctx context.Context
|
||||
tracer Tracer
|
||||
name string
|
||||
labels []Label
|
||||
ctx context.Context
|
||||
tracer Tracer
|
||||
name string
|
||||
opts SpanOptions
|
||||
status SpanStatus
|
||||
statusMsg string
|
||||
}
|
||||
|
||||
func (s *noopSpan) Finish(opts ...SpanOption) {
|
||||
@@ -56,8 +59,25 @@ func (s *noopSpan) SetName(name string) {
|
||||
s.name = name
|
||||
}
|
||||
|
||||
func (s *noopSpan) SetLabels(labels ...Label) {
|
||||
s.labels = labels
|
||||
func (s *noopSpan) SetLabels(labels ...interface{}) {
|
||||
s.opts.Labels = labels
|
||||
}
|
||||
|
||||
func (s *noopSpan) AddLabels(labels ...interface{}) {
|
||||
s.opts.Labels = append(s.opts.Labels, labels...)
|
||||
}
|
||||
|
||||
func (s *noopSpan) Kind() SpanKind {
|
||||
return s.opts.Kind
|
||||
}
|
||||
|
||||
func (s *noopSpan) Status() (SpanStatus, string) {
|
||||
return s.status, s.statusMsg
|
||||
}
|
||||
|
||||
func (s *noopSpan) SetStatus(st SpanStatus, msg string) {
|
||||
s.status = st
|
||||
s.statusMsg = msg
|
||||
}
|
||||
|
||||
// NewTracer returns new memory tracer
|
||||
|
@@ -1,9 +1,91 @@
|
||||
package tracer
|
||||
|
||||
import "go.unistack.org/micro/v3/logger"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.unistack.org/micro/v3/logger"
|
||||
)
|
||||
|
||||
type SpanStatus int
|
||||
|
||||
const (
|
||||
// SpanStatusUnset is the default status code.
|
||||
SpanStatusUnset SpanStatus = 0
|
||||
|
||||
// SpanStatusError indicates the operation contains an error.
|
||||
SpanStatusError SpanStatus = 1
|
||||
|
||||
// SpanStatusOK indicates operation has been validated by an Application developers
|
||||
// or Operator to have completed successfully, or contain no error.
|
||||
SpanStatusOK SpanStatus = 2
|
||||
)
|
||||
|
||||
func (s SpanStatus) String() string {
|
||||
switch s {
|
||||
case SpanStatusUnset:
|
||||
return "Unset"
|
||||
case SpanStatusError:
|
||||
return "Error"
|
||||
case SpanStatusOK:
|
||||
return "OK"
|
||||
default:
|
||||
return "Unset"
|
||||
}
|
||||
}
|
||||
|
||||
type SpanKind int
|
||||
|
||||
const (
|
||||
// SpanKindUnspecified is an unspecified SpanKind and is not a valid
|
||||
// SpanKind. SpanKindUnspecified should be replaced with SpanKindInternal
|
||||
// if it is received.
|
||||
SpanKindUnspecified SpanKind = 0
|
||||
// SpanKindInternal is a SpanKind for a Span that represents an internal
|
||||
// operation within an application.
|
||||
SpanKindInternal SpanKind = 1
|
||||
// SpanKindServer is a SpanKind for a Span that represents the operation
|
||||
// of handling a request from a client.
|
||||
SpanKindServer SpanKind = 2
|
||||
// SpanKindClient is a SpanKind for a Span that represents the operation
|
||||
// of client making a request to a server.
|
||||
SpanKindClient SpanKind = 3
|
||||
// SpanKindProducer is a SpanKind for a Span that represents the operation
|
||||
// of a producer sending a message to a message broker. Unlike
|
||||
// SpanKindClient and SpanKindServer, there is often no direct
|
||||
// relationship between this kind of Span and a SpanKindConsumer kind. A
|
||||
// SpanKindProducer Span will end once the message is accepted by the
|
||||
// message broker which might not overlap with the processing of that
|
||||
// message.
|
||||
SpanKindProducer SpanKind = 4
|
||||
// SpanKindConsumer is a SpanKind for a Span that represents the operation
|
||||
// of a consumer receiving a message from a message broker. Like
|
||||
// SpanKindProducer Spans, there is often no direct relationship between
|
||||
// this Span and the Span that produced the message.
|
||||
SpanKindConsumer SpanKind = 5
|
||||
)
|
||||
|
||||
func (sk SpanKind) String() string {
|
||||
switch sk {
|
||||
case SpanKindInternal:
|
||||
return "internal"
|
||||
case SpanKindServer:
|
||||
return "server"
|
||||
case SpanKindClient:
|
||||
return "client"
|
||||
case SpanKindProducer:
|
||||
return "producer"
|
||||
case SpanKindConsumer:
|
||||
return "consumer"
|
||||
default:
|
||||
return "unspecified"
|
||||
}
|
||||
}
|
||||
|
||||
// SpanOptions contains span option
|
||||
type SpanOptions struct{}
|
||||
type SpanOptions struct {
|
||||
Labels []interface{}
|
||||
Kind SpanKind
|
||||
}
|
||||
|
||||
// SpanOption func signature
|
||||
type SpanOption func(o *SpanOptions)
|
||||
@@ -14,8 +96,22 @@ type EventOptions struct{}
|
||||
// EventOption func signature
|
||||
type EventOption func(o *EventOptions)
|
||||
|
||||
func WithSpanLabels(labels ...interface{}) SpanOption {
|
||||
return func(o *SpanOptions) {
|
||||
o.Labels = labels
|
||||
}
|
||||
}
|
||||
|
||||
func WithSpanKind(k SpanKind) SpanOption {
|
||||
return func(o *SpanOptions) {
|
||||
o.Kind = k
|
||||
}
|
||||
}
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
// Context used to store custome tracer options
|
||||
Context context.Context
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Name of the tracer
|
||||
@@ -32,6 +128,17 @@ func Logger(l logger.Logger) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// NewSpanOptions returns default SpanOptions
|
||||
func NewSpanOptions(opts ...SpanOption) SpanOptions {
|
||||
options := SpanOptions{
|
||||
Kind: SpanKindInternal,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// NewOptions returns default options
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
|
@@ -29,35 +29,14 @@ type Span interface {
|
||||
Context() context.Context
|
||||
// SetName set the span name
|
||||
SetName(name string)
|
||||
// SetStatus set the span status code and msg
|
||||
SetStatus(status SpanStatus, msg string)
|
||||
// Status returns span status and msg
|
||||
Status() (SpanStatus, string)
|
||||
// SetLabels set the span labels
|
||||
SetLabels(labels ...Label)
|
||||
}
|
||||
|
||||
type Label struct {
|
||||
val interface{}
|
||||
key string
|
||||
}
|
||||
|
||||
func LabelAny(k string, v interface{}) Label {
|
||||
return Label{key: k, val: v}
|
||||
}
|
||||
|
||||
func LabelString(k string, v string) Label {
|
||||
return Label{key: k, val: v}
|
||||
}
|
||||
|
||||
func LabelInt(k string, v int) Label {
|
||||
return Label{key: k, val: v}
|
||||
}
|
||||
|
||||
func LabelInt64(k string, v int64) Label {
|
||||
return Label{key: k, val: v}
|
||||
}
|
||||
|
||||
func LabelFloat64(k string, v float64) Label {
|
||||
return Label{key: k, val: v}
|
||||
}
|
||||
|
||||
func LabelBool(k string, v bool) Label {
|
||||
return Label{key: k, val: v}
|
||||
SetLabels(labels ...interface{})
|
||||
// AddLabels append the span labels
|
||||
AddLabels(labels ...interface{})
|
||||
// Kind returns span kind
|
||||
Kind() SpanKind
|
||||
}
|
||||
|
@@ -13,96 +13,108 @@ import (
|
||||
|
||||
var (
|
||||
DefaultClientCallObserver = func(ctx context.Context, req client.Request, rsp interface{}, opts []client.CallOption, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Call %s.%s", req.Service(), req.Method()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md)+1)
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultClientStreamObserver = func(ctx context.Context, req client.Request, opts []client.CallOption, stream client.Stream, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Stream %s.%s", req.Service(), req.Method()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md))
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultClientPublishObserver = func(ctx context.Context, msg client.Message, opts []client.PublishOption, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("Pub to %s", msg.Topic()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Publish %s", msg.Topic()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md))
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultServerHandlerObserver = func(ctx context.Context, req server.Request, rsp interface{}, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Handler %s.%s", req.Service(), req.Method()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromIncomingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md))
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultServerSubscriberObserver = func(ctx context.Context, msg server.Message, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("Sub from %s", msg.Topic()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Subscriber %s", msg.Topic()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromIncomingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md))
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultClientCallFuncObserver = func(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions, sp tracer.Span, err error) {
|
||||
sp.SetName(fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()))
|
||||
var labels []tracer.Label
|
||||
sp.SetName(fmt.Sprintf("Call %s.%s", req.Service(), req.Method()))
|
||||
var labels []interface{}
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
labels = make([]tracer.Label, 0, len(md))
|
||||
labels = make([]interface{}, 0, len(md))
|
||||
for k, v := range md {
|
||||
labels = append(labels, tracer.LabelString(k, v))
|
||||
labels = append(labels, k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
labels = append(labels, tracer.LabelBool("error", true))
|
||||
labels = append(labels, "error", err.Error())
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
labels = append(labels, "kind", sp.Kind())
|
||||
sp.SetLabels(labels...)
|
||||
}
|
||||
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics"}
|
||||
DefaultSkipEndpoints = []string{"Meter.Metrics", "Health.Live", "Health.Ready", "Health.Version"}
|
||||
)
|
||||
|
||||
type tWrapper struct {
|
||||
@@ -231,7 +243,7 @@ func (ot *tWrapper) Call(ctx context.Context, req client.Request, rsp interface{
|
||||
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, endpoint)
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindClient))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
@@ -254,7 +266,7 @@ func (ot *tWrapper) Stream(ctx context.Context, req client.Request, opts ...clie
|
||||
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, endpoint)
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindClient))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
@@ -270,7 +282,7 @@ func (ot *tWrapper) Stream(ctx context.Context, req client.Request, opts ...clie
|
||||
func (ot *tWrapper) Publish(ctx context.Context, msg client.Message, opts ...client.PublishOption) error {
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, msg.Topic())
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindProducer))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
@@ -284,7 +296,7 @@ func (ot *tWrapper) Publish(ctx context.Context, msg client.Message, opts ...cli
|
||||
}
|
||||
|
||||
func (ot *tWrapper) ServerHandler(ctx context.Context, req server.Request, rsp interface{}) error {
|
||||
endpoint := req.Endpoint()
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Method())
|
||||
for _, ep := range ot.opts.SkipEndpoints {
|
||||
if ep == endpoint {
|
||||
return ot.serverHandler(ctx, req, rsp)
|
||||
@@ -293,7 +305,7 @@ func (ot *tWrapper) ServerHandler(ctx context.Context, req server.Request, rsp i
|
||||
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()))
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindServer))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
@@ -309,7 +321,7 @@ func (ot *tWrapper) ServerHandler(ctx context.Context, req server.Request, rsp i
|
||||
func (ot *tWrapper) ServerSubscriber(ctx context.Context, msg server.Message) error {
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, msg.Topic())
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindConsumer))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
@@ -347,7 +359,7 @@ func NewClientCallWrapper(opts ...Option) client.CallWrapper {
|
||||
}
|
||||
|
||||
func (ot *tWrapper) ClientCallFunc(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Method())
|
||||
for _, ep := range ot.opts.SkipEndpoints {
|
||||
if ep == endpoint {
|
||||
return ot.ClientCallFunc(ctx, addr, req, rsp, opts)
|
||||
@@ -356,7 +368,7 @@ func (ot *tWrapper) ClientCallFunc(ctx context.Context, addr string, req client.
|
||||
|
||||
sp, ok := tracer.SpanFromContext(ctx)
|
||||
if !ok {
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, endpoint)
|
||||
ctx, sp = ot.opts.Tracer.Start(ctx, "", tracer.WithSpanKind(tracer.SpanKindClient))
|
||||
}
|
||||
defer sp.Finish()
|
||||
|
||||
|
@@ -7,6 +7,7 @@ package http
|
||||
// Modified by Unistack LLC to support interface{} type handler and parameters in map[string]string
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
@@ -15,6 +16,11 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("route not found")
|
||||
ErrMethodNotAllowed = errors.New("method not allowed")
|
||||
)
|
||||
|
||||
type methodTyp uint
|
||||
|
||||
const (
|
||||
@@ -399,16 +405,19 @@ func (n *Trie) setEndpoint(method methodTyp, handler interface{}, pattern string
|
||||
}
|
||||
|
||||
// Search try to find element in tree with path and method
|
||||
func (n *Trie) Search(method string, path string) (interface{}, map[string]string, bool) {
|
||||
func (n *Trie) Search(method string, path string) (interface{}, map[string]string, error) {
|
||||
params := &routeParams{}
|
||||
// Find the routing handlers for the path
|
||||
rn := n.findRoute(params, methodMap[method], path)
|
||||
if rn == nil {
|
||||
return nil, nil, false
|
||||
if rn == nil && !params.methodNotAllowed {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
if params.methodNotAllowed {
|
||||
return nil, nil, ErrMethodNotAllowed
|
||||
}
|
||||
ep, ok := rn.endpoints[methodMap[method]]
|
||||
if !ok {
|
||||
return nil, nil, false
|
||||
return nil, nil, ErrMethodNotAllowed
|
||||
}
|
||||
|
||||
eparams := make(map[string]string, len(params.keys))
|
||||
@@ -416,12 +425,13 @@ func (n *Trie) Search(method string, path string) (interface{}, map[string]strin
|
||||
eparams[key] = params.vals[idx]
|
||||
}
|
||||
|
||||
return ep.handler, eparams, true
|
||||
return ep.handler, eparams, nil
|
||||
}
|
||||
|
||||
type routeParams struct {
|
||||
keys []string
|
||||
vals []string
|
||||
keys []string
|
||||
vals []string
|
||||
methodNotAllowed bool
|
||||
}
|
||||
|
||||
// Recursive edge traversal by checking all nodeTyp groups along the way.
|
||||
@@ -495,6 +505,7 @@ func (n *Trie) findRoute(params *routeParams, method methodTyp, path string) *Tr
|
||||
params.keys = append(params.keys, h.paramKeys...)
|
||||
return xn
|
||||
}
|
||||
params.methodNotAllowed = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,6 +541,7 @@ func (n *Trie) findRoute(params *routeParams, method methodTyp, path string) *Tr
|
||||
params.keys = append(params.keys, h.paramKeys...)
|
||||
return xn
|
||||
}
|
||||
params.methodNotAllowed = true
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -21,22 +21,22 @@ func TestTrieWildcardPathPrefix(t *testing.T) {
|
||||
if err = tr.Insert([]string{http.MethodPost}, "/v1/*", &handler{name: "post_create"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, _, ok := tr.Search(http.MethodPost, "/v1/test/one")
|
||||
if !ok {
|
||||
h, _, err := tr.Search(http.MethodPost, "/v1/test/one")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error handler not found")
|
||||
}
|
||||
if h.(*handler).name != "post_create" {
|
||||
t.Fatalf("invalid handler %v", h)
|
||||
}
|
||||
h, _, ok = tr.Search(http.MethodPost, "/v1/update")
|
||||
if !ok {
|
||||
h, _, err = tr.Search(http.MethodPost, "/v1/update")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error")
|
||||
}
|
||||
if h.(*handler).name != "post_update" {
|
||||
t.Fatalf("invalid handler %v", h)
|
||||
}
|
||||
h, _, ok = tr.Search(http.MethodPost, "/v1/update/some/{x}")
|
||||
if !ok {
|
||||
h, _, err = tr.Search(http.MethodPost, "/v1/update/some/{x}")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error")
|
||||
}
|
||||
if h.(*handler).name != "post_create" {
|
||||
@@ -52,8 +52,8 @@ func TestTriePathPrefix(t *testing.T) {
|
||||
_ = tr.Insert([]string{http.MethodPost}, "/v1/create/{id}", &handler{name: "post_create"})
|
||||
_ = tr.Insert([]string{http.MethodPost}, "/v1/update/{id}", &handler{name: "post_update"})
|
||||
_ = tr.Insert([]string{http.MethodPost}, "/", &handler{name: "post_wildcard"})
|
||||
h, _, ok := tr.Search(http.MethodPost, "/")
|
||||
if !ok {
|
||||
h, _, err := tr.Search(http.MethodPost, "/")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error")
|
||||
}
|
||||
if h.(*handler).name != "post_wildcard" {
|
||||
@@ -68,8 +68,8 @@ func TestTrieFixedPattern(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/{id}", &handler{name: "pattern"})
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/12", &handler{name: "fixed"})
|
||||
h, _, ok := tr.Search(http.MethodPut, "/v1/create/12")
|
||||
if !ok {
|
||||
h, _, err := tr.Search(http.MethodPut, "/v1/create/12")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error")
|
||||
}
|
||||
if h.(*handler).name != "fixed" {
|
||||
@@ -80,8 +80,8 @@ func TestTrieFixedPattern(t *testing.T) {
|
||||
func TestTrieNoMatchMethod(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/{id}", nil)
|
||||
_, _, ok := tr.Search(http.MethodPost, "/v1/create")
|
||||
if ok {
|
||||
_, _, err := tr.Search(http.MethodPost, "/v1/create")
|
||||
if err == nil && err != ErrNotFound {
|
||||
t.Fatalf("must be not found error")
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,9 @@ func TestTrieMatchRegexp(t *testing.T) {
|
||||
type handler struct{}
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/{category}/{id:[0-9]+}", &handler{})
|
||||
_, params, ok := tr.Search(http.MethodPut, "/v1/create/test_cat/12345")
|
||||
_, params, err := tr.Search(http.MethodPut, "/v1/create/test_cat/12345")
|
||||
switch {
|
||||
case !ok:
|
||||
case err != nil:
|
||||
t.Fatalf("route not found")
|
||||
case len(params) != 2:
|
||||
t.Fatalf("param matching error %v", params)
|
||||
@@ -105,8 +105,8 @@ func TestTrieMatchRegexpFail(t *testing.T) {
|
||||
type handler struct{}
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/{id:[a-z]+}", &handler{})
|
||||
_, _, ok := tr.Search(http.MethodPut, "/v1/create/12345")
|
||||
if ok {
|
||||
_, _, err := tr.Search(http.MethodPut, "/v1/create/12345")
|
||||
if err != ErrNotFound {
|
||||
t.Fatalf("route must not be not found")
|
||||
}
|
||||
}
|
||||
@@ -118,14 +118,28 @@ func TestTrieMatchLongest(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create", &handler{name: "first"})
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create/{id:[0-9]+}", &handler{name: "second"})
|
||||
if h, _, ok := tr.Search(http.MethodPut, "/v1/create/12345"); !ok {
|
||||
if h, _, err := tr.Search(http.MethodPut, "/v1/create/12345"); err != nil {
|
||||
t.Fatalf("route must be found")
|
||||
} else if h.(*handler).name != "second" {
|
||||
t.Fatalf("invalid handler found: %s != %s", h.(*handler).name, "second")
|
||||
}
|
||||
if h, _, ok := tr.Search(http.MethodPut, "/v1/create"); !ok {
|
||||
if h, _, err := tr.Search(http.MethodPut, "/v1/create"); err != nil {
|
||||
t.Fatalf("route must be found")
|
||||
} else if h.(*handler).name != "first" {
|
||||
t.Fatalf("invalid handler found: %s != %s", h.(*handler).name, "first")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMethodNotAllowed(t *testing.T) {
|
||||
type handler struct{}
|
||||
tr := NewTrie()
|
||||
_ = tr.Insert([]string{http.MethodPut}, "/v1/create", &handler{})
|
||||
_, _, err := tr.Search(http.MethodPost, "/v1/create")
|
||||
if err != ErrMethodNotAllowed {
|
||||
t.Fatalf("route must be method not allowed: %v", err)
|
||||
}
|
||||
_, _, err = tr.Search(http.MethodPut, "/v1/create")
|
||||
if err != nil {
|
||||
t.Fatalf("route must be found: %v", err)
|
||||
}
|
||||
}
|
||||
|
84
util/text/text.go
Normal file
84
util/text/text.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package text
|
||||
|
||||
|
||||
func DetectEncoding(text string) map[string]int {
|
||||
charsets := map[string]int{
|
||||
"UTF-8": 0,
|
||||
"CP1251": 0,
|
||||
"KOI8-R": 0,
|
||||
"IBM866": 0,
|
||||
"ISO-8859-5": 0,
|
||||
"MAC": 0,
|
||||
}
|
||||
|
||||
if len(text) == 0 {
|
||||
return charsets
|
||||
}
|
||||
|
||||
utflower := 7
|
||||
utfupper := 5
|
||||
lowercase := 3
|
||||
uppercase := 1
|
||||
last_simb := 0
|
||||
|
||||
for a := 0; a < len(text); a++ {
|
||||
char := int(text[a])
|
||||
|
||||
// non-russian characters
|
||||
if char < 128 || char > 256 {
|
||||
continue
|
||||
}
|
||||
|
||||
// UTF-8
|
||||
if (last_simb == 208) && ((char > 143 && char < 176) || char == 129) {
|
||||
charsets["UTF-8"] += (utfupper * 2)
|
||||
}
|
||||
if ((last_simb == 208) && ((char > 175 && char < 192) || char == 145)) || (last_simb == 209 && char > 127 && char < 144) {
|
||||
charsets["UTF-8"] += (utflower * 2)
|
||||
}
|
||||
|
||||
// CP1251
|
||||
if (char > 223 && char < 256) || char == 184 {
|
||||
charsets["CP1251"] += lowercase
|
||||
}
|
||||
if (char > 191 && char < 224) || char == 168 {
|
||||
charsets["CP1251"] += uppercase
|
||||
}
|
||||
|
||||
// KOI8-R
|
||||
if (char > 191 && char < 224) || char == 163 {
|
||||
charsets["KOI8-R"] += lowercase
|
||||
}
|
||||
if (char > 222 && char < 256) || char == 179 {
|
||||
charsets["KOI8-R"] += uppercase
|
||||
}
|
||||
|
||||
// IBM866
|
||||
if (char > 159 && char < 176) || (char > 223 && char < 241) {
|
||||
charsets["IBM866"] += lowercase
|
||||
}
|
||||
if (char > 127 && char < 160) || char == 241 {
|
||||
charsets["IBM866"] += uppercase
|
||||
}
|
||||
|
||||
// ISO-8859-5
|
||||
if (char > 207 && char < 240) || char == 161 {
|
||||
charsets["ISO-8859-5"] += lowercase
|
||||
}
|
||||
if (char > 175 && char < 208) || char == 241 {
|
||||
charsets["ISO-8859-5"] += uppercase
|
||||
}
|
||||
|
||||
// MAC
|
||||
if char > 221 && char < 255 {
|
||||
charsets["MAC"] += lowercase
|
||||
}
|
||||
if char > 127 && char < 160 {
|
||||
charsets["MAC"] += uppercase
|
||||
}
|
||||
|
||||
last_simb = char
|
||||
}
|
||||
|
||||
return charsets
|
||||
}
|
48
util/time/duration.go
Normal file
48
util/time/duration.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package time
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Duration int64
|
||||
|
||||
func ParseDuration(s string) (time.Duration, error) {
|
||||
if s == "" {
|
||||
return 0, fmt.Errorf(`time: invalid duration "` + s + `"`)
|
||||
}
|
||||
|
||||
//var sb strings.Builder
|
||||
/*
|
||||
for i, r := range s {
|
||||
switch r {
|
||||
case 'd':
|
||||
n, err := strconv.Atoi(s[idx:i])
|
||||
if err != nil {
|
||||
return 0, errors.New("time: invalid duration " + s)
|
||||
}
|
||||
s[idx:i] = fmt.Sprintf("%d", n*24)
|
||||
default:
|
||||
sb.WriteRune(r)
|
||||
}
|
||||
}
|
||||
*/
|
||||
var td time.Duration
|
||||
var err error
|
||||
switch s[len(s)-1] {
|
||||
case 's', 'm', 'h':
|
||||
td, err = time.ParseDuration(s)
|
||||
case 'd':
|
||||
if td, err = time.ParseDuration(s[:len(s)-1] + "h"); err == nil {
|
||||
td *= 24
|
||||
}
|
||||
case 'y':
|
||||
if td, err = time.ParseDuration(s[:len(s)-1] + "h"); err == nil {
|
||||
year := time.Date(time.Now().Year(), time.December, 31, 0, 0, 0, 0, time.Local)
|
||||
days := year.YearDay()
|
||||
td *= 24 * time.Duration(days)
|
||||
}
|
||||
}
|
||||
|
||||
return td, err
|
||||
}
|
27
util/time/duration_test.go
Normal file
27
util/time/duration_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package time
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseDuration(t *testing.T) {
|
||||
var td time.Duration
|
||||
var err error
|
||||
t.Skip()
|
||||
td, err = ParseDuration("14d4h")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseDuration error: %v", err)
|
||||
}
|
||||
if td.String() != "336h0m0s" {
|
||||
t.Fatalf("ParseDuration 14d != 336h0m0s : %s", td.String())
|
||||
}
|
||||
|
||||
td, err = ParseDuration("1y")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseDuration error: %v", err)
|
||||
}
|
||||
if td.String() != "8760h0m0s" {
|
||||
t.Fatalf("ParseDuration 1y != 8760h0m0s : %s", td.String())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user