Compare commits
58 Commits
Author | SHA1 | Date | |
---|---|---|---|
39f66cc86c | |||
bbbcb22565 | |||
cb70dfa664 | |||
1f0482fbd5 | |||
a862562284 | |||
c320c23913 | |||
|
ae848ba8bb | ||
|
8e264cbb3e | ||
|
54e523ab3f | ||
09973af099 | |||
3247da3dd0 | |||
b505455f7c | |||
293949f081 | |||
8d7e442b3a | |||
|
f7b5211af3 | ||
7eb6d030dc | |||
47e75c31c7 | |||
20ff5eed22 | |||
d23ca8db73 | |||
4dd28ac720 | |||
240b6016df | |||
cf2aa827e4 | |||
5596345382 | |||
67748a2132 | |||
c2333a9f35 | |||
4ec4c277b7 | |||
a11dd00174 | |||
cc7ebedf22 | |||
e5bf1448f4 | |||
f182bba6ff | |||
1f8810599b | |||
82248eb3b0 | |||
abb9937787 | |||
fd5ed64729 | |||
6751060d05 | |||
ef664607b4 | |||
62e482a14b | |||
a390ebf80f | |||
9a44960be7 | |||
c846c59b9b | |||
|
902bf6326b | ||
|
bddf3bf502 | ||
|
284131da98 | ||
927c7ea3c2 | |||
0e51a79bb6 | |||
1de9911b73 | |||
b4092c6619 | |||
024868bfd7 | |||
a0bbfd6d02 | |||
2cb6843773 | |||
87e1480077 | |||
bcd7f6a551 | |||
925b3af46b | |||
ef4efa6a6b | |||
125646d89b | |||
7af7649448 | |||
827d467077 | |||
ac8a3a12c4 |
20
.github/renovate.json
vendored
Normal file
20
.github/renovate.json
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": [
|
||||
"config:base"
|
||||
],
|
||||
"postUpdateOptions": ["gomodTidy"],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["minor", "patch", "pin", "digest"],
|
||||
"automerge": true
|
||||
},
|
||||
{
|
||||
"groupName": "all deps",
|
||||
"separateMajorMinor": true,
|
||||
"groupSlug": "all",
|
||||
"packagePatterns": [
|
||||
"*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
6
.github/workflows/build.yml
vendored
6
.github/workflows/build.yml
vendored
@@ -9,9 +9,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v1
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
go-version: 1.16
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v1
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
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.
|
||||
|
8
.github/workflows/pr.yml
vendored
8
.github/workflows/pr.yml
vendored
@@ -9,13 +9,13 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v1
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
go-version: 1.16
|
||||
- name: cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
path: ~/go/pkg
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: sdk checkout
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v1
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
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.
|
||||
|
@@ -1,8 +1,6 @@
|
||||
run:
|
||||
deadline: 5m
|
||||
modules-download-mode: readonly
|
||||
skip-dirs:
|
||||
- util/mdns.new
|
||||
skip-files:
|
||||
- ".*\\.pb\\.go$"
|
||||
- ".*\\.pb\\.micro\\.go$"
|
||||
@@ -30,11 +28,3 @@ linters:
|
||||
- interfacer
|
||||
- typecheck
|
||||
- dupl
|
||||
output:
|
||||
format: colored-line-number
|
||||
# print lines of code with issue, default is true
|
||||
print-issued-lines: true
|
||||
# print linter name in the end of issue text, default is true
|
||||
print-linter-name: true
|
||||
# make issues output unique by line, default is true
|
||||
uniq-by-line: true
|
||||
|
47
api/api.go
47
api/api.go
@@ -6,10 +6,11 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
// Api interface
|
||||
type Api interface {
|
||||
// Initialise options
|
||||
Init(...Option) error
|
||||
@@ -23,28 +24,30 @@ type Api interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
// Options holds the options
|
||||
type Options struct{}
|
||||
|
||||
// Option func signature
|
||||
type Option func(*Options) error
|
||||
|
||||
// Endpoint is a mapping between an RPC method and HTTP endpoint
|
||||
type Endpoint struct {
|
||||
// RPC Method e.g. Greeter.Hello
|
||||
// Name Greeter.Hello
|
||||
Name string
|
||||
// Description e.g what's this endpoint for
|
||||
// Desciption for endpoint
|
||||
Description string
|
||||
// API Handler e.g rpc, proxy
|
||||
// Handler e.g rpc, proxy
|
||||
Handler string
|
||||
// HTTP Host e.g example.com
|
||||
Host []string
|
||||
// HTTP Methods e.g GET, POST
|
||||
Method []string
|
||||
// HTTP Path e.g /greeter. Expect POSIX regex
|
||||
Path []string
|
||||
// Body destination
|
||||
// "*" or "" - top level message value
|
||||
// "string" - inner message value
|
||||
Body string
|
||||
// Host e.g example.com
|
||||
Host []string
|
||||
// Method e.g GET, POST
|
||||
Method []string
|
||||
// Path e.g /greeter. Expect POSIX regex
|
||||
Path []string
|
||||
// Stream flag
|
||||
Stream bool
|
||||
}
|
||||
@@ -53,26 +56,10 @@ type Endpoint struct {
|
||||
type Service struct {
|
||||
// Name of service
|
||||
Name string
|
||||
// The endpoint for this service
|
||||
// Endpoint for this service
|
||||
Endpoint *Endpoint
|
||||
// Versions of this service
|
||||
Services []*registry.Service
|
||||
}
|
||||
|
||||
func strip(s string) string {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func slice(s string) []string {
|
||||
var sl []string
|
||||
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if str := strip(p); len(str) > 0 {
|
||||
sl = append(sl, strip(p))
|
||||
}
|
||||
}
|
||||
|
||||
return sl
|
||||
// Services that provides service
|
||||
Services []*register.Service
|
||||
}
|
||||
|
||||
// Encode encodes an endpoint to endpoint metadata
|
||||
@@ -98,6 +85,7 @@ func Encode(e *Endpoint) map[string]string {
|
||||
set("method", strings.Join(e.Method, ","))
|
||||
set("path", strings.Join(e.Path, ","))
|
||||
set("host", strings.Join(e.Host, ","))
|
||||
set("body", e.Body)
|
||||
|
||||
return ep
|
||||
}
|
||||
@@ -118,6 +106,7 @@ func Decode(e metadata.Metadata) *Endpoint {
|
||||
ephost, _ := e.Get("host")
|
||||
ep.Host = []string{ephost}
|
||||
ep.Handler, _ = e.Get("handler")
|
||||
ep.Body, _ = e.Get("body")
|
||||
|
||||
return ep
|
||||
}
|
||||
|
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
//nolint:gocyclo
|
||||
func TestEncoding(t *testing.T) {
|
||||
testData := []*Endpoint{
|
||||
nil,
|
||||
|
@@ -1,121 +0,0 @@
|
||||
// Package api provides an http-rpc handler which provides the entire http request over rpc
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
goapi "github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
api "github.com/unistack-org/micro/v3/api/proto"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/errors"
|
||||
"github.com/unistack-org/micro/v3/util/ctx"
|
||||
"github.com/unistack-org/micro/v3/util/router"
|
||||
)
|
||||
|
||||
type apiHandler struct {
|
||||
opts handler.Options
|
||||
s *goapi.Service
|
||||
}
|
||||
|
||||
const (
|
||||
Handler = "api"
|
||||
)
|
||||
|
||||
// API handler is the default handler which takes api.Request and returns api.Response
|
||||
func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
bsize := handler.DefaultMaxRecvSize
|
||||
if a.opts.MaxRecvSize > 0 {
|
||||
bsize = a.opts.MaxRecvSize
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
||||
request, err := requestToProto(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
var service *goapi.Service
|
||||
|
||||
if a.s != nil {
|
||||
// we were given the service
|
||||
service = a.s
|
||||
} else if a.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := a.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
er := errors.InternalServerError("go.micro.api", "no route found")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// create request and response
|
||||
c := a.opts.Client
|
||||
req := c.NewRequest(service.Name, service.Endpoint.Name, request)
|
||||
rsp := &api.Response{}
|
||||
|
||||
// create the context from headers
|
||||
cx := ctx.FromRequest(r)
|
||||
|
||||
if err := c.Call(cx, req, rsp, client.WithRouter(router.New(service.Services))); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
ce := errors.Parse(err.Error())
|
||||
switch ce.Code {
|
||||
case 0:
|
||||
w.WriteHeader(500)
|
||||
default:
|
||||
w.WriteHeader(int(ce.Code))
|
||||
}
|
||||
w.Write([]byte(ce.Error()))
|
||||
return
|
||||
} else if rsp.StatusCode == 0 {
|
||||
rsp.StatusCode = http.StatusOK
|
||||
}
|
||||
|
||||
for _, header := range rsp.GetHeader() {
|
||||
for _, val := range header.Values {
|
||||
w.Header().Add(header.Key, val)
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.Header().Get("Content-Type")) == 0 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
w.WriteHeader(int(rsp.StatusCode))
|
||||
w.Write([]byte(rsp.Body))
|
||||
}
|
||||
|
||||
func (a *apiHandler) String() string {
|
||||
return "api"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *goapi.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,109 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/oxtoacart/bpool"
|
||||
api "github.com/unistack-org/micro/v3/api/proto"
|
||||
)
|
||||
|
||||
var (
|
||||
// need to calculate later to specify useful defaults
|
||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
||||
)
|
||||
|
||||
func requestToProto(r *http.Request) (*api.Request, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, fmt.Errorf("Error parsing form: %v", err)
|
||||
}
|
||||
|
||||
req := &api.Request{
|
||||
Path: r.URL.Path,
|
||||
Method: r.Method,
|
||||
Header: make(map[string]*api.Pair),
|
||||
Get: make(map[string]*api.Pair),
|
||||
Post: make(map[string]*api.Pair),
|
||||
Url: r.URL.String(),
|
||||
}
|
||||
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
ct = "text/plain; charset=UTF-8" //default CT is text/plain
|
||||
r.Header.Set("Content-Type", ct)
|
||||
}
|
||||
|
||||
//set the body:
|
||||
if r.Body != nil {
|
||||
switch ct {
|
||||
case "application/x-www-form-urlencoded":
|
||||
// expect form vals in Post data
|
||||
default:
|
||||
buf := bufferPool.Get()
|
||||
defer bufferPool.Put(buf)
|
||||
if _, err = buf.ReadFrom(r.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Body = buf.String()
|
||||
}
|
||||
}
|
||||
|
||||
// Set X-Forwarded-For if it does not exist
|
||||
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
ip = strings.Join(prior, ", ") + ", " + ip
|
||||
}
|
||||
|
||||
// Set the header
|
||||
req.Header["X-Forwarded-For"] = &api.Pair{
|
||||
Key: "X-Forwarded-For",
|
||||
Values: []string{ip},
|
||||
}
|
||||
}
|
||||
|
||||
// Host is stripped from net/http Headers so let's add it
|
||||
req.Header["Host"] = &api.Pair{
|
||||
Key: "Host",
|
||||
Values: []string{r.Host},
|
||||
}
|
||||
|
||||
// Get data
|
||||
for key, vals := range r.URL.Query() {
|
||||
header, ok := req.Get[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Get[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// Post data
|
||||
for key, vals := range r.PostForm {
|
||||
header, ok := req.Post[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Post[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
for key, vals := range r.Header {
|
||||
header, ok := req.Header[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
@@ -1,46 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequestToProto(t *testing.T) {
|
||||
testData := []*http.Request{
|
||||
{
|
||||
Method: "GET",
|
||||
Header: http.Header{
|
||||
"Header": []string{"test"},
|
||||
},
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: "localhost",
|
||||
Path: "/foo/bar",
|
||||
RawQuery: "param1=value1",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
p, err := requestToProto(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Path != d.URL.Path {
|
||||
t.Fatalf("Expected path %s got %s", d.URL.Path, p.Path)
|
||||
}
|
||||
if p.Method != d.Method {
|
||||
t.Fatalf("Expected method %s got %s", d.Method, p.Method)
|
||||
}
|
||||
for k, v := range d.Header {
|
||||
if val, ok := p.Header[k]; !ok {
|
||||
t.Fatalf("Expected header %s", k)
|
||||
} else {
|
||||
if val.Values[0] != v[0] {
|
||||
t.Fatalf("Expected val %s, got %s", val.Values[0], v[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,141 +0,0 @@
|
||||
// Package event provides a handler which publishes an event
|
||||
package event
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/oxtoacart/bpool"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
proto "github.com/unistack-org/micro/v3/api/proto"
|
||||
"github.com/unistack-org/micro/v3/util/ctx"
|
||||
)
|
||||
|
||||
var (
|
||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
||||
)
|
||||
|
||||
type event struct {
|
||||
opts handler.Options
|
||||
}
|
||||
|
||||
var (
|
||||
Handler = "event"
|
||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func eventName(parts []string) string {
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func evRoute(ns, p string) (string, string) {
|
||||
p = path.Clean(p)
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
|
||||
if len(p) == 0 {
|
||||
return ns, "event"
|
||||
}
|
||||
|
||||
parts := strings.Split(p, "/")
|
||||
|
||||
// no path
|
||||
if len(parts) == 0 {
|
||||
// topic: namespace
|
||||
// action: event
|
||||
return strings.Trim(ns, "."), "event"
|
||||
}
|
||||
|
||||
// Treat /v[0-9]+ as versioning
|
||||
// /v1/foo/bar => topic: v1.foo action: bar
|
||||
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
|
||||
topic := ns + "." + strings.Join(parts[:2], ".")
|
||||
action := eventName(parts[1:])
|
||||
return topic, action
|
||||
}
|
||||
|
||||
// /foo => topic: ns.foo action: foo
|
||||
// /foo/bar => topic: ns.foo action: bar
|
||||
topic := ns + "." + strings.Join(parts[:1], ".")
|
||||
action := eventName(parts[1:])
|
||||
|
||||
return topic, action
|
||||
}
|
||||
|
||||
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
bsize := handler.DefaultMaxRecvSize
|
||||
if e.opts.MaxRecvSize > 0 {
|
||||
bsize = e.opts.MaxRecvSize
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
||||
|
||||
// request to topic:event
|
||||
// create event
|
||||
// publish to topic
|
||||
|
||||
topic, action := evRoute(e.opts.Namespace, r.URL.Path)
|
||||
|
||||
// create event
|
||||
ev := &proto.Event{
|
||||
Name: action,
|
||||
// TODO: dedupe event
|
||||
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.New().String()),
|
||||
Header: make(map[string]*proto.Pair),
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
|
||||
// set headers
|
||||
for key, vals := range r.Header {
|
||||
header, ok := ev.Header[key]
|
||||
if !ok {
|
||||
header = &proto.Pair{
|
||||
Key: key,
|
||||
}
|
||||
ev.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// set body
|
||||
if r.Method == "GET" {
|
||||
bytes, _ := json.Marshal(r.URL.Query())
|
||||
ev.Data = string(bytes)
|
||||
} else {
|
||||
// Read body
|
||||
buf := bufferPool.Get()
|
||||
defer bufferPool.Put(buf)
|
||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
ev.Data = buf.String()
|
||||
}
|
||||
|
||||
// get client
|
||||
c := e.opts.Client
|
||||
|
||||
// create publication
|
||||
p := c.NewMessage(topic, ev)
|
||||
|
||||
// publish event
|
||||
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *event) String() string {
|
||||
return "event"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &event{
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
@@ -1,105 +0,0 @@
|
||||
// Package http is a http reverse proxy handler
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "http"
|
||||
)
|
||||
|
||||
type httpHandler struct {
|
||||
options handler.Options
|
||||
|
||||
// set with different initializer
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := h.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (h *httpHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if h.s != nil {
|
||||
// we were given the service
|
||||
service = h.s
|
||||
} else if h.options.Router != nil {
|
||||
// try get service from router
|
||||
s, err := h.options.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
if len(service.Services) == 0 {
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// get the nodes for this service
|
||||
nodes := make([]*registry.Node, 0, len(service.Services))
|
||||
for _, srv := range service.Services {
|
||||
nodes = append(nodes, srv.Nodes...)
|
||||
}
|
||||
|
||||
// select a random node
|
||||
node := nodes[rand.Int()%len(nodes)]
|
||||
|
||||
return fmt.Sprintf("http://%s", node.Address), nil
|
||||
}
|
||||
|
||||
func (h *httpHandler) String() string {
|
||||
return "http"
|
||||
}
|
||||
|
||||
// NewHandler returns a http proxy handler
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
// WithService creates a handler with a service
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,129 +0,0 @@
|
||||
// +build ignore
|
||||
|
||||
package http
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
"github.com/unistack-org/micro/v3/api/router"
|
||||
regRouter "github.com/unistack-org/micro/v3/api/router/registry"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/registry/memory"
|
||||
)
|
||||
|
||||
func testHttp(t *testing.T, path, service, ns string) {
|
||||
r := memory.NewRegistry()
|
||||
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
s := ®istry.Service{
|
||||
Name: service,
|
||||
Nodes: []*registry.Node{
|
||||
{
|
||||
Id: service + "-1",
|
||||
Address: l.Addr().String(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
r.Register(s)
|
||||
defer r.Deregister(s)
|
||||
|
||||
// setup the test handler
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`you got served`))
|
||||
})
|
||||
|
||||
// start http test serve
|
||||
go http.Serve(l, m)
|
||||
|
||||
// create new request and writer
|
||||
w := httptest.NewRecorder()
|
||||
req, err := http.NewRequest("POST", path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// initialise the handler
|
||||
rt := regRouter.NewRouter(
|
||||
router.WithHandler("http"),
|
||||
router.WithRegistry(r),
|
||||
router.WithResolver(vpath.NewResolver(
|
||||
resolver.WithServicePrefix(ns),
|
||||
)),
|
||||
)
|
||||
|
||||
p := NewHandler(handler.WithRouter(rt))
|
||||
|
||||
// execute the handler
|
||||
p.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if w.Body.String() != "you got served" {
|
||||
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttpHandler(t *testing.T) {
|
||||
testData := []struct {
|
||||
path string
|
||||
service string
|
||||
namespace string
|
||||
}{
|
||||
{
|
||||
"/test/foo",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/test/foo/baz",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"v2.baz",
|
||||
"",
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
t.Run(d.service, func(t *testing.T) {
|
||||
testHttp(t, d.path, d.service, d.namespace)
|
||||
})
|
||||
}
|
||||
}
|
@@ -3,24 +3,34 @@ package handler
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/api/router"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultMaxRecvSize specifies max recv size for handler
|
||||
DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb
|
||||
)
|
||||
|
||||
// Options struct holds handler options
|
||||
type Options struct {
|
||||
MaxRecvSize int64
|
||||
Namespace string
|
||||
Router router.Router
|
||||
Client client.Client
|
||||
Logger logger.Logger
|
||||
Namespace string
|
||||
MaxRecvSize int64
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions fills in the blanks
|
||||
// NewOptions creates new options struct and fills it
|
||||
func NewOptions(opts ...Option) Options {
|
||||
var options Options
|
||||
options := Options{
|
||||
Client: client.DefaultClient,
|
||||
Router: router.DefaultRouter,
|
||||
Logger: logger.DefaultLogger,
|
||||
MaxRecvSize: DefaultMaxRecvSize,
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
@@ -30,10 +40,6 @@ func NewOptions(opts ...Option) Options {
|
||||
WithNamespace("go.micro.api")(&options)
|
||||
}
|
||||
|
||||
if options.MaxRecvSize == 0 {
|
||||
options.MaxRecvSize = DefaultMaxRecvSize
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
@@ -51,6 +57,7 @@ func WithRouter(r router.Router) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithClient specifies client to be used by the handler
|
||||
func WithClient(c client.Client) Option {
|
||||
return func(o *Options) {
|
||||
o.Client = c
|
||||
|
@@ -1,182 +0,0 @@
|
||||
// Package web contains the web handler including websocket support
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
"github.com/unistack-org/micro/v3/api/handler"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "web"
|
||||
)
|
||||
|
||||
type webHandler struct {
|
||||
opts handler.Options
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := wh.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if isWebSocket(r) {
|
||||
wh.serveWebSocket(rp.Host, w, r)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (wh *webHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if wh.s != nil {
|
||||
// we were given the service
|
||||
service = wh.s
|
||||
} else if wh.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := wh.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// get the nodes
|
||||
nodes := make([]*registry.Node, 0, len(service.Services))
|
||||
for _, srv := range service.Services {
|
||||
nodes = append(nodes, srv.Nodes...)
|
||||
}
|
||||
|
||||
if len(nodes) == 0 {
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// select a random node
|
||||
node := nodes[rand.Int()%len(nodes)]
|
||||
|
||||
return fmt.Sprintf("http://%s", node.Address), nil
|
||||
}
|
||||
|
||||
// serveWebSocket used to serve a web socket proxied connection
|
||||
func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) {
|
||||
req := new(http.Request)
|
||||
*req = *r
|
||||
|
||||
if len(host) == 0 {
|
||||
http.Error(w, "invalid host", 500)
|
||||
return
|
||||
}
|
||||
|
||||
// set x-forward-for
|
||||
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if ips, ok := req.Header["X-Forwarded-For"]; ok {
|
||||
clientIP = strings.Join(ips, ", ") + ", " + clientIP
|
||||
}
|
||||
req.Header.Set("X-Forwarded-For", clientIP)
|
||||
}
|
||||
|
||||
// connect to the backend host
|
||||
conn, err := net.Dial("tcp", host)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// hijack the connection
|
||||
hj, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "failed to connect", 500)
|
||||
return
|
||||
}
|
||||
|
||||
nc, _, err := hj.Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
defer nc.Close()
|
||||
defer conn.Close()
|
||||
|
||||
if err = req.Write(conn); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
errCh := make(chan error, 2)
|
||||
|
||||
cp := func(dst io.Writer, src io.Reader) {
|
||||
_, err := io.Copy(dst, src)
|
||||
errCh <- err
|
||||
}
|
||||
|
||||
go cp(conn, nc)
|
||||
go cp(nc, conn)
|
||||
|
||||
<-errCh
|
||||
}
|
||||
|
||||
func isWebSocket(r *http.Request) bool {
|
||||
contains := func(key, val string) bool {
|
||||
vv := strings.Split(r.Header.Get(key), ",")
|
||||
for _, v := range vv {
|
||||
if val == strings.ToLower(strings.TrimSpace(v)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (wh *webHandler) String() string {
|
||||
return "web"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &webHandler{
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &webHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
package proto
|
||||
|
||||
type Message struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (m *Message) ProtoMessage() {}
|
||||
|
||||
func (m *Message) Reset() {
|
||||
*m = Message{}
|
||||
}
|
||||
|
||||
func (m *Message) String() string {
|
||||
return string(m.data)
|
||||
}
|
||||
|
||||
func (m *Message) Marshal() ([]byte, error) {
|
||||
return m.data, nil
|
||||
}
|
||||
|
||||
func (m *Message) Unmarshal(data []byte) error {
|
||||
m.data = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewMessage(data []byte) *Message {
|
||||
return &Message{data}
|
||||
}
|
@@ -1,511 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.25.0
|
||||
// protoc v3.6.1
|
||||
// source: api/proto/api.proto
|
||||
|
||||
package go_api
|
||||
|
||||
import (
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||
// of the legacy proto package is being used.
|
||||
const _ = proto.ProtoPackageIsVersion4
|
||||
|
||||
type Pair struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
||||
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Pair) Reset() {
|
||||
*x = Pair{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Pair) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Pair) ProtoMessage() {}
|
||||
|
||||
func (x *Pair) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Pair.ProtoReflect.Descriptor instead.
|
||||
func (*Pair) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Pair) GetKey() string {
|
||||
if x != nil {
|
||||
return x.Key
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Pair) GetValues() []string {
|
||||
if x != nil {
|
||||
return x.Values
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
type Request struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"` // raw request body; if not application/x-www-form-urlencoded
|
||||
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Request) Reset() {
|
||||
*x = Request{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Request) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Request) ProtoMessage() {}
|
||||
|
||||
func (x *Request) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
|
||||
func (*Request) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Request) GetMethod() string {
|
||||
if x != nil {
|
||||
return x.Method
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetPath() string {
|
||||
if x != nil {
|
||||
return x.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetGet() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Get
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetPost() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Post
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Request) GetBody() string {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetUrl() string {
|
||||
if x != nil {
|
||||
return x.Url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
type Response struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Response) Reset() {
|
||||
*x = Response{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Response) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Response) ProtoMessage() {}
|
||||
|
||||
func (x *Response) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
|
||||
func (*Response) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *Response) GetStatusCode() int32 {
|
||||
if x != nil {
|
||||
return x.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Response) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Response) GetBody() string {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
type Event struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// e.g login
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
// uuid
|
||||
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
|
||||
// unix timestamp of event
|
||||
Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
// event headers
|
||||
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
// the event data
|
||||
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Event) Reset() {
|
||||
*x = Event{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Event) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Event) ProtoMessage() {}
|
||||
|
||||
func (x *Event) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_api_proto_api_proto_msgTypes[3]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Event.ProtoReflect.Descriptor instead.
|
||||
func (*Event) Descriptor() ([]byte, []int) {
|
||||
return file_api_proto_api_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Event) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Event) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Event) GetTimestamp() int64 {
|
||||
if x != nil {
|
||||
return x.Timestamp
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Event) GetHeader() map[string]*Pair {
|
||||
if x != nil {
|
||||
return x.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Event) GetData() string {
|
||||
if x != nil {
|
||||
return x.Data
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_api_proto_api_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_api_proto_api_proto_rawDesc = []byte{
|
||||
0x0a, 0x13, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x22, 0x30, 0x0a,
|
||||
0x04, 0x50, 0x61, 0x69, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x22,
|
||||
0xc1, 0x03, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x6d,
|
||||
0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, 0x65, 0x74,
|
||||
0x68, 0x6f, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28,
|
||||
0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x33, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65,
|
||||
0x72, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69,
|
||||
0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45,
|
||||
0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x03,
|
||||
0x67, 0x65, 0x74, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x67, 0x6f, 0x2e, 0x61,
|
||||
0x70, 0x69, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x47, 0x65, 0x74, 0x45, 0x6e,
|
||||
0x74, 0x72, 0x79, 0x52, 0x03, 0x67, 0x65, 0x74, 0x12, 0x2d, 0x0a, 0x04, 0x70, 0x6f, 0x73, 0x74,
|
||||
0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72,
|
||||
0x79, 0x52, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18,
|
||||
0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x75,
|
||||
0x72, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x1a, 0x47, 0x0a,
|
||||
0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03,
|
||||
0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22,
|
||||
0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e,
|
||||
0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c,
|
||||
0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x44, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x45, 0x6e, 0x74,
|
||||
0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||
0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20,
|
||||
0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69,
|
||||
0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x45, 0x0a, 0x09,
|
||||
0x50, 0x6f, 0x73, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||
0x02, 0x38, 0x01, 0x22, 0xbd, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
|
||||
0x12, 0x1e, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x01,
|
||||
0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65,
|
||||
0x12, 0x34, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b,
|
||||
0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||
0x73, 0x65, 0x2e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06,
|
||||
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x03,
|
||||
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65,
|
||||
0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
|
||||
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76,
|
||||
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e,
|
||||
0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
|
||||
0x02, 0x38, 0x01, 0x22, 0xd9, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a,
|
||||
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
|
||||
0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69,
|
||||
0x64, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03,
|
||||
0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12,
|
||||
0x31, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32,
|
||||
0x19, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x48,
|
||||
0x65, 0x61, 0x64, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64,
|
||||
0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09,
|
||||
0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x47, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72,
|
||||
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x22, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x67, 0x6f, 0x2e, 0x61, 0x70, 0x69, 0x2e,
|
||||
0x50, 0x61, 0x69, 0x72, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x62,
|
||||
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_api_proto_api_proto_rawDescOnce sync.Once
|
||||
file_api_proto_api_proto_rawDescData = file_api_proto_api_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_api_proto_api_proto_rawDescGZIP() []byte {
|
||||
file_api_proto_api_proto_rawDescOnce.Do(func() {
|
||||
file_api_proto_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_api_proto_api_proto_rawDescData)
|
||||
})
|
||||
return file_api_proto_api_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_api_proto_api_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
|
||||
var file_api_proto_api_proto_goTypes = []interface{}{
|
||||
(*Pair)(nil), // 0: go.api.Pair
|
||||
(*Request)(nil), // 1: go.api.Request
|
||||
(*Response)(nil), // 2: go.api.Response
|
||||
(*Event)(nil), // 3: go.api.Event
|
||||
nil, // 4: go.api.Request.HeaderEntry
|
||||
nil, // 5: go.api.Request.GetEntry
|
||||
nil, // 6: go.api.Request.PostEntry
|
||||
nil, // 7: go.api.Response.HeaderEntry
|
||||
nil, // 8: go.api.Event.HeaderEntry
|
||||
}
|
||||
var file_api_proto_api_proto_depIdxs = []int32{
|
||||
4, // 0: go.api.Request.header:type_name -> go.api.Request.HeaderEntry
|
||||
5, // 1: go.api.Request.get:type_name -> go.api.Request.GetEntry
|
||||
6, // 2: go.api.Request.post:type_name -> go.api.Request.PostEntry
|
||||
7, // 3: go.api.Response.header:type_name -> go.api.Response.HeaderEntry
|
||||
8, // 4: go.api.Event.header:type_name -> go.api.Event.HeaderEntry
|
||||
0, // 5: go.api.Request.HeaderEntry.value:type_name -> go.api.Pair
|
||||
0, // 6: go.api.Request.GetEntry.value:type_name -> go.api.Pair
|
||||
0, // 7: go.api.Request.PostEntry.value:type_name -> go.api.Pair
|
||||
0, // 8: go.api.Response.HeaderEntry.value:type_name -> go.api.Pair
|
||||
0, // 9: go.api.Event.HeaderEntry.value:type_name -> go.api.Pair
|
||||
10, // [10:10] is the sub-list for method output_type
|
||||
10, // [10:10] is the sub-list for method input_type
|
||||
10, // [10:10] is the sub-list for extension type_name
|
||||
10, // [10:10] is the sub-list for extension extendee
|
||||
0, // [0:10] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_api_proto_api_proto_init() }
|
||||
func file_api_proto_api_proto_init() {
|
||||
if File_api_proto_api_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_api_proto_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Pair); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Request); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Response); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_api_proto_api_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Event); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_api_proto_api_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 9,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_api_proto_api_proto_goTypes,
|
||||
DependencyIndexes: file_api_proto_api_proto_depIdxs,
|
||||
MessageInfos: file_api_proto_api_proto_msgTypes,
|
||||
}.Build()
|
||||
File_api_proto_api_proto = out.File
|
||||
file_api_proto_api_proto_rawDesc = nil
|
||||
file_api_proto_api_proto_goTypes = nil
|
||||
file_api_proto_api_proto_depIdxs = nil
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
||||
// source: api/proto/api.proto
|
||||
|
||||
package go_api
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
math "math"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
@@ -1,43 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package go.api;
|
||||
|
||||
message Pair {
|
||||
string key = 1;
|
||||
repeated string values = 2;
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
message Request {
|
||||
string method = 1;
|
||||
string path = 2;
|
||||
map<string, Pair> header = 3;
|
||||
map<string, Pair> get = 4;
|
||||
map<string, Pair> post = 5;
|
||||
string body = 6; // raw request body; if not application/x-www-form-urlencoded
|
||||
string url = 7;
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
message Response {
|
||||
int32 statusCode = 1;
|
||||
map<string, Pair> header = 2;
|
||||
string body = 3;
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
message Event {
|
||||
// e.g login
|
||||
string name = 1;
|
||||
// uuid
|
||||
string id = 2;
|
||||
// unix timestamp of event
|
||||
int64 timestamp = 3;
|
||||
// event headers
|
||||
map<string, Pair> header = 4;
|
||||
// the event data
|
||||
string data = 5;
|
||||
}
|
@@ -7,11 +7,12 @@ import (
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct {
|
||||
type hostResolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve endpoint
|
||||
func (r *hostResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// parse options
|
||||
options := resolver.NewResolveOptions(opts...)
|
||||
|
||||
@@ -24,10 +25,11 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
func (r *hostResolver) String() string {
|
||||
return "host"
|
||||
}
|
||||
|
||||
// NewResolver creates new host api resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
return &hostResolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
@@ -3,14 +3,17 @@ package resolver
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
)
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
Handler string
|
||||
// Context is for external defined options
|
||||
Context context.Context
|
||||
// Handler name
|
||||
Handler string
|
||||
// ServicePrefix is the prefix
|
||||
ServicePrefix string
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Option func
|
||||
@@ -58,7 +61,7 @@ func Domain(n string) ResolveOption {
|
||||
|
||||
// NewResolveOptions returns new initialised resolve options
|
||||
func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
|
||||
options := ResolveOptions{Domain: registry.DefaultDomain}
|
||||
options := ResolveOptions{Domain: register.DefaultDomain}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
@@ -8,10 +8,12 @@ import (
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
// Resolver the path resolver
|
||||
type Resolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
// Resolve resolves endpoint
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// parse options
|
||||
options := resolver.NewResolveOptions(opts...)
|
||||
@@ -31,10 +33,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String retruns the string representation
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
}
|
||||
|
||||
// NewResolver returns new path resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
@@ -12,17 +12,19 @@ import (
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// NewResolver creates new subdomain api resolver
|
||||
func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver {
|
||||
options := resolver.NewOptions(opts...)
|
||||
return &Resolver{options, parent}
|
||||
return &subdomainResolver{options, parent}
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
type subdomainResolver struct {
|
||||
opts resolver.Options
|
||||
resolver.Resolver
|
||||
}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve resolve endpoint based on subdomain
|
||||
func (r *subdomainResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
if dom := r.Domain(req); len(dom) > 0 {
|
||||
opts = append(opts, resolver.Domain(dom))
|
||||
}
|
||||
@@ -30,7 +32,8 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
return r.Resolver.Resolve(req, opts...)
|
||||
}
|
||||
|
||||
func (r *Resolver) Domain(req *http.Request) string {
|
||||
// Domain returns domain
|
||||
func (r *subdomainResolver) Domain(req *http.Request) string {
|
||||
// determine the host, e.g. foobar.m3o.app
|
||||
host := req.URL.Hostname()
|
||||
if len(host) == 0 {
|
||||
@@ -82,6 +85,6 @@ func (r *Resolver) Domain(req *http.Request) string {
|
||||
return strings.Join(comps, "-")
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
func (r *subdomainResolver) String() string {
|
||||
return "subdomain"
|
||||
}
|
||||
|
@@ -6,8 +6,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestResolve(t *testing.T) {
|
||||
@@ -62,9 +60,13 @@ func TestResolve(t *testing.T) {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
r := NewResolver(vpath.NewResolver())
|
||||
result, err := r.Resolve(&http.Request{URL: &url.URL{Host: tc.Host, Path: "foo/bar"}})
|
||||
assert.Nil(t, err, "Expecter err to be nil")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result != nil {
|
||||
assert.Equal(t, tc.Result, result.Domain, "Expected %v but got %v", tc.Result, result.Domain)
|
||||
if tc.Result != result.Domain {
|
||||
t.Fatalf("Expected %v but got %v", tc.Result, result.Domain)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@@ -10,11 +10,12 @@ import (
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
)
|
||||
|
||||
// NewResolver creates new vpath api resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
||||
return &vpathResolver{opts: resolver.NewOptions(opts...)}
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
type vpathResolver struct {
|
||||
opts resolver.Options
|
||||
}
|
||||
|
||||
@@ -22,7 +23,8 @@ var (
|
||||
re = regexp.MustCompile("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
// Resolve endpoint
|
||||
func (r *vpathResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
||||
if req.URL.Path == "/" {
|
||||
return nil, errors.New("unknown name")
|
||||
}
|
||||
@@ -60,12 +62,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
func (r *vpathResolver) String() string {
|
||||
return "vpath"
|
||||
}
|
||||
|
||||
// withPrefix transforms "foo" into "go.micro.api.foo"
|
||||
func (r *Resolver) withPrefix(parts ...string) string {
|
||||
func (r *vpathResolver) withPrefix(parts ...string) string {
|
||||
p := r.opts.ServicePrefix
|
||||
if len(p) > 0 {
|
||||
parts = append([]string{p}, parts...)
|
||||
|
@@ -6,19 +6,27 @@ import (
|
||||
"github.com/unistack-org/micro/v3/api/resolver"
|
||||
"github.com/unistack-org/micro/v3/api/resolver/vpath"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
)
|
||||
|
||||
// Options holds the options for api router
|
||||
type Options struct {
|
||||
Handler string
|
||||
Registry registry.Registry
|
||||
// Register for service lookup
|
||||
Register register.Register
|
||||
// Resolver to use
|
||||
Resolver resolver.Resolver
|
||||
Logger logger.Logger
|
||||
Context context.Context
|
||||
// Logger micro logger
|
||||
Logger logger.Logger
|
||||
// Context is for external options
|
||||
Context context.Context
|
||||
// Handler name
|
||||
Handler string
|
||||
}
|
||||
|
||||
// Option func signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions returns options struct filled by opts
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
@@ -52,10 +60,10 @@ func WithHandler(h string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithRegistry sets the registry
|
||||
func WithRegistry(r registry.Registry) Option {
|
||||
// WithRegister sets the register
|
||||
func WithRegister(r register.Register) Option {
|
||||
return func(o *Options) {
|
||||
o.Registry = r
|
||||
o.Register = r
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -7,6 +7,11 @@ import (
|
||||
"github.com/unistack-org/micro/v3/api"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultRouter contains default router implementation
|
||||
DefaultRouter Router
|
||||
)
|
||||
|
||||
// Router is used to determine an endpoint for a request
|
||||
type Router interface {
|
||||
// Returns options
|
||||
@@ -23,6 +28,6 @@ type Router interface {
|
||||
Deregister(ep *api.Endpoint) error
|
||||
// Route returns an api.Service route
|
||||
Route(r *http.Request) (*api.Service, error)
|
||||
// String represenation of router
|
||||
// String representation of router
|
||||
String() string
|
||||
}
|
||||
|
35
auth/auth.go
35
auth/auth.go
@@ -19,6 +19,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultAuth holds default auth implementation
|
||||
DefaultAuth Auth = NewAuth()
|
||||
// ErrInvalidToken is when the token provided is not valid
|
||||
ErrInvalidToken = errors.New("invalid token provided")
|
||||
@@ -52,30 +53,30 @@ type Auth interface {
|
||||
|
||||
// Account provided by an auth provider
|
||||
type Account struct {
|
||||
// ID of the account e.g. email
|
||||
// Metadata any other associated metadata
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// ID of the account e.g. email or uuid
|
||||
ID string `json:"id"`
|
||||
// Type of the account, e.g. service
|
||||
Type string `json:"type"`
|
||||
// Issuer of the account
|
||||
Issuer string `json:"issuer"`
|
||||
// Any other associated metadata
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// Scopes the account has access to
|
||||
Scopes []string `json:"scopes"`
|
||||
// Secret for the account, e.g. the password
|
||||
Secret string `json:"secret"`
|
||||
// Scopes the account has access to
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
|
||||
// Token can be short or long lived
|
||||
type Token struct {
|
||||
// The token to be used for accessing resources
|
||||
AccessToken string `json:"access_token"`
|
||||
// RefreshToken to be used to generate a new token
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
// Time of token creation
|
||||
Created time.Time `json:"created"`
|
||||
// Time of token expiry
|
||||
Expiry time.Time `json:"expiry"`
|
||||
// The token to be used for accessing resources
|
||||
AccessToken string `json:"access_token"`
|
||||
// RefreshToken to be used to generate a new token
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// Expired returns a boolean indicating if the token needs to be refreshed
|
||||
@@ -105,17 +106,15 @@ const (
|
||||
|
||||
// Rule is used to verify access to a resource
|
||||
type Rule struct {
|
||||
// ID of the rule, e.g. "public"
|
||||
ID string
|
||||
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
|
||||
// applies to any valid account
|
||||
Scope string
|
||||
// Resource the rule applies to
|
||||
// Resource that rule belongs to
|
||||
Resource *Resource
|
||||
// Access determines if the rule grants or denies access to the resource
|
||||
// ID of the rule
|
||||
ID string
|
||||
// Scope of the rule
|
||||
Scope string
|
||||
// Access flag allow/deny
|
||||
Access Access
|
||||
// Priority the rule should take when verifying a request, the higher the value the sooner the
|
||||
// rule will be applied
|
||||
// Priority holds the rule priority
|
||||
Priority int32
|
||||
}
|
||||
|
||||
|
@@ -24,33 +24,36 @@ func NewOptions(opts ...Option) Options {
|
||||
return options
|
||||
}
|
||||
|
||||
// Options struct holds auth options
|
||||
type Options struct {
|
||||
// Issuer of the service's account
|
||||
Issuer string
|
||||
// ID is the services auth ID
|
||||
ID string
|
||||
// Secret is used to authenticate the service
|
||||
Secret string
|
||||
// Context holds the external options
|
||||
Context context.Context
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Store used for stre data
|
||||
Store store.Store
|
||||
// Token is the services token used to authenticate itself
|
||||
Token *Token
|
||||
// PublicKey for decoding JWTs
|
||||
PublicKey string
|
||||
// PrivateKey for encoding JWTs
|
||||
PrivateKey string
|
||||
// LoginURL is the relative url path where a user can login
|
||||
LoginURL string
|
||||
// Store to back auth
|
||||
Store store.Store
|
||||
// PrivateKey for encoding JWTs
|
||||
PrivateKey string
|
||||
// PublicKey for decoding JWTs
|
||||
PublicKey string
|
||||
// Secret is used to authenticate the service
|
||||
Secret string
|
||||
// ID is the services auth ID
|
||||
ID string
|
||||
// Issuer of the service's account
|
||||
Issuer string
|
||||
// Name holds the auth name
|
||||
Name string
|
||||
// Addrs sets the addresses of auth
|
||||
Addrs []string
|
||||
// Logger sets the logger
|
||||
Logger logger.Logger
|
||||
// Meter sets tht meter
|
||||
Meter meter.Meter
|
||||
// Tracer
|
||||
Tracer tracer.Tracer
|
||||
// Context to store other options
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Option func
|
||||
@@ -63,6 +66,13 @@ func Addrs(addrs ...string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// Issuer of the services account
|
||||
func Issuer(i string) Option {
|
||||
return func(o *Options) {
|
||||
@@ -115,18 +125,12 @@ func LoginURL(url string) Option {
|
||||
|
||||
// GenerateOptions struct
|
||||
type GenerateOptions struct {
|
||||
// Metadata associated with the account
|
||||
Metadata metadata.Metadata
|
||||
// Scopes the account has access too
|
||||
Scopes []string
|
||||
// Provider of the account, e.g. oauth
|
||||
Provider string
|
||||
// Type of the account, e.g. user
|
||||
Type string
|
||||
// Secret used to authenticate the account
|
||||
Secret string
|
||||
// Issuer of the account, e.g. micro
|
||||
Issuer string
|
||||
Type string
|
||||
Secret string
|
||||
Issuer string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
// GenerateOption func
|
||||
@@ -185,16 +189,11 @@ func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
||||
|
||||
// TokenOptions struct
|
||||
type TokenOptions struct {
|
||||
// ID for the account
|
||||
ID string
|
||||
// Secret for the account
|
||||
Secret string
|
||||
// RefreshToken is used to refesh a token
|
||||
ID string
|
||||
Secret string
|
||||
RefreshToken string
|
||||
// Expiry is the time the token should live for
|
||||
Expiry time.Duration
|
||||
// Issuer of the account
|
||||
Issuer string
|
||||
Issuer string
|
||||
Expiry time.Duration
|
||||
}
|
||||
|
||||
// TokenOption func
|
||||
|
@@ -9,6 +9,7 @@ import (
|
||||
// VerifyAccess an account has access to a resource using the rules provided. If the account does not have
|
||||
// access an error will be returned. If there are no rules provided which match the resource, an error
|
||||
// will be returned
|
||||
//nolint:gocyclo
|
||||
func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error {
|
||||
// the rule is only to be applied if the type matches the resource or is catch-all (*)
|
||||
validTypes := []string{"*", res.Type}
|
||||
|
@@ -14,6 +14,7 @@ var (
|
||||
|
||||
// Broker is an interface used for asynchronous messaging.
|
||||
type Broker interface {
|
||||
Name() string
|
||||
Init(...Option) error
|
||||
Options() Options
|
||||
Address() string
|
||||
|
243
broker/memory.go
Normal file
243
broker/memory.go
Normal file
@@ -0,0 +1,243 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
maddr "github.com/unistack-org/micro/v3/util/addr"
|
||||
mnet "github.com/unistack-org/micro/v3/util/net"
|
||||
"github.com/unistack-org/micro/v3/util/rand"
|
||||
)
|
||||
|
||||
type memoryBroker struct {
|
||||
opts Options
|
||||
Subscribers map[string][]*memorySubscriber
|
||||
addr string
|
||||
sync.RWMutex
|
||||
connected bool
|
||||
}
|
||||
|
||||
type memoryEvent struct {
|
||||
opts Options
|
||||
err error
|
||||
message interface{}
|
||||
topic string
|
||||
}
|
||||
|
||||
type memorySubscriber struct {
|
||||
opts SubscribeOptions
|
||||
ctx context.Context
|
||||
exit chan bool
|
||||
handler Handler
|
||||
id string
|
||||
topic string
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Options() Options {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Address() string {
|
||||
return m.addr
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Connect(ctx context.Context) error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if m.connected {
|
||||
return nil
|
||||
}
|
||||
|
||||
// use 127.0.0.1 to avoid scan of all network interfaces
|
||||
addr, err := maddr.Extract("127.0.0.1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rng rand.Rand
|
||||
i := rng.Intn(20000)
|
||||
// set addr with port
|
||||
addr = mnet.HostPort(addr, 10000+i)
|
||||
|
||||
m.addr = addr
|
||||
m.connected = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Disconnect(ctx context.Context) error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if !m.connected {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.connected = false
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error {
|
||||
m.RLock()
|
||||
if !m.connected {
|
||||
m.RUnlock()
|
||||
return errors.New("not connected")
|
||||
}
|
||||
|
||||
subs, ok := m.Subscribers[topic]
|
||||
m.RUnlock()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
var v interface{}
|
||||
if m.opts.Codec != nil {
|
||||
buf, err := m.opts.Codec.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v = buf
|
||||
} else {
|
||||
v = msg
|
||||
}
|
||||
|
||||
p := &memoryEvent{
|
||||
topic: topic,
|
||||
message: v,
|
||||
opts: m.opts,
|
||||
}
|
||||
|
||||
eh := m.opts.ErrorHandler
|
||||
|
||||
for _, sub := range subs {
|
||||
if err := sub.handler(p); err != nil {
|
||||
p.err = err
|
||||
if sub.opts.ErrorHandler != nil {
|
||||
eh = sub.opts.ErrorHandler
|
||||
}
|
||||
if eh != nil {
|
||||
eh(p)
|
||||
} else if m.opts.Logger.V(logger.ErrorLevel) {
|
||||
m.opts.Logger.Error(m.opts.Context, err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Subscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||
m.RLock()
|
||||
if !m.connected {
|
||||
m.RUnlock()
|
||||
return nil, errors.New("not connected")
|
||||
}
|
||||
m.RUnlock()
|
||||
|
||||
options := NewSubscribeOptions(opts...)
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sub := &memorySubscriber{
|
||||
exit: make(chan bool, 1),
|
||||
id: id.String(),
|
||||
topic: topic,
|
||||
handler: handler,
|
||||
opts: options,
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
m.Lock()
|
||||
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
|
||||
m.Unlock()
|
||||
|
||||
go func() {
|
||||
<-sub.exit
|
||||
m.Lock()
|
||||
var newSubscribers []*memorySubscriber
|
||||
for _, sb := range m.Subscribers[topic] {
|
||||
if sb.id == sub.id {
|
||||
continue
|
||||
}
|
||||
newSubscribers = append(newSubscribers, sb)
|
||||
}
|
||||
m.Subscribers[topic] = newSubscribers
|
||||
m.Unlock()
|
||||
}()
|
||||
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
func (m *memoryBroker) String() string {
|
||||
return "memory"
|
||||
}
|
||||
|
||||
func (m *memoryBroker) Name() string {
|
||||
return m.opts.Name
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Topic() string {
|
||||
return m.topic
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Message() *Message {
|
||||
switch v := m.message.(type) {
|
||||
case *Message:
|
||||
return v
|
||||
case []byte:
|
||||
msg := &Message{}
|
||||
if err := m.opts.Codec.Unmarshal(v, msg); err != nil {
|
||||
if m.opts.Logger.V(logger.ErrorLevel) {
|
||||
m.opts.Logger.Error(m.opts.Context, "[memory]: failed to unmarshal: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Ack() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryEvent) Error() error {
|
||||
return m.err
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Options() SubscribeOptions {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Topic() string {
|
||||
return m.topic
|
||||
}
|
||||
|
||||
func (m *memorySubscriber) Unsubscribe(ctx context.Context) error {
|
||||
m.exit <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewBroker return new memory broker
|
||||
func NewBroker(opts ...Option) Broker {
|
||||
return &memoryBroker{
|
||||
opts: NewOptions(opts...),
|
||||
Subscribers: make(map[string][]*memorySubscriber),
|
||||
}
|
||||
}
|
50
broker/memory_test.go
Normal file
50
broker/memory_test.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMemoryBroker(t *testing.T) {
|
||||
b := NewBroker()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := b.Connect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
|
||||
topic := "test"
|
||||
count := 10
|
||||
|
||||
fn := func(p Event) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
sub, err := b.Subscribe(ctx, topic, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error subscribing %v", err)
|
||||
}
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
message := &Message{
|
||||
Header: map[string]string{
|
||||
"foo": "bar",
|
||||
"id": fmt.Sprintf("%d", i),
|
||||
},
|
||||
Body: []byte(`hello world`),
|
||||
}
|
||||
|
||||
if err := b.Publish(ctx, topic, message); err != nil {
|
||||
t.Fatalf("Unexpected error publishing %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
if err := sub.Unsubscribe(ctx); err != nil {
|
||||
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
||||
}
|
||||
|
||||
if err := b.Disconnect(ctx); err != nil {
|
||||
t.Fatalf("Unexpected connect error %v", err)
|
||||
}
|
||||
}
|
@@ -1,77 +0,0 @@
|
||||
package broker
|
||||
|
||||
import "context"
|
||||
|
||||
type noopBroker struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
type noopSubscriber struct {
|
||||
topic string
|
||||
opts SubscribeOptions
|
||||
}
|
||||
|
||||
// NewBroker returns new noop broker
|
||||
func NewBroker(opts ...Option) Broker {
|
||||
return &noopBroker{opts: NewOptions(opts...)}
|
||||
}
|
||||
|
||||
// Init initialize broker
|
||||
func (n *noopBroker) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&n.opts)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options returns broker Options
|
||||
func (n *noopBroker) Options() Options {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
// Address returns broker address
|
||||
func (n *noopBroker) Address() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Connect connects to broker
|
||||
func (n *noopBroker) Connect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Disconnect disconnects from broker
|
||||
func (n *noopBroker) Disconnect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Publish publishes message to broker
|
||||
func (n *noopBroker) Publish(ctx context.Context, topic string, m *Message, opts ...PublishOption) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Subscribe subscribes to broker topic
|
||||
func (n *noopBroker) Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||
options := NewSubscribeOptions(opts...)
|
||||
return &noopSubscriber{topic: topic, opts: options}, nil
|
||||
}
|
||||
|
||||
// String return broker string representation
|
||||
func (n *noopBroker) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
// Options returns subscriber options
|
||||
func (n *noopSubscriber) Options() SubscribeOptions {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
// TOpic returns subscriber topic
|
||||
func (n *noopSubscriber) Topic() string {
|
||||
return n.topic
|
||||
}
|
||||
|
||||
// Unsubscribe unsbscribes from broker topic
|
||||
func (n *noopSubscriber) Unsubscribe(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
@@ -7,36 +7,38 @@ import (
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options struct
|
||||
type Options struct {
|
||||
// Addrs useed by broker
|
||||
Addrs []string
|
||||
// ErrorHandler executed when errors occur processing messages
|
||||
ErrorHandler Handler
|
||||
// Codec used to marshal/unmarshal messages
|
||||
Codec codec.Codec
|
||||
// Logger the used logger
|
||||
Logger logger.Logger
|
||||
// Meter the used for metrics
|
||||
Meter meter.Meter
|
||||
// Tracer used for trace
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// TLSConfig for secure communication
|
||||
TLSConfig *tls.Config
|
||||
// Registry used for clustering
|
||||
Registry registry.Registry
|
||||
// Context is used for non default options
|
||||
// Register can be used for clustering
|
||||
Register register.Register
|
||||
// Codec holds the codec for marshal/unmarshal
|
||||
Codec codec.Codec
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// TLSConfig holds tls.TLSConfig options
|
||||
TLSConfig *tls.Config
|
||||
// ErrorHandler used when broker can't unmarshal incoming message
|
||||
ErrorHandler Handler
|
||||
// Name holds the broker name
|
||||
Name string
|
||||
// Addrs holds the broker address
|
||||
Addrs []string
|
||||
}
|
||||
|
||||
// NewOptions create new Options
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Registry: registry.DefaultRegistry,
|
||||
Register: register.DefaultRegister,
|
||||
Logger: logger.DefaultLogger,
|
||||
Context: context.Background(),
|
||||
Meter: meter.DefaultMeter,
|
||||
@@ -58,10 +60,10 @@ func Context(ctx context.Context) Option {
|
||||
|
||||
// PublishOptions struct
|
||||
type PublishOptions struct {
|
||||
// BodyOnly says that only body of the message must be published
|
||||
BodyOnly bool
|
||||
// Context for non default options
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// BodyOnly flag says the message contains raw body bytes
|
||||
BodyOnly bool
|
||||
}
|
||||
|
||||
// NewPublishOptions creates PublishOptions struct
|
||||
@@ -79,22 +81,16 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
|
||||
|
||||
// SubscribeOptions struct
|
||||
type SubscribeOptions struct {
|
||||
// AutoAck ack messages if handler returns nil err
|
||||
AutoAck bool
|
||||
|
||||
// ErrorHandler executed when errors occur processing messages
|
||||
ErrorHandler Handler
|
||||
|
||||
// Group for subscriber, Subscribers with the same group name
|
||||
// will create a shared subscription where each
|
||||
// receives a subset of messages.
|
||||
Group string
|
||||
|
||||
// BodyOnly says that consumed only body of the message
|
||||
BodyOnly bool
|
||||
|
||||
// Context is used for non default options
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// ErrorHandler used when broker can't unmarshal incoming message
|
||||
ErrorHandler Handler
|
||||
// Group holds consumer group
|
||||
Group string
|
||||
// AutoAck flag specifies auto ack of incoming message when no error happens
|
||||
AutoAck bool
|
||||
// BodyOnly flag specifies that message contains only body bytes without header
|
||||
BodyOnly bool
|
||||
}
|
||||
|
||||
// Option func
|
||||
@@ -202,10 +198,10 @@ func SubscribeGroup(name string) SubscribeOption {
|
||||
}
|
||||
}
|
||||
|
||||
// Registry sets registry option
|
||||
func Registry(r registry.Registry) Option {
|
||||
// Register sets register option
|
||||
func Register(r register.Register) Option {
|
||||
return func(o *Options) {
|
||||
o.Registry = r
|
||||
o.Register = r
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,6 +233,13 @@ func Meter(m meter.Meter) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeContext set context
|
||||
func SubscribeContext(ctx context.Context) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
|
@@ -21,12 +21,12 @@ type Source struct {
|
||||
|
||||
// Package is packaged format for source
|
||||
type Package struct {
|
||||
// Source of the package
|
||||
Source *Source
|
||||
// Name of the package
|
||||
Name string
|
||||
// Location of the package
|
||||
Path string
|
||||
// Type of package e.g tarball, binary, docker
|
||||
Type string
|
||||
// Source of the package
|
||||
Source *Source
|
||||
}
|
||||
|
@@ -12,16 +12,31 @@ import (
|
||||
var (
|
||||
// DefaultClient is the global default client
|
||||
DefaultClient Client = NewClient()
|
||||
// DefaultContentType is the default content-type if not specified
|
||||
DefaultContentType = "application/json"
|
||||
// DefaultBackoff is the default backoff function for retries
|
||||
DefaultBackoff = exponentialBackoff
|
||||
// DefaultRetry is the default check-for-retry function for retries
|
||||
DefaultRetry = RetryNever
|
||||
// DefaultRetries is the default number of times a request is tried
|
||||
DefaultRetries = 0
|
||||
// DefaultRequestTimeout is the default request timeout
|
||||
DefaultRequestTimeout = time.Second * 5
|
||||
// DefaultPoolSize sets the connection pool size
|
||||
DefaultPoolSize = 100
|
||||
// DefaultPoolTTL sets the connection pool ttl
|
||||
DefaultPoolTTL = time.Minute
|
||||
)
|
||||
|
||||
// Client is the interface used to make requests to services.
|
||||
// It supports Request/Response via Transport and Publishing via the Broker.
|
||||
// It also supports bidirectional streaming of requests.
|
||||
type Client interface {
|
||||
Init(...Option) error
|
||||
Name() string
|
||||
Init(opts ...Option) error
|
||||
Options() Options
|
||||
NewMessage(topic string, msg interface{}, opts ...MessageOption) Message
|
||||
NewRequest(service, endpoint string, req interface{}, reqOpts ...RequestOption) Request
|
||||
NewRequest(service string, endpoint string, req interface{}, opts ...RequestOption) Request
|
||||
Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error
|
||||
Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error)
|
||||
Publish(ctx context.Context, msg Message, opts ...PublishOption) error
|
||||
@@ -72,9 +87,9 @@ type Stream interface {
|
||||
// The response read
|
||||
Response() Response
|
||||
// Send will encode and send a request
|
||||
Send(interface{}) error
|
||||
Send(msg interface{}) error
|
||||
// Recv will decode and read a response
|
||||
Recv(interface{}) error
|
||||
Recv(msg interface{}) error
|
||||
// Error returns the stream error
|
||||
Error() error
|
||||
// Close closes the stream
|
||||
@@ -95,18 +110,3 @@ type MessageOption func(*MessageOptions)
|
||||
|
||||
// RequestOption used by NewRequest
|
||||
type RequestOption func(*RequestOptions)
|
||||
|
||||
var (
|
||||
// DefaultBackoff is the default backoff function for retries
|
||||
DefaultBackoff = exponentialBackoff
|
||||
// DefaultRetry is the default check-for-retry function for retries
|
||||
DefaultRetry = RetryNever
|
||||
// DefaultRetries is the default number of times a request is tried
|
||||
DefaultRetries = 0
|
||||
// DefaultRequestTimeout is the default request timeout
|
||||
DefaultRequestTimeout = time.Second * 5
|
||||
// DefaultPoolSize sets the connection pool size
|
||||
DefaultPoolSize = 100
|
||||
// DefaultPoolTTL sets the connection pool ttl
|
||||
DefaultPoolTTL = time.Minute
|
||||
)
|
||||
|
@@ -20,10 +20,6 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
defaultContentType = "application/json"
|
||||
)
|
||||
|
||||
type noopClient struct {
|
||||
opts Options
|
||||
}
|
||||
@@ -35,18 +31,31 @@ type noopMessage struct {
|
||||
}
|
||||
|
||||
type noopRequest struct {
|
||||
body interface{}
|
||||
codec codec.Codec
|
||||
service string
|
||||
method string
|
||||
endpoint string
|
||||
contentType string
|
||||
body interface{}
|
||||
codec codec.Codec
|
||||
stream bool
|
||||
}
|
||||
|
||||
// NewClient returns new noop client
|
||||
func NewClient(opts ...Option) Client {
|
||||
return &noopClient{opts: NewOptions(opts...)}
|
||||
nc := &noopClient{opts: NewOptions(opts...)}
|
||||
// wrap in reverse
|
||||
|
||||
c := Client(nc)
|
||||
|
||||
for i := len(nc.opts.Wrappers); i > 0; i-- {
|
||||
c = nc.opts.Wrappers[i-1](c)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (n *noopClient) Name() string {
|
||||
return n.opts.Name
|
||||
}
|
||||
|
||||
func (n *noopRequest) Service() string {
|
||||
@@ -166,7 +175,7 @@ func (n *noopClient) Call(ctx context.Context, req Request, rsp interface{}, opt
|
||||
}
|
||||
|
||||
func (n *noopClient) NewRequest(service, endpoint string, req interface{}, opts ...RequestOption) Request {
|
||||
return &noopRequest{}
|
||||
return &noopRequest{service: service, endpoint: endpoint}
|
||||
}
|
||||
|
||||
func (n *noopClient) NewMessage(topic string, msg interface{}, opts ...MessageOption) Message {
|
||||
@@ -183,7 +192,7 @@ func (n *noopClient) Publish(ctx context.Context, p Message, opts ...PublishOpti
|
||||
|
||||
options := NewPublishOptions(opts...)
|
||||
|
||||
md, ok := metadata.FromContext(ctx)
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(0)
|
||||
}
|
||||
|
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/network/transport"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/router"
|
||||
"github.com/unistack-org/micro/v3/selector"
|
||||
"github.com/unistack-org/micro/v3/selector/random"
|
||||
@@ -18,34 +18,40 @@ import (
|
||||
|
||||
// Options holds client options
|
||||
type Options struct {
|
||||
// Used to select codec
|
||||
ContentType string
|
||||
// Proxy address to send requests via
|
||||
Proxy string
|
||||
|
||||
// Plugged interfaces
|
||||
Broker broker.Broker
|
||||
Codecs map[string]codec.Codec
|
||||
Router router.Router
|
||||
Selector selector.Selector
|
||||
Transport transport.Transport
|
||||
Logger logger.Logger
|
||||
Meter meter.Meter
|
||||
// Lookup used for looking up routes
|
||||
Lookup LookupFunc
|
||||
|
||||
// Connection Pool
|
||||
PoolSize int
|
||||
PoolTTL time.Duration
|
||||
Tracer tracer.Tracer
|
||||
// Wrapper that used client
|
||||
Wrappers []Wrapper
|
||||
|
||||
// CallOptions that used by default
|
||||
// CallOptions contains default CallOptions
|
||||
CallOptions CallOptions
|
||||
|
||||
// Context is used for non default options
|
||||
// Logger used to log messages
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Broker used to publish messages
|
||||
Broker broker.Broker
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Router used to get route
|
||||
Router router.Router
|
||||
// Selector used to select needed address
|
||||
Selector selector.Selector
|
||||
// Transport used for transfer messages
|
||||
Transport transport.Transport
|
||||
// Context is used for external options
|
||||
Context context.Context
|
||||
// Codecs map
|
||||
Codecs map[string]codec.Codec
|
||||
// Lookup func used to get destination addr
|
||||
Lookup LookupFunc
|
||||
// Proxy is used for proxy requests
|
||||
Proxy string
|
||||
// ContentType is Used to select codec
|
||||
ContentType string
|
||||
// Name is the client name
|
||||
Name string
|
||||
// Wrappers contains wrappers
|
||||
Wrappers []Wrapper
|
||||
// PoolSize connection pool size
|
||||
PoolSize int
|
||||
// PoolTTL conection pool ttl
|
||||
PoolTTL time.Duration
|
||||
}
|
||||
|
||||
// NewCallOptions creates new call options struct
|
||||
@@ -59,34 +65,34 @@ func NewCallOptions(opts ...CallOption) CallOptions {
|
||||
|
||||
// CallOptions holds client call options
|
||||
type CallOptions struct {
|
||||
// Address of remote hosts
|
||||
Address []string
|
||||
// Backoff func
|
||||
Backoff BackoffFunc
|
||||
// Transport Dial Timeout
|
||||
DialTimeout time.Duration
|
||||
// Number of Call attempts
|
||||
Retries int
|
||||
// Check if retriable func
|
||||
Retry RetryFunc
|
||||
// Request/Response timeout
|
||||
RequestTimeout time.Duration
|
||||
// Router to use for this call
|
||||
// Router used for route
|
||||
Router router.Router
|
||||
// Selector to use for the call
|
||||
// Selector selects addr
|
||||
Selector selector.Selector
|
||||
// SelectOptions to use when selecting a route
|
||||
SelectOptions []selector.SelectOption
|
||||
// Stream timeout for the stream
|
||||
StreamTimeout time.Duration
|
||||
// Use the auth token as the authorization header
|
||||
AuthToken bool
|
||||
// Network to lookup the route within
|
||||
Network string
|
||||
// Middleware for low level call func
|
||||
CallWrappers []CallWrapper
|
||||
// Context is uded for non default options
|
||||
// Context used for deadline
|
||||
Context context.Context
|
||||
// Retry func used for retries
|
||||
Retry RetryFunc
|
||||
// Backoff func used for backoff when retry
|
||||
Backoff BackoffFunc
|
||||
// Network name
|
||||
Network string
|
||||
// CallWrappers call wrappers
|
||||
CallWrappers []CallWrapper
|
||||
// SelectOptions selector options
|
||||
SelectOptions []selector.SelectOption
|
||||
// Address specifies static addr list
|
||||
Address []string
|
||||
// Retries specifies retries num
|
||||
Retries int
|
||||
// StreamTimeout stream timeout
|
||||
StreamTimeout time.Duration
|
||||
// RequestTimeout request timeout
|
||||
RequestTimeout time.Duration
|
||||
// DialTimeout dial timeout
|
||||
DialTimeout time.Duration
|
||||
// AuthToken flag
|
||||
AuthToken bool
|
||||
}
|
||||
|
||||
// Context pass context to client
|
||||
@@ -107,11 +113,10 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions {
|
||||
|
||||
// PublishOptions holds publish options
|
||||
type PublishOptions struct {
|
||||
// Exchange is the routing exchange for the message
|
||||
Exchange string
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// Exchange topic exchange name
|
||||
Exchange string
|
||||
}
|
||||
|
||||
// NewMessageOptions creates message options struct
|
||||
@@ -125,6 +130,7 @@ func NewMessageOptions(opts ...MessageOption) MessageOptions {
|
||||
|
||||
// MessageOptions holds client message options
|
||||
type MessageOptions struct {
|
||||
// ContentType specify content-type of message
|
||||
ContentType string
|
||||
}
|
||||
|
||||
@@ -139,18 +145,19 @@ func NewRequestOptions(opts ...RequestOption) RequestOptions {
|
||||
|
||||
// RequestOptions holds client request options
|
||||
type RequestOptions struct {
|
||||
ContentType string
|
||||
Stream bool
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// ContentType specify content-type of message
|
||||
ContentType string
|
||||
// Stream flag
|
||||
Stream bool
|
||||
}
|
||||
|
||||
// NewOptions creates new options struct
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
ContentType: "application/json",
|
||||
ContentType: DefaultContentType,
|
||||
Codecs: make(map[string]codec.Codec),
|
||||
CallOptions: CallOptions{
|
||||
Backoff: DefaultBackoff,
|
||||
@@ -211,7 +218,7 @@ func Codec(contentType string, c codec.Codec) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Default content type of the client
|
||||
// ContentType used by default if not specified
|
||||
func ContentType(ct string) Option {
|
||||
return func(o *Options) {
|
||||
o.ContentType = ct
|
||||
@@ -246,11 +253,11 @@ func Transport(t transport.Transport) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Registry sets the routers registry
|
||||
func Registry(r registry.Registry) Option {
|
||||
// Register sets the routers register
|
||||
func Register(r register.Register) Option {
|
||||
return func(o *Options) {
|
||||
if o.Router != nil {
|
||||
o.Router.Init(router.Registry(r))
|
||||
o.Router.Init(router.Register(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -269,28 +276,34 @@ func Selector(s selector.Selector) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a Wrapper to a list of options passed into the client
|
||||
// Wrap adds a wrapper to the list of options passed into the client
|
||||
func Wrap(w Wrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Wrappers = append(o.Wrappers, w)
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a Wrapper to the list of CallFunc wrappers
|
||||
// WrapCall adds a wrapper to the list of CallFunc wrappers
|
||||
func WrapCall(cw ...CallWrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.CallWrappers = append(o.CallOptions.CallWrappers, cw...)
|
||||
}
|
||||
}
|
||||
|
||||
// Backoff is used to set the backoff function used
|
||||
// when retrying Calls
|
||||
// Backoff is used to set the backoff function used when retrying Calls
|
||||
func Backoff(fn BackoffFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.Backoff = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the client name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup sets the lookup function to use for resolving service names
|
||||
func Lookup(l LookupFunc) Option {
|
||||
return func(o *Options) {
|
||||
@@ -299,7 +312,6 @@ func Lookup(l LookupFunc) Option {
|
||||
}
|
||||
|
||||
// Retries sets the retry count when making the request.
|
||||
// Should this be a Call Option?
|
||||
func Retries(i int) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.Retries = i
|
||||
@@ -314,7 +326,6 @@ func Retry(fn RetryFunc) Option {
|
||||
}
|
||||
|
||||
// RequestTimeout is the request timeout.
|
||||
// Should this be a Call Option?
|
||||
func RequestTimeout(d time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.RequestTimeout = d
|
||||
@@ -328,15 +339,13 @@ func StreamTimeout(d time.Duration) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Transport dial timeout
|
||||
// DialTimeout sets the dial timeout
|
||||
func DialTimeout(d time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.CallOptions.DialTimeout = d
|
||||
}
|
||||
}
|
||||
|
||||
// Call Options
|
||||
|
||||
// WithExchange sets the exchange to route a message through
|
||||
func WithExchange(e string) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
@@ -455,8 +464,6 @@ func WithMessageContentType(ct string) MessageOption {
|
||||
}
|
||||
}
|
||||
|
||||
// Request Options
|
||||
|
||||
// WithContentType specifies request content type
|
||||
func WithContentType(ct string) RequestOption {
|
||||
return func(o *RequestOptions) {
|
||||
|
@@ -5,13 +5,13 @@ import (
|
||||
)
|
||||
|
||||
type testRequest struct {
|
||||
service string
|
||||
opts RequestOptions
|
||||
codec codec.Codec
|
||||
body interface{}
|
||||
method string
|
||||
endpoint string
|
||||
contentType string
|
||||
codec codec.Codec
|
||||
body interface{}
|
||||
opts RequestOptions
|
||||
service string
|
||||
}
|
||||
|
||||
func (r *testRequest) ContentType() string {
|
||||
|
@@ -8,8 +8,8 @@ import (
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// Message types
|
||||
const (
|
||||
// Message types
|
||||
Error MessageType = iota
|
||||
Request
|
||||
Response
|
||||
@@ -25,11 +25,12 @@ var (
|
||||
|
||||
var (
|
||||
// DefaultMaxMsgSize specifies how much data codec can handle
|
||||
DefaultMaxMsgSize int = 1024 * 1024 * 4 // 4Mb
|
||||
DefaultCodec Codec = NewCodec()
|
||||
DefaultMaxMsgSize int = 1024 * 1024 * 4 // 4Mb
|
||||
// DefaultCodec is the global default codec
|
||||
DefaultCodec Codec = NewCodec()
|
||||
)
|
||||
|
||||
// MessageType
|
||||
// MessageType specifies message type for codec
|
||||
type MessageType int
|
||||
|
||||
// Codec encodes/decodes various types of messages used within micro.
|
||||
@@ -50,16 +51,14 @@ type Codec interface {
|
||||
// the communication, likely followed by the body.
|
||||
// In the case of an error, body may be nil.
|
||||
type Message struct {
|
||||
Id string
|
||||
Type MessageType
|
||||
Header metadata.Metadata
|
||||
Target string
|
||||
Method string
|
||||
Endpoint string
|
||||
Error string
|
||||
|
||||
// The values read from the socket
|
||||
Header metadata.Metadata
|
||||
Body []byte
|
||||
Id string
|
||||
Body []byte
|
||||
Type MessageType
|
||||
}
|
||||
|
||||
// NewMessage creates new codec message
|
||||
|
@@ -1,8 +1,8 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
type noopCodec struct {
|
||||
@@ -19,7 +19,7 @@ func (c *noopCodec) ReadHeader(conn io.Reader, m *Message, t MessageType) error
|
||||
|
||||
func (c *noopCodec) ReadBody(conn io.Reader, b interface{}) error {
|
||||
// read bytes
|
||||
buf, err := ioutil.ReadAll(conn)
|
||||
buf, err := io.ReadAll(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -29,18 +29,14 @@ func (c *noopCodec) ReadBody(conn io.Reader, b interface{}) error {
|
||||
}
|
||||
|
||||
switch v := b.(type) {
|
||||
case string:
|
||||
v = string(buf)
|
||||
case *string:
|
||||
*v = string(buf)
|
||||
case []byte:
|
||||
v = buf
|
||||
case *[]byte:
|
||||
*v = buf
|
||||
case *Frame:
|
||||
v.Data = buf
|
||||
default:
|
||||
return ErrInvalidMessage
|
||||
return json.Unmarshal(buf, v)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -64,7 +60,11 @@ func (c *noopCodec) Write(conn io.Writer, m *Message, b interface{}) error {
|
||||
case []byte:
|
||||
v = vb
|
||||
default:
|
||||
return ErrInvalidMessage
|
||||
var err error
|
||||
v, err = json.Marshal(vb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := conn.Write(v)
|
||||
return err
|
||||
@@ -98,30 +98,28 @@ func (c *noopCodec) Marshal(v interface{}) ([]byte, error) {
|
||||
case *Message:
|
||||
return ve.Body, nil
|
||||
}
|
||||
return nil, ErrInvalidMessage
|
||||
|
||||
return json.Marshal(v)
|
||||
}
|
||||
|
||||
func (c *noopCodec) Unmarshal(d []byte, v interface{}) error {
|
||||
var err error
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
switch ve := v.(type) {
|
||||
case string:
|
||||
ve = string(d)
|
||||
case *string:
|
||||
*ve = string(d)
|
||||
case []byte:
|
||||
ve = d
|
||||
return nil
|
||||
case *[]byte:
|
||||
*ve = d
|
||||
return nil
|
||||
case *Frame:
|
||||
ve.Data = d
|
||||
return nil
|
||||
case *Message:
|
||||
ve.Body = d
|
||||
default:
|
||||
err = ErrInvalidMessage
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
return json.Unmarshal(d, v)
|
||||
}
|
||||
|
34
codec/noop_test.go
Normal file
34
codec/noop_test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNoopBytes(t *testing.T) {
|
||||
req := []byte("test req")
|
||||
rsp := make([]byte, len(req))
|
||||
|
||||
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
|
||||
|
||||
nc := NewCodec()
|
||||
if err := nc.Unmarshal(req, &rsp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(req, []byte(rsp)) {
|
||||
t.Fatalf("req not eq rsp: %s != %s", req, rsp)
|
||||
}
|
||||
}
|
@@ -11,10 +11,14 @@ type Option func(*Options)
|
||||
|
||||
// Options contains codec options
|
||||
type Options struct {
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// MaxMsgSize specifies max messages size that reads by codec
|
||||
MaxMsgSize int
|
||||
Meter meter.Meter
|
||||
Logger logger.Logger
|
||||
Tracer tracer.Tracer
|
||||
}
|
||||
|
||||
// MaxMsgSize sets the max message size
|
||||
@@ -45,6 +49,7 @@ func Meter(m meter.Meter) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// NewOptions returns new options
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
|
@@ -22,6 +22,7 @@ var (
|
||||
|
||||
// Config is an interface abstraction for dynamic configuration
|
||||
type Config interface {
|
||||
Name() string
|
||||
// Init the config
|
||||
Init(opts ...Option) error
|
||||
// Options in the config
|
||||
|
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
type configKey struct{}
|
||||
|
||||
// FromContext returns store from context
|
||||
func FromContext(ctx context.Context) (Config, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
@@ -14,6 +15,7 @@ func FromContext(ctx context.Context) (Config, bool) {
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// NewContext put store in context
|
||||
func NewContext(ctx context.Context, c Config) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
|
@@ -53,6 +53,7 @@ func (c *defaultConfig) Load(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:gocyclo
|
||||
func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val string) error {
|
||||
if !rutil.IsEmpty(value) {
|
||||
return nil
|
||||
@@ -107,7 +108,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(float64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case reflect.Int:
|
||||
v, err := strconv.ParseInt(val, 10, 0)
|
||||
if err != nil {
|
||||
@@ -137,7 +138,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(int64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
case reflect.Uint:
|
||||
v, err := strconv.ParseUint(val, 10, 0)
|
||||
if err != nil {
|
||||
@@ -167,7 +168,7 @@ func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value.Set(reflect.ValueOf(uint64(v)))
|
||||
value.Set(reflect.ValueOf(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -251,6 +252,11 @@ func (c *defaultConfig) String() string {
|
||||
return "default"
|
||||
}
|
||||
|
||||
func (c *defaultConfig) Name() string {
|
||||
return c.opts.Name
|
||||
}
|
||||
|
||||
// NewConfig returns new default config source
|
||||
func NewConfig(opts ...Option) Config {
|
||||
options := NewOptions(opts...)
|
||||
if len(options.StructTag) == 0 {
|
||||
|
@@ -9,30 +9,40 @@ import (
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options hold the config options
|
||||
type Options struct {
|
||||
AllowFail bool
|
||||
BeforeLoad []func(context.Context, Config) error
|
||||
AfterLoad []func(context.Context, Config) error
|
||||
BeforeSave []func(context.Context, Config) error
|
||||
AfterSave []func(context.Context, Config) error
|
||||
// Struct that holds config data
|
||||
// Struct holds the destination config struct
|
||||
Struct interface{}
|
||||
// StructTag name
|
||||
StructTag string
|
||||
// Logger that will be used
|
||||
Logger logger.Logger
|
||||
// Meter that will be used
|
||||
Meter meter.Meter
|
||||
// Tracer used for trace
|
||||
Tracer tracer.Tracer
|
||||
// Codec that used for load/save
|
||||
Codec codec.Codec
|
||||
// Context for alternative data
|
||||
// Tracer that will be used
|
||||
Tracer tracer.Tracer
|
||||
// Meter that will be used
|
||||
Meter meter.Meter
|
||||
// Logger that will be used
|
||||
Logger logger.Logger
|
||||
// Context used for external options
|
||||
Context context.Context
|
||||
// Name of the config
|
||||
Name string
|
||||
// StructTag name
|
||||
StructTag string
|
||||
// BeforeSave contains slice of funcs that runs before save
|
||||
BeforeSave []func(context.Context, Config) error
|
||||
// AfterLoad contains slice of funcs that runs after load
|
||||
AfterLoad []func(context.Context, Config) error
|
||||
// BeforeLoad contains slice of funcs that runs before load
|
||||
BeforeLoad []func(context.Context, Config) error
|
||||
// AfterSave contains slice of funcs that runs after save
|
||||
AfterSave []func(context.Context, Config) error
|
||||
// AllowFail flag to allow fail in config source
|
||||
AllowFail bool
|
||||
}
|
||||
|
||||
// Option function signature
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions new options struct with filed values
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
@@ -47,36 +57,42 @@ func NewOptions(opts ...Option) Options {
|
||||
return options
|
||||
}
|
||||
|
||||
// AllowFail allows config source to fail
|
||||
func AllowFail(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.AllowFail = b
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeLoad run funcs before config load
|
||||
func BeforeLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.BeforeLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// AfterLoad run funcs after config load
|
||||
func AfterLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.AfterLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeSave run funcs before save
|
||||
func BeforeSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.BeforeSave = fn
|
||||
}
|
||||
}
|
||||
|
||||
// AfterSave run fncs after save
|
||||
func AfterSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.AfterSave = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Context pass context
|
||||
func Context(ctx context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = ctx
|
||||
@@ -90,6 +106,7 @@ func Codec(c codec.Codec) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Logger sets the logger
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
@@ -110,9 +127,16 @@ func Struct(v interface{}) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// StructTag
|
||||
// StructTag sets the struct tag that used for filling
|
||||
func StructTag(name string) Option {
|
||||
return func(o *Options) {
|
||||
o.StructTag = name
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
22
context.go
Normal file
22
context.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package micro
|
||||
|
||||
import "context"
|
||||
|
||||
type serviceKey struct{}
|
||||
|
||||
// FromContext retrieves a Service from the Context.
|
||||
func FromContext(ctx context.Context) (Service, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
s, ok := ctx.Value(serviceKey{}).(Service)
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// NewContext returns a new Context with the Service embedded within it.
|
||||
func NewContext(ctx context.Context, s Service) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, serviceKey{}, s)
|
||||
}
|
@@ -1,2 +0,0 @@
|
||||
// Package debug provides interfaces for service debugging
|
||||
package debug
|
@@ -1,190 +0,0 @@
|
||||
// Package kubernetes is a logger implementing (github.com/unistack-org/micro/v3/debug/log).Log
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/util/kubernetes/client"
|
||||
)
|
||||
|
||||
type klog struct {
|
||||
client client.Client
|
||||
|
||||
log.Options
|
||||
}
|
||||
|
||||
func (k *klog) podLogStream(podName string, stream *kubeStream) {
|
||||
p := make(map[string]string)
|
||||
p["follow"] = "true"
|
||||
|
||||
// get the logs for the pod
|
||||
body, err := k.client.Log(&client.Resource{
|
||||
Name: podName,
|
||||
Kind: "pod",
|
||||
}, client.LogParams(p))
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
s := bufio.NewScanner(body)
|
||||
defer body.Close()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stream.stop:
|
||||
return
|
||||
default:
|
||||
if s.Scan() {
|
||||
record := k.parse(s.Text())
|
||||
stream.stream <- record
|
||||
} else {
|
||||
// TODO: is there a blocking call
|
||||
// rather than a sleep loop?
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (k *klog) getMatchingPods() ([]string, error) {
|
||||
r := &client.Resource{
|
||||
Kind: "pod",
|
||||
Value: new(client.PodList),
|
||||
}
|
||||
|
||||
l := make(map[string]string)
|
||||
|
||||
l["name"] = client.Format(k.Options.Name)
|
||||
// TODO: specify micro:service
|
||||
// l["micro"] = "service"
|
||||
|
||||
if err := k.client.Get(r, client.GetLabels(l)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var matches []string
|
||||
|
||||
for _, p := range r.Value.(*client.PodList).Items {
|
||||
// find labels that match the name
|
||||
if p.Metadata.Labels["name"] == client.Format(k.Options.Name) {
|
||||
matches = append(matches, p.Metadata.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
func (k *klog) parse(line string) log.Record {
|
||||
record := log.Record{}
|
||||
|
||||
if err := json.Unmarshal([]byte(line), &record); err != nil {
|
||||
record.Timestamp = time.Now().UTC()
|
||||
record.Message = line
|
||||
record.Metadata = metadata.New(1)
|
||||
}
|
||||
|
||||
record.Metadata["service"] = k.Options.Name
|
||||
|
||||
return record
|
||||
}
|
||||
|
||||
func (k *klog) Read(options ...log.ReadOption) ([]log.Record, error) {
|
||||
opts := &log.ReadOptions{}
|
||||
for _, o := range options {
|
||||
o(opts)
|
||||
}
|
||||
pods, err := k.getMatchingPods()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var records []log.Record
|
||||
|
||||
for _, pod := range pods {
|
||||
logParams := make(map[string]string)
|
||||
|
||||
if !opts.Since.Equal(time.Time{}) {
|
||||
logParams["sinceSeconds"] = strconv.Itoa(int(time.Since(opts.Since).Seconds()))
|
||||
}
|
||||
|
||||
if opts.Count != 0 {
|
||||
logParams["tailLines"] = strconv.Itoa(opts.Count)
|
||||
}
|
||||
|
||||
if opts.Stream {
|
||||
logParams["follow"] = "true"
|
||||
}
|
||||
|
||||
logs, err := k.client.Log(&client.Resource{
|
||||
Name: pod,
|
||||
Kind: "pod",
|
||||
}, client.LogParams(logParams))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer logs.Close()
|
||||
|
||||
s := bufio.NewScanner(logs)
|
||||
|
||||
for s.Scan() {
|
||||
record := k.parse(s.Text())
|
||||
record.Metadata["pod"] = pod
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
|
||||
// sort the records
|
||||
sort.Slice(records, func(i, j int) bool { return records[i].Timestamp.Before(records[j].Timestamp) })
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (k *klog) Write(l log.Record) error {
|
||||
return write(l)
|
||||
}
|
||||
|
||||
func (k *klog) Stream() (log.Stream, error) {
|
||||
// find the matching pods
|
||||
pods, err := k.getMatchingPods()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := &kubeStream{
|
||||
stream: make(chan log.Record),
|
||||
stop: make(chan bool),
|
||||
}
|
||||
|
||||
// stream from the individual pods
|
||||
for _, pod := range pods {
|
||||
go k.podLogStream(pod, stream)
|
||||
}
|
||||
|
||||
return stream, nil
|
||||
}
|
||||
|
||||
// NewLog returns a configured Kubernetes logger
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
klog := &klog{}
|
||||
for _, o := range opts {
|
||||
o(&klog.Options)
|
||||
}
|
||||
|
||||
if len(os.Getenv("KUBERNETES_SERVICE_HOST")) > 0 {
|
||||
klog.client = client.NewClusterClient()
|
||||
} else {
|
||||
klog.client = client.NewLocalClient()
|
||||
}
|
||||
return klog
|
||||
}
|
@@ -1,71 +0,0 @@
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func TestKubernetes(t *testing.T) {
|
||||
if len(os.Getenv("INTEGRATION_TESTS")) > 0 {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
k := NewLog(log.Name("micro-network"))
|
||||
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := os.Stderr
|
||||
os.Stderr = w
|
||||
meta := make(map[string]string)
|
||||
|
||||
write := log.Record{
|
||||
Timestamp: time.Unix(0, 0).UTC(),
|
||||
Message: "Test log entry",
|
||||
Metadata: meta,
|
||||
}
|
||||
|
||||
meta["foo"] = "bar"
|
||||
|
||||
k.Write(write)
|
||||
b := &bytes.Buffer{}
|
||||
w.Close()
|
||||
io.Copy(b, r)
|
||||
os.Stderr = s
|
||||
|
||||
var read log.Record
|
||||
|
||||
if err := json.Unmarshal(b.Bytes(), &read); err != nil {
|
||||
t.Fatalf("json.Unmarshal failed: %s", err.Error())
|
||||
}
|
||||
|
||||
assert.Equal(t, write, read, "Write was not equal")
|
||||
|
||||
records, err := k.Read()
|
||||
assert.Nil(t, err, "Read should not error")
|
||||
assert.NotNil(t, records, "Read should return records")
|
||||
|
||||
stream, err := k.Stream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
records = nil
|
||||
|
||||
go stream.Stop()
|
||||
|
||||
for s := range stream.Chan() {
|
||||
records = append(records, s)
|
||||
}
|
||||
|
||||
assert.Equal(t, 0, len(records), "Stream should return nothing")
|
||||
}
|
@@ -1,44 +0,0 @@
|
||||
package kubernetes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func write(l log.Record) error {
|
||||
m, err := json.Marshal(l)
|
||||
if err == nil {
|
||||
_, err := fmt.Fprintf(os.Stderr, "%s", m)
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type kubeStream struct {
|
||||
// the k8s log stream
|
||||
stream chan log.Record
|
||||
sync.Mutex
|
||||
// the stop chan
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func (k *kubeStream) Chan() <-chan log.Record {
|
||||
return k.stream
|
||||
}
|
||||
|
||||
func (k *kubeStream) Stop() error {
|
||||
k.Lock()
|
||||
defer k.Unlock()
|
||||
select {
|
||||
case <-k.stop:
|
||||
return nil
|
||||
default:
|
||||
close(k.stop)
|
||||
close(k.stream)
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -1,58 +0,0 @@
|
||||
// Package log provides debug logging
|
||||
package log
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// Default buffer size if any
|
||||
DefaultSize = 256
|
||||
// Default formatter
|
||||
DefaultFormat = TextFormat
|
||||
)
|
||||
|
||||
// Log is debug log interface for reading and writing logs
|
||||
type Log interface {
|
||||
// Read reads log entries from the logger
|
||||
Read(...ReadOption) ([]Record, error)
|
||||
// Write writes records to log
|
||||
Write(Record) error
|
||||
// Stream log records
|
||||
Stream() (Stream, error)
|
||||
}
|
||||
|
||||
// Record is log record entry
|
||||
type Record struct {
|
||||
// Timestamp of logged event
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
// Metadata to enrich log record
|
||||
Metadata metadata.Metadata `json:"metadata"`
|
||||
// Value contains log entry
|
||||
Message interface{} `json:"message"`
|
||||
}
|
||||
|
||||
// Stream returns a log stream
|
||||
type Stream interface {
|
||||
Chan() <-chan Record
|
||||
Stop() error
|
||||
}
|
||||
|
||||
// Format is a function which formats the output
|
||||
type FormatFunc func(Record) string
|
||||
|
||||
// TextFormat returns text format
|
||||
func TextFormat(r Record) string {
|
||||
t := r.Timestamp.Format("2006-01-02 15:04:05")
|
||||
return fmt.Sprintf("%s %v", t, r.Message)
|
||||
}
|
||||
|
||||
// JSONFormat is a json Format func
|
||||
func JSONFormat(r Record) string {
|
||||
b, _ := json.Marshal(r)
|
||||
return string(b)
|
||||
}
|
@@ -1,115 +0,0 @@
|
||||
// Package memory provides an in memory log buffer
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/util/ring"
|
||||
)
|
||||
|
||||
// memoryLog is default micro log
|
||||
type memoryLog struct {
|
||||
*ring.Buffer
|
||||
}
|
||||
|
||||
// NewLog returns default Logger with
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
// get default options
|
||||
options := log.DefaultOptions()
|
||||
|
||||
// apply requested options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return &memoryLog{
|
||||
Buffer: ring.New(options.Size),
|
||||
}
|
||||
}
|
||||
|
||||
// Write writes logs into logger
|
||||
func (l *memoryLog) Write(r log.Record) error {
|
||||
l.Buffer.Put(fmt.Sprint(r.Message))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read reads logs and returns them
|
||||
func (l *memoryLog) Read(opts ...log.ReadOption) ([]log.Record, error) {
|
||||
options := log.ReadOptions{}
|
||||
// initialize the read options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
var entries []*ring.Entry
|
||||
// if Since options ha sbeen specified we honor it
|
||||
if !options.Since.IsZero() {
|
||||
entries = l.Buffer.Since(options.Since)
|
||||
}
|
||||
|
||||
// only if we specified valid count constraint
|
||||
// do we end up doing some serious if-else kung-fu
|
||||
// if since constraint has been provided
|
||||
// we return *count* number of logs since the given timestamp;
|
||||
// otherwise we return last count number of logs
|
||||
if options.Count > 0 {
|
||||
switch len(entries) > 0 {
|
||||
case true:
|
||||
// if we request fewer logs than what since constraint gives us
|
||||
if options.Count < len(entries) {
|
||||
entries = entries[0:options.Count]
|
||||
}
|
||||
default:
|
||||
entries = l.Buffer.Get(options.Count)
|
||||
}
|
||||
}
|
||||
|
||||
records := make([]log.Record, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
record := log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// Stream returns channel for reading log records
|
||||
// along with a stop channel, close it when done
|
||||
func (l *memoryLog) Stream() (log.Stream, error) {
|
||||
// get stream channel from ring buffer
|
||||
stream, stop := l.Buffer.Stream()
|
||||
// make a buffered channel
|
||||
records := make(chan log.Record, 128)
|
||||
// get last 10 records
|
||||
last10 := l.Buffer.Get(10)
|
||||
|
||||
// stream the log records
|
||||
go func() {
|
||||
// first send last 10 records
|
||||
for _, entry := range last10 {
|
||||
records <- log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
Metadata: metadata.New(0),
|
||||
}
|
||||
}
|
||||
// now stream continuously
|
||||
for entry := range stream {
|
||||
records <- log.Record{
|
||||
Timestamp: entry.Timestamp,
|
||||
Message: entry.Value,
|
||||
Metadata: metadata.New(0),
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return &logStream{
|
||||
stream: records,
|
||||
stop: stop,
|
||||
}, nil
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
func TestLogger(t *testing.T) {
|
||||
// set size to some value
|
||||
size := 100
|
||||
// override the global logger
|
||||
lg := NewLog(log.Size(size))
|
||||
// make sure we have the right size of the logger ring buffer
|
||||
if lg.(*memoryLog).Size() != size {
|
||||
t.Errorf("expected buffer size: %d, got: %d", size, lg.(*memoryLog).Size())
|
||||
}
|
||||
|
||||
// Log some cruft
|
||||
lg.Write(log.Record{Message: "foobar"})
|
||||
lg.Write(log.Record{Message: "foo bar"})
|
||||
|
||||
// Check if the logs are stored in the logger ring buffer
|
||||
expected := []string{"foobar", "foo bar"}
|
||||
entries, _ := lg.Read(log.Count(len(expected)))
|
||||
for i, entry := range entries {
|
||||
if !reflect.DeepEqual(entry.Message, expected[i]) {
|
||||
t.Errorf("expected %s, got %s", expected[i], entry.Message)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,24 +0,0 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
type logStream struct {
|
||||
stream <-chan log.Record
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func (l *logStream) Chan() <-chan log.Record {
|
||||
return l.stream
|
||||
}
|
||||
|
||||
func (l *logStream) Stop() error {
|
||||
select {
|
||||
case <-l.stop:
|
||||
return nil
|
||||
default:
|
||||
close(l.stop)
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -1,23 +0,0 @@
|
||||
package noop
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/debug/log"
|
||||
)
|
||||
|
||||
type noop struct{}
|
||||
|
||||
func (n *noop) Read(...log.ReadOption) ([]log.Record, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (n *noop) Write(log.Record) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noop) Stream() (log.Stream, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func NewLog(opts ...log.Option) log.Log {
|
||||
return new(noop)
|
||||
}
|
@@ -1,70 +0,0 @@
|
||||
package log
|
||||
|
||||
import "time"
|
||||
|
||||
// Option used by the logger
|
||||
type Option func(*Options)
|
||||
|
||||
// Options are logger options
|
||||
type Options struct {
|
||||
// Name of the log
|
||||
Name string
|
||||
// Size is the size of ring buffer
|
||||
Size int
|
||||
// Format specifies the output format
|
||||
Format FormatFunc
|
||||
}
|
||||
|
||||
// Name of the log
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// Size sets the size of the ring buffer
|
||||
func Size(s int) Option {
|
||||
return func(o *Options) {
|
||||
o.Size = s
|
||||
}
|
||||
}
|
||||
|
||||
func Format(f FormatFunc) Option {
|
||||
return func(o *Options) {
|
||||
o.Format = f
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultOptions returns default options
|
||||
func DefaultOptions() Options {
|
||||
return Options{
|
||||
Size: DefaultSize,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOptions for querying the logs
|
||||
type ReadOptions struct {
|
||||
// Since what time in past to return the logs
|
||||
Since time.Time
|
||||
// Count specifies number of logs to return
|
||||
Count int
|
||||
// Stream requests continuous log stream
|
||||
Stream bool
|
||||
}
|
||||
|
||||
// ReadOption used for reading the logs
|
||||
type ReadOption func(*ReadOptions)
|
||||
|
||||
// Since sets the time since which to return the log records
|
||||
func Since(s time.Time) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Since = s
|
||||
}
|
||||
}
|
||||
|
||||
// Count sets the number of log records to return
|
||||
func Count(c int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Count = c
|
||||
}
|
||||
}
|
@@ -1,89 +0,0 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/stats"
|
||||
"github.com/unistack-org/micro/v3/util/ring"
|
||||
)
|
||||
|
||||
type memoryStats struct {
|
||||
// used to store past stats
|
||||
buffer *ring.Buffer
|
||||
|
||||
sync.RWMutex
|
||||
started int64
|
||||
requests uint64
|
||||
errors uint64
|
||||
}
|
||||
|
||||
func (s *memoryStats) snapshot() *stats.Stat {
|
||||
s.RLock()
|
||||
defer s.RUnlock()
|
||||
|
||||
var mstat runtime.MemStats
|
||||
runtime.ReadMemStats(&mstat)
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
return &stats.Stat{
|
||||
Timestamp: now,
|
||||
Started: s.started,
|
||||
Uptime: now - s.started,
|
||||
Memory: mstat.Alloc,
|
||||
GC: mstat.PauseTotalNs,
|
||||
Threads: uint64(runtime.NumGoroutine()),
|
||||
Requests: s.requests,
|
||||
Errors: s.errors,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *memoryStats) Read() ([]*stats.Stat, error) {
|
||||
buf := s.buffer.Get(s.buffer.Size())
|
||||
var buffer []*stats.Stat
|
||||
|
||||
// get a value from the buffer if it exists
|
||||
for _, b := range buf {
|
||||
stat, ok := b.Value.(*stats.Stat)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
buffer = append(buffer, stat)
|
||||
}
|
||||
|
||||
// get a snapshot
|
||||
buffer = append(buffer, s.snapshot())
|
||||
|
||||
return buffer, nil
|
||||
}
|
||||
|
||||
func (s *memoryStats) Write(stat *stats.Stat) error {
|
||||
s.buffer.Put(stat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memoryStats) Record(err error) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// increment the total request count
|
||||
s.requests++
|
||||
|
||||
// increment the error count
|
||||
if err != nil {
|
||||
s.errors++
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewStats returns a new in memory stats buffer
|
||||
// TODO add options
|
||||
func NewStats() stats.Stats {
|
||||
return &memoryStats{
|
||||
started: time.Now().Unix(),
|
||||
buffer: ring.New(1),
|
||||
}
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
// Package stats provides runtime stats
|
||||
package stats
|
||||
|
||||
// Stats provides stats interface
|
||||
type Stats interface {
|
||||
// Read stat snapshot
|
||||
Read() ([]*Stat, error)
|
||||
// Write a stat snapshot
|
||||
Write(*Stat) error
|
||||
// Record a request
|
||||
Record(error) error
|
||||
}
|
||||
|
||||
// A runtime stat
|
||||
type Stat struct {
|
||||
// Timestamp of recording
|
||||
Timestamp int64
|
||||
// Start time as unix timestamp
|
||||
Started int64
|
||||
// Uptime in seconds
|
||||
Uptime int64
|
||||
// Memory usage in bytes
|
||||
Memory uint64
|
||||
// Threads aka go routines
|
||||
Threads uint64
|
||||
// Garbage collection in nanoseconds
|
||||
GC uint64
|
||||
// Total requests
|
||||
Requests uint64
|
||||
// Total errors
|
||||
Errors uint64
|
||||
}
|
@@ -9,46 +9,51 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrBadRequest
|
||||
// ErrBadRequest returns then requests contains invalid data
|
||||
ErrBadRequest = &Error{Code: 400}
|
||||
// ErrUnauthorized
|
||||
// ErrUnauthorized returns then user have unauthorized call
|
||||
ErrUnauthorized = &Error{Code: 401}
|
||||
// ErrForbidden
|
||||
// ErrForbidden returns then user have not access the resource
|
||||
ErrForbidden = &Error{Code: 403}
|
||||
// ErrNotFound
|
||||
// ErrNotFound returns then user specify invalid endpoint
|
||||
ErrNotFound = &Error{Code: 404}
|
||||
// ErrMethodNotAllowed
|
||||
// ErrMethodNotAllowed returns then user try to get invalid method
|
||||
ErrMethodNotAllowed = &Error{Code: 405}
|
||||
// ErrTimeout
|
||||
// ErrTimeout returns then timeout exceeded
|
||||
ErrTimeout = &Error{Code: 408}
|
||||
// ErrConflict
|
||||
// ErrConflict returns then request create duplicate resource
|
||||
ErrConflict = &Error{Code: 409}
|
||||
// ErrInternalServerError
|
||||
// ErrInternalServerError returns then server cant process request because of internal error
|
||||
ErrInternalServerError = &Error{Code: 500}
|
||||
// ErNotImplemented
|
||||
// ErNotImplemented returns then server does not have desired endpoint method
|
||||
ErNotImplemented = &Error{Code: 501}
|
||||
// ErrBadGateway
|
||||
// ErrBadGateway returns then server cant process request
|
||||
ErrBadGateway = &Error{Code: 502}
|
||||
// ErrServiceUnavailable
|
||||
// ErrServiceUnavailable returns then service unavailable
|
||||
ErrServiceUnavailable = &Error{Code: 503}
|
||||
// ErrGatewayTimeout
|
||||
// ErrGatewayTimeout returns then server have long time to process request
|
||||
ErrGatewayTimeout = &Error{Code: 504}
|
||||
)
|
||||
|
||||
// Error tpye
|
||||
// Error type
|
||||
type Error struct {
|
||||
Id string
|
||||
Code int32
|
||||
// Id holds error id or service, usually someting like my_service or uuid
|
||||
Id string
|
||||
// Detail holds some useful details about error
|
||||
Detail string
|
||||
// Status usually holds text of http status
|
||||
Status string
|
||||
// Code holds error code
|
||||
Code int32
|
||||
}
|
||||
|
||||
// Error satisfies error interface
|
||||
func (e *Error) Error() string {
|
||||
b, _ := json.Marshal(e)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// New generates a custom error.
|
||||
// New generates a custom error
|
||||
func New(id, detail string, code int32) error {
|
||||
return &Error{
|
||||
Id: id,
|
||||
|
11
event.go
11
event.go
@@ -6,11 +6,22 @@ import (
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
)
|
||||
|
||||
// Event is used to publish messages to a topic
|
||||
type Event interface {
|
||||
// Publish publishes a message to the event topic
|
||||
Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error
|
||||
}
|
||||
|
||||
type event struct {
|
||||
c client.Client
|
||||
topic string
|
||||
}
|
||||
|
||||
// NewEvent creates a new event publisher
|
||||
func NewEvent(topic string, c client.Client) Event {
|
||||
return &event{c, topic}
|
||||
}
|
||||
|
||||
func (e *event) Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error {
|
||||
return e.c.Publish(ctx, e.c.NewMessage(e.topic, msg), opts...)
|
||||
}
|
||||
|
@@ -1,49 +0,0 @@
|
||||
// Package events contains interfaces for managing events within distributed systems
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMissingTopic is returned if a blank topic was provided to publish
|
||||
ErrMissingTopic = errors.New("Missing topic")
|
||||
// ErrEncodingMessage is returned from publish if there was an error encoding the message option
|
||||
ErrEncodingMessage = errors.New("Error encoding message")
|
||||
)
|
||||
|
||||
// Stream of events
|
||||
type Stream interface {
|
||||
Publish(ctx context.Context, topic string, msg interface{}, opts ...PublishOption) error
|
||||
Subscribe(ctx context.Context, topic string, opts ...SubscribeOption) (<-chan Event, error)
|
||||
}
|
||||
|
||||
// Store of events
|
||||
type Store interface {
|
||||
Read(ctx context.Context, opts ...ReadOption) ([]*Event, error)
|
||||
Write(ctx context.Context, event *Event, opts ...WriteOption) error
|
||||
}
|
||||
|
||||
// Event is the object returned by the broker when you subscribe to a topic
|
||||
type Event struct {
|
||||
// ID to uniquely identify the event
|
||||
ID string
|
||||
// Topic of event, e.g. "registry.service.created"
|
||||
Topic string
|
||||
// Timestamp of the event
|
||||
Timestamp time.Time
|
||||
// Metadata contains the encoded event was indexed by
|
||||
Metadata metadata.Metadata
|
||||
// Payload contains the encoded message
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
// Unmarshal the events message into an object
|
||||
func (e *Event) Unmarshal(v interface{}) error {
|
||||
return json.Unmarshal(e.Payload, v)
|
||||
}
|
@@ -1,124 +0,0 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// PublishOptions contains all the options which can be provided when publishing an event
|
||||
type PublishOptions struct {
|
||||
// Metadata contains any keys which can be used to query the data, for example a customer id
|
||||
Metadata metadata.Metadata
|
||||
// Timestamp to set for the event, if the timestamp is a zero value, the current time will be used
|
||||
Timestamp time.Time
|
||||
}
|
||||
|
||||
// PublishOption sets attributes on PublishOptions
|
||||
type PublishOption func(o *PublishOptions)
|
||||
|
||||
// WithMetadata sets the Metadata field on PublishOptions
|
||||
func WithMetadata(md metadata.Metadata) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Metadata = metadata.Copy(md)
|
||||
}
|
||||
}
|
||||
|
||||
// WithTimestamp sets the timestamp field on PublishOptions
|
||||
func WithTimestamp(t time.Time) PublishOption {
|
||||
return func(o *PublishOptions) {
|
||||
o.Timestamp = t
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeOptions contains all the options which can be provided when subscribing to a topic
|
||||
type SubscribeOptions struct {
|
||||
// Queue is the name of the subscribers queue, if two subscribers have the same queue the message
|
||||
// should only be published to one of them
|
||||
Queue string
|
||||
// StartAtTime is the time from which the messages should be consumed from. If not provided then
|
||||
// the messages will be consumed starting from the moment the Subscription starts.
|
||||
StartAtTime time.Time
|
||||
}
|
||||
|
||||
// SubscribeOption sets attributes on SubscribeOptions
|
||||
type SubscribeOption func(o *SubscribeOptions)
|
||||
|
||||
// WithQueue sets the Queue fielf on SubscribeOptions to the value provided
|
||||
func WithQueue(q string) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.Queue = q
|
||||
}
|
||||
}
|
||||
|
||||
// WithStartAtTime sets the StartAtTime field on SubscribeOptions to the value provided
|
||||
func WithStartAtTime(t time.Time) SubscribeOption {
|
||||
return func(o *SubscribeOptions) {
|
||||
o.StartAtTime = t
|
||||
}
|
||||
}
|
||||
|
||||
// WriteOptions contains all the options which can be provided when writing an event to a store
|
||||
type WriteOptions struct {
|
||||
// TTL is the duration the event should be recorded for, a zero value TTL indicates the event should
|
||||
// be stored indefinitely
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// WriteOption sets attributes on WriteOptions
|
||||
type WriteOption func(o *WriteOptions)
|
||||
|
||||
// WithTTL sets the TTL attribute on WriteOptions
|
||||
func WithTTL(d time.Duration) WriteOption {
|
||||
return func(o *WriteOptions) {
|
||||
o.TTL = d
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOptions contains all the options which can be provided when reading events from a store
|
||||
type ReadOptions struct {
|
||||
// Topic to read events from, if no topic is provided events from all topics will be returned
|
||||
Topic string
|
||||
// Query to filter the results using. The store will query the metadata provided when the event
|
||||
// was written to the store
|
||||
Query map[string]string
|
||||
// Limit the number of results to return
|
||||
Limit int
|
||||
// Offset the results by this number, useful for paginated queries
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ReadOption sets attributes on ReadOptions
|
||||
type ReadOption func(o *ReadOptions)
|
||||
|
||||
// ReadTopic sets the topic attribute on ReadOptions
|
||||
func ReadTopic(t string) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Topic = t
|
||||
}
|
||||
}
|
||||
|
||||
// ReadFilter sets a key and value in the query
|
||||
func ReadFilter(key, value string) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
if o.Query == nil {
|
||||
o.Query = map[string]string{key: value}
|
||||
} else {
|
||||
o.Query[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReadLimit sets the limit attribute on ReadOptions
|
||||
func ReadLimit(l int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Limit = 1
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOffset sets the offset attribute on ReadOptions
|
||||
func ReadOffset(l int) ReadOption {
|
||||
return func(o *ReadOptions) {
|
||||
o.Offset = 1
|
||||
}
|
||||
}
|
21
flow/dag.go
Normal file
21
flow/dag.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package flow
|
||||
|
||||
type node struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (n *node) ID() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) Name() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) String() string {
|
||||
return n.name
|
||||
}
|
||||
|
||||
func (n *node) Hashcode() interface{} {
|
||||
return n.name
|
||||
}
|
68
flow/dag_test.go
Normal file
68
flow/dag_test.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/silas/dag"
|
||||
)
|
||||
|
||||
func checkErr(t *testing.T, err error) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDag(t *testing.T) {
|
||||
d1 := &dag.AcyclicGraph{}
|
||||
d2 := &dag.AcyclicGraph{}
|
||||
d2v1 := d2.Add(&node{"Substep.Create"})
|
||||
v1 := d1.Add(&node{"AccountService.Create"})
|
||||
v2 := d1.Add(&node{"AuthzService.Create"})
|
||||
v3 := d1.Add(&node{"AuthnService.Create"})
|
||||
v4 := d1.Add(&node{"ProjectService.Create"})
|
||||
v5 := d1.Add(&node{"ContactService.Create"})
|
||||
v6 := d1.Add(&node{"NetworkService.Create"})
|
||||
v7 := d1.Add(&node{"MailerService.Create"})
|
||||
v8 := d1.Add(&node{"NestedService.Create"})
|
||||
v9 := d1.Add(d2v1)
|
||||
d1.Connect(dag.BasicEdge(v1, v2))
|
||||
d1.Connect(dag.BasicEdge(v1, v3))
|
||||
d1.Connect(dag.BasicEdge(v1, v4))
|
||||
d1.Connect(dag.BasicEdge(v1, v5))
|
||||
d1.Connect(dag.BasicEdge(v1, v6))
|
||||
d1.Connect(dag.BasicEdge(v1, v7))
|
||||
d1.Connect(dag.BasicEdge(v7, v8))
|
||||
d1.Connect(dag.BasicEdge(v8, v9))
|
||||
|
||||
if err := d1.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d1.TransitiveReduction()
|
||||
|
||||
var steps [][]string
|
||||
fn := func(n dag.Vertex, idx int) error {
|
||||
if idx == 0 {
|
||||
steps = make([][]string, 1, 1)
|
||||
steps[0] = make([]string, 0, 1)
|
||||
} else if idx >= len(steps) {
|
||||
tsteps := make([][]string, idx+1, 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{"AccountService.Create"}
|
||||
err := d1.SortedDepthFirstWalk([]dag.Vertex{start}, fn)
|
||||
checkErr(t, err)
|
||||
if len(steps) != 4 {
|
||||
t.Fatalf("invalid steps: %#+v", steps)
|
||||
}
|
||||
if steps[3][0] != "Substep.Create" {
|
||||
t.Fatalf("invalid last step: %#+v", steps)
|
||||
}
|
||||
}
|
7
flow/flow.go
Normal file
7
flow/flow.go
Normal file
@@ -0,0 +1,7 @@
|
||||
// Package flow is an interface used for saga pattern messaging
|
||||
package flow
|
||||
|
||||
type Step interface {
|
||||
// Endpoint returns service_name.service_method
|
||||
Endpoint() string
|
||||
}
|
21
function.go
21
function.go
@@ -1,3 +1,5 @@
|
||||
// +build ignore
|
||||
|
||||
package micro
|
||||
|
||||
import (
|
||||
@@ -7,11 +9,28 @@ import (
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
// Function is a one time executing Service
|
||||
type Function interface {
|
||||
// Inherits Service interface
|
||||
Service
|
||||
// Done signals to complete execution
|
||||
Done() error
|
||||
// Handle registers an RPC handler
|
||||
Handle(v interface{}) error
|
||||
// Subscribe registers a subscriber
|
||||
Subscribe(topic string, v interface{}) error
|
||||
}
|
||||
|
||||
type function struct {
|
||||
cancel context.CancelFunc
|
||||
Service
|
||||
}
|
||||
|
||||
// NewFunction returns a new Function for a one time executing Service
|
||||
func NewFunction(opts ...Option) Function {
|
||||
return newFunction(opts...)
|
||||
}
|
||||
|
||||
func fnHandlerWrapper(f Function) server.HandlerWrapper {
|
||||
return func(h server.HandlerFunc) server.HandlerFunc {
|
||||
return func(ctx context.Context, req server.Request, rsp interface{}) error {
|
||||
@@ -45,7 +64,7 @@ func newFunction(opts ...Option) Function {
|
||||
// make context the last thing
|
||||
fopts = append(fopts, Context(ctx))
|
||||
|
||||
service := newService(fopts...)
|
||||
service := &service{opts: NewOptions(fopts...)}
|
||||
|
||||
fn := &function{
|
||||
cancel: cancel,
|
||||
|
@@ -2,25 +2,26 @@
|
||||
|
||||
package micro
|
||||
|
||||
/*
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
rmemory "github.com/unistack-org/micro-registry-memory"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
)
|
||||
|
||||
func TestFunction(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
|
||||
r := rmemory.NewRegistry()
|
||||
|
||||
r := register.NewRegister()
|
||||
ctx := context.TODO()
|
||||
// create service
|
||||
fn := NewFunction(
|
||||
Registry(r),
|
||||
Register(r),
|
||||
Name("test.function"),
|
||||
AfterStart(func() error {
|
||||
AfterStart(func(ctx context.Context) error {
|
||||
wg.Done()
|
||||
return nil
|
||||
}),
|
||||
@@ -61,3 +62,5 @@ func TestFunction(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
|
19
go.mod
19
go.mod
@@ -1,22 +1,13 @@
|
||||
module github.com/unistack-org/micro/v3
|
||||
|
||||
go 1.14
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/ef-ds/deque v1.0.4
|
||||
github.com/golang/protobuf v1.4.3
|
||||
github.com/google/uuid v1.1.5
|
||||
github.com/google/uuid v1.2.0
|
||||
github.com/imdario/mergo v0.3.11
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/miekg/dns v1.1.35
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c
|
||||
github.com/stretchr/testify v1.7.0
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
|
||||
google.golang.org/protobuf v1.25.0
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
|
||||
)
|
||||
|
121
go.sum
121
go.sum
@@ -1,126 +1,21 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/ef-ds/deque v1.0.4 h1:iFAZNmveMT9WERAkqLJ+oaABF9AcVQ5AjXem/hroniI=
|
||||
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||
github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
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=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/uuid v1.1.5 h1:kxhtnfFVi+rYdOALN0B3k9UT86zVJKfBimRaciULW4I=
|
||||
github.com/google/uuid v1.1.5/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
|
||||
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/miekg/dns v1.1.35 h1:oTfOaDH+mZkdcgdIjH6yBajRGtIwcwcaR+rt23ZSrJs=
|
||||
github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw=
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34 h1:vBfVmA5mZhsQa2jr1FOL9nfA37N/jnbBmi5XUfviVTI=
|
||||
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
@@ -6,7 +6,7 @@ import "context"
|
||||
var (
|
||||
// DefaultLogger variable
|
||||
DefaultLogger Logger = NewLogger()
|
||||
// DefaultLogger level
|
||||
// DefaultLevel used by logger
|
||||
DefaultLevel Level = InfoLevel
|
||||
)
|
||||
|
||||
|
@@ -21,9 +21,9 @@ func init() {
|
||||
}
|
||||
|
||||
type defaultLogger struct {
|
||||
sync.RWMutex
|
||||
opts Options
|
||||
enc *json.Encoder
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
// Init(opts...) should only overwrite provided options
|
||||
@@ -49,10 +49,18 @@ func (l *defaultLogger) V(level Level) bool {
|
||||
}
|
||||
|
||||
func (l *defaultLogger) Fields(fields map[string]interface{}) Logger {
|
||||
l.Lock()
|
||||
l.opts.Fields = copyFields(fields)
|
||||
l.Unlock()
|
||||
return l
|
||||
nl := &defaultLogger{opts: l.opts, enc: l.enc}
|
||||
nl.opts.Fields = make(map[string]interface{}, len(l.opts.Fields)+len(fields))
|
||||
l.RLock()
|
||||
for k, v := range l.opts.Fields {
|
||||
nl.opts.Fields[k] = v
|
||||
}
|
||||
l.RUnlock()
|
||||
|
||||
for k, v := range fields {
|
||||
nl.opts.Fields[k] = v
|
||||
}
|
||||
return nl
|
||||
}
|
||||
|
||||
func copyFields(src map[string]interface{}) map[string]interface{} {
|
||||
@@ -153,7 +161,9 @@ func (l *defaultLogger) Log(ctx context.Context, level Level, args ...interface{
|
||||
}
|
||||
|
||||
fields["timestamp"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
fields["msg"] = fmt.Sprint(args...)
|
||||
if len(args) > 0 {
|
||||
fields["msg"] = fmt.Sprint(args...)
|
||||
}
|
||||
|
||||
l.RLock()
|
||||
_ = l.enc.Encode(fields)
|
||||
@@ -178,7 +188,7 @@ func (l *defaultLogger) Logf(ctx context.Context, level Level, msg string, args
|
||||
fields["timestamp"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
if len(args) > 0 {
|
||||
fields["msg"] = fmt.Sprintf(msg, args...)
|
||||
} else {
|
||||
} else if msg != "" {
|
||||
fields["msg"] = msg
|
||||
}
|
||||
l.RLock()
|
||||
|
@@ -11,16 +11,18 @@ type Option func(*Options)
|
||||
|
||||
// Options holds logger options
|
||||
type Options struct {
|
||||
// The logging level the logger should log at. default is `InfoLevel`
|
||||
Level Level
|
||||
// fields to always be logged
|
||||
Fields map[string]interface{}
|
||||
// It's common to set this to a file, or leave it default which is `os.Stderr`
|
||||
// Out holds the output writer
|
||||
Out io.Writer
|
||||
// Caller skip frame count for file:line info
|
||||
CallerSkipCount int
|
||||
// Alternative options
|
||||
// Context holds exernal options
|
||||
Context context.Context
|
||||
// Fields holds additional metadata
|
||||
Fields map[string]interface{}
|
||||
// Name holds the logger name
|
||||
Name string
|
||||
// CallerSkipCount number of frmaes to skip
|
||||
CallerSkipCount int
|
||||
// The logging level the logger should log
|
||||
Level Level
|
||||
}
|
||||
|
||||
// NewOptions creates new options struct
|
||||
@@ -72,3 +74,10 @@ func WithContext(ctx context.Context) Option {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// WithName sets the name
|
||||
func withName(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
330
logger/wrapper/wrapper.go
Normal file
330
logger/wrapper/wrapper.go
Normal file
@@ -0,0 +1,330 @@
|
||||
// Package wrapper provides wrapper for Tracer
|
||||
package wrapper
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
type lWrapper struct {
|
||||
client.Client
|
||||
serverHandler server.HandlerFunc
|
||||
serverSubscriber server.SubscriberFunc
|
||||
clientCallFunc client.CallFunc
|
||||
opts Options
|
||||
}
|
||||
|
||||
type ClientCallObserver func(context.Context, client.Request, interface{}, []client.CallOption, error) []string
|
||||
type ClientStreamObserver func(context.Context, client.Request, []client.CallOption, client.Stream, error) []string
|
||||
type ClientPublishObserver func(context.Context, client.Message, []client.PublishOption, error) []string
|
||||
type ClientCallFuncObserver func(context.Context, string, client.Request, interface{}, client.CallOptions, error) []string
|
||||
type ServerHandlerObserver func(context.Context, server.Request, interface{}, error) []string
|
||||
type ServerSubscriberObserver func(context.Context, server.Message, error) []string
|
||||
|
||||
type Options struct {
|
||||
Logger logger.Logger
|
||||
Level logger.Level
|
||||
Enabled bool
|
||||
ClientCallObservers []ClientCallObserver
|
||||
ClientStreamObservers []ClientStreamObserver
|
||||
ClientPublishObservers []ClientPublishObserver
|
||||
ClientCallFuncObservers []ClientCallFuncObserver
|
||||
ServerHandlerObservers []ServerHandlerObserver
|
||||
ServerSubscriberObservers []ServerSubscriberObserver
|
||||
}
|
||||
|
||||
type Option func(*Options)
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
Level: logger.TraceLevel,
|
||||
ClientCallObservers: []ClientCallObserver{DefaultClientCallObserver},
|
||||
ClientStreamObservers: []ClientStreamObserver{DefaultClientStreamObserver},
|
||||
ClientPublishObservers: []ClientPublishObserver{DefaultClientPublishObserver},
|
||||
ClientCallFuncObservers: []ClientCallFuncObserver{DefaultClientCallFuncObserver},
|
||||
ServerHandlerObservers: []ServerHandlerObserver{DefaultServerHandlerObserver},
|
||||
ServerSubscriberObservers: []ServerSubscriberObserver{DefaultServerSubscriberObserver},
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
func WithEnabled(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.Enabled = b
|
||||
}
|
||||
}
|
||||
|
||||
func WithLevel(l logger.Level) Option {
|
||||
return func(o *Options) {
|
||||
o.Level = l
|
||||
}
|
||||
}
|
||||
|
||||
func WithLogger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
func WithClientCallObservers(ob ...ClientCallObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ClientCallObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func WithClientStreamObservers(ob ...ClientStreamObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ClientStreamObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func WithClientPublishObservers(ob ...ClientPublishObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ClientPublishObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func WithClientCallFuncObservers(ob ...ClientCallFuncObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ClientCallFuncObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func WithServerHandlerObservers(ob ...ServerHandlerObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ServerHandlerObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func WithServerSubscriberObservers(ob ...ServerSubscriberObserver) Option {
|
||||
return func(o *Options) {
|
||||
o.ServerSubscriberObservers = ob
|
||||
}
|
||||
}
|
||||
|
||||
func DefaultClientCallObserver(ctx context.Context, req client.Request, rsp interface{}, opts []client.CallOption, err error) []string {
|
||||
labels := []string{"service", req.Service(), "endpoint", req.Endpoint()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func DefaultClientStreamObserver(ctx context.Context, req client.Request, opts []client.CallOption, stream client.Stream, err error) []string {
|
||||
labels := []string{"service", req.Service(), "endpoint", req.Endpoint()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func DefaultClientPublishObserver(ctx context.Context, msg client.Message, opts []client.PublishOption, err error) []string {
|
||||
labels := []string{"endpoint", msg.Topic()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func DefaultServerHandlerObserver(ctx context.Context, req server.Request, rsp interface{}, err error) []string {
|
||||
labels := []string{"service", req.Service(), "endpoint", req.Endpoint()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func DefaultServerSubscriberObserver(ctx context.Context, msg server.Message, err error) []string {
|
||||
labels := []string{"endpoint", msg.Topic()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func DefaultClientCallFuncObserver(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions, err error) []string {
|
||||
labels := []string{"service", req.Service(), "endpoint", req.Endpoint()}
|
||||
if err != nil {
|
||||
labels = append(labels, "error", err.Error())
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
func (l *lWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||
err := l.Client.Call(ctx, req, rsp, opts...)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ClientCallObservers {
|
||||
labels = append(labels, o(ctx, req, rsp, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *lWrapper) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||
stream, err := l.Client.Stream(ctx, req, opts...)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return stream, err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ClientStreamObservers {
|
||||
labels = append(labels, o(ctx, req, opts, stream, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return stream, err
|
||||
}
|
||||
|
||||
func (l *lWrapper) Publish(ctx context.Context, msg client.Message, opts ...client.PublishOption) error {
|
||||
err := l.Client.Publish(ctx, msg, opts...)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ClientPublishObservers {
|
||||
labels = append(labels, o(ctx, msg, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *lWrapper) ServerHandler(ctx context.Context, req server.Request, rsp interface{}) error {
|
||||
err := l.serverHandler(ctx, req, rsp)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ServerHandlerObservers {
|
||||
labels = append(labels, o(ctx, req, rsp, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *lWrapper) ServerSubscriber(ctx context.Context, msg server.Message) error {
|
||||
err := l.serverSubscriber(ctx, msg)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ServerSubscriberObservers {
|
||||
labels = append(labels, o(ctx, msg, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// NewClientWrapper accepts an open tracing Trace and returns a Client Wrapper
|
||||
func NewClientWrapper(opts ...Option) client.Wrapper {
|
||||
return func(c client.Client) client.Client {
|
||||
options := NewOptions()
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &lWrapper{opts: options, Client: c}
|
||||
}
|
||||
}
|
||||
|
||||
// NewClientCallWrapper accepts an opentracing Tracer and returns a Call Wrapper
|
||||
func NewClientCallWrapper(opts ...Option) client.CallWrapper {
|
||||
return func(h client.CallFunc) client.CallFunc {
|
||||
options := NewOptions()
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
l := &lWrapper{opts: options, clientCallFunc: h}
|
||||
return l.ClientCallFunc
|
||||
}
|
||||
}
|
||||
|
||||
func (l *lWrapper) ClientCallFunc(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||
err := l.clientCallFunc(ctx, addr, req, rsp, opts)
|
||||
|
||||
if !l.opts.Enabled {
|
||||
return err
|
||||
}
|
||||
|
||||
var labels []string
|
||||
for _, o := range l.opts.ClientCallFuncObservers {
|
||||
labels = append(labels, o(ctx, addr, req, rsp, opts, err)...)
|
||||
}
|
||||
fields := make(map[string]interface{}, int(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)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// NewServerHandlerWrapper accepts an options and returns a Handler Wrapper
|
||||
func NewServerHandlerWrapper(opts ...Option) server.HandlerWrapper {
|
||||
return func(h server.HandlerFunc) server.HandlerFunc {
|
||||
options := NewOptions()
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
l := &lWrapper{opts: options, serverHandler: h}
|
||||
return l.ServerHandler
|
||||
}
|
||||
}
|
||||
|
||||
// NewServerSubscriberWrapper accepts an opentracing Tracer and returns a Subscriber Wrapper
|
||||
func NewServerSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
|
||||
return func(h server.SubscriberFunc) server.SubscriberFunc {
|
||||
options := NewOptions()
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
l := &lWrapper{opts: options, serverSubscriber: h}
|
||||
return l.ServerSubscriber
|
||||
}
|
||||
}
|
@@ -5,35 +5,140 @@ import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type mdIncomingKey struct{}
|
||||
type mdOutgoingKey struct{}
|
||||
type mdKey struct{}
|
||||
|
||||
// FromIncomingContext returns metadata from incoming ctx
|
||||
// returned metadata shoud not be modified or race condition happens
|
||||
func FromIncomingContext(ctx context.Context) (Metadata, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
md, ok := ctx.Value(mdIncomingKey{}).(*rawMetadata)
|
||||
if !ok || md.md == nil {
|
||||
return nil, false
|
||||
}
|
||||
return md.md, ok
|
||||
}
|
||||
|
||||
// FromOutgoingContext returns metadata from outgoing ctx
|
||||
// returned metadata shoud not be modified or race condition happens
|
||||
func FromOutgoingContext(ctx context.Context) (Metadata, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
md, ok := ctx.Value(mdOutgoingKey{}).(*rawMetadata)
|
||||
if !ok || md.md == nil {
|
||||
return nil, false
|
||||
}
|
||||
return md.md, ok
|
||||
}
|
||||
|
||||
// FromContext returns metadata from the given context
|
||||
// returned metadata shoud not be modified or race condition happens
|
||||
//
|
||||
// Deprecated: use FromIncomingContext or FromOutgoingContext
|
||||
func FromContext(ctx context.Context) (Metadata, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
md, ok := ctx.Value(metadataKey{}).(Metadata)
|
||||
if !ok {
|
||||
return nil, ok
|
||||
md, ok := ctx.Value(mdKey{}).(*rawMetadata)
|
||||
if !ok || md.md == nil {
|
||||
return nil, false
|
||||
}
|
||||
nmd := Copy(md)
|
||||
return nmd, ok
|
||||
return md.md, ok
|
||||
}
|
||||
|
||||
// NewContext creates a new context with the given metadata
|
||||
//
|
||||
// Deprecated: use NewIncomingContext or NewOutgoingContext
|
||||
func NewContext(ctx context.Context, md Metadata) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, metadataKey{}, Copy(md))
|
||||
ctx = context.WithValue(ctx, mdKey{}, &rawMetadata{md})
|
||||
ctx = context.WithValue(ctx, mdIncomingKey{}, &rawMetadata{})
|
||||
ctx = context.WithValue(ctx, mdOutgoingKey{}, &rawMetadata{})
|
||||
return ctx
|
||||
}
|
||||
|
||||
// MergeContext merges metadata to existing metadata, overwriting if specified
|
||||
func MergeContext(ctx context.Context, pmd Metadata, overwrite bool) context.Context {
|
||||
// SetOutgoingContext modify outgoing context with given metadata
|
||||
func SetOutgoingContext(ctx context.Context, md Metadata) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
if omd, ok := ctx.Value(mdOutgoingKey{}).(*rawMetadata); ok {
|
||||
omd.md = md
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIncomingContext modify incoming context with given metadata
|
||||
func SetIncomingContext(ctx context.Context, md Metadata) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
if omd, ok := ctx.Value(mdIncomingKey{}).(*rawMetadata); ok {
|
||||
omd.md = md
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NewIncomingContext creates a new context with incoming metadata attached
|
||||
func NewIncomingContext(ctx context.Context, md Metadata) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
md, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
return context.WithValue(ctx, metadataKey{}, Copy(pmd))
|
||||
ctx = context.WithValue(ctx, mdIncomingKey{}, &rawMetadata{md})
|
||||
if v, ok := ctx.Value(mdOutgoingKey{}).(*rawMetadata); !ok || v == nil {
|
||||
ctx = context.WithValue(ctx, mdOutgoingKey{}, &rawMetadata{})
|
||||
}
|
||||
return context.WithValue(ctx, metadataKey{}, Merge(md, pmd, overwrite))
|
||||
return ctx
|
||||
}
|
||||
|
||||
// NewOutgoingContext creates a new context with outcoming metadata attached
|
||||
func NewOutgoingContext(ctx context.Context, md Metadata) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
ctx = context.WithValue(ctx, mdOutgoingKey{}, &rawMetadata{md})
|
||||
if v, ok := ctx.Value(mdIncomingKey{}).(*rawMetadata); !ok || v == nil {
|
||||
ctx = context.WithValue(ctx, mdIncomingKey{}, &rawMetadata{})
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// AppendOutgoingContext apends new md to context
|
||||
func AppendOutgoingContext(ctx context.Context, kv ...string) context.Context {
|
||||
md, ok := Pairs(kv...)
|
||||
if !ok {
|
||||
return ctx
|
||||
}
|
||||
omd, ok := FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
return NewOutgoingContext(ctx, md)
|
||||
}
|
||||
for k, v := range md {
|
||||
omd.Set(k, v)
|
||||
}
|
||||
return NewOutgoingContext(ctx, omd)
|
||||
}
|
||||
|
||||
// AppendIncomingContext apends new md to context
|
||||
func AppendIncomingContext(ctx context.Context, kv ...string) context.Context {
|
||||
md, ok := Pairs(kv...)
|
||||
if !ok {
|
||||
return ctx
|
||||
}
|
||||
omd, ok := FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return NewIncomingContext(ctx, md)
|
||||
}
|
||||
for k, v := range md {
|
||||
omd.Set(k, v)
|
||||
}
|
||||
return NewIncomingContext(ctx, omd)
|
||||
}
|
||||
|
@@ -2,30 +2,38 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/textproto"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type metadataKey struct{}
|
||||
var (
|
||||
// HeaderPrefix for all headers passed
|
||||
HeaderPrefix = "Micro-"
|
||||
)
|
||||
|
||||
// Metadata is our way of representing request headers internally.
|
||||
// They're used at the RPC level and translate back and forth
|
||||
// from Transport headers.
|
||||
type Metadata map[string]string
|
||||
|
||||
var (
|
||||
// DefaultMetadataSize used when need to init new Metadata
|
||||
DefaultMetadataSize = 6
|
||||
)
|
||||
|
||||
type Iterator struct {
|
||||
cur int
|
||||
cnt int
|
||||
keys []string
|
||||
md Metadata
|
||||
type rawMetadata struct {
|
||||
md Metadata
|
||||
}
|
||||
|
||||
var (
|
||||
// defaultMetadataSize used when need to init new Metadata
|
||||
defaultMetadataSize = 2
|
||||
)
|
||||
|
||||
// Iterator used to iterate over metadata with order
|
||||
type Iterator struct {
|
||||
md Metadata
|
||||
keys []string
|
||||
cur int
|
||||
cnt int
|
||||
}
|
||||
|
||||
// Next advance iterator to next element
|
||||
func (iter *Iterator) Next(k, v *string) bool {
|
||||
if iter.cur+1 > iter.cnt {
|
||||
return false
|
||||
@@ -37,7 +45,7 @@ func (iter *Iterator) Next(k, v *string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Iterate returns run user func with map key, val sorted by key
|
||||
// Iterator returns the itarator for metadata in sorted order
|
||||
func (md Metadata) Iterator() *Iterator {
|
||||
iter := &Iterator{md: md, cnt: len(md)}
|
||||
iter.keys = make([]string, 0, iter.cnt)
|
||||
@@ -67,12 +75,9 @@ func (md Metadata) Set(key, val string) {
|
||||
// Del is used to remove value from metadata
|
||||
func (md Metadata) Del(key string) {
|
||||
// fast path
|
||||
if _, ok := md[key]; ok {
|
||||
delete(md, key)
|
||||
} else {
|
||||
// slow path
|
||||
delete(md, textproto.CanonicalMIMEHeaderKey(key))
|
||||
}
|
||||
delete(md, key)
|
||||
// slow path
|
||||
delete(md, textproto.CanonicalMIMEHeaderKey(key))
|
||||
}
|
||||
|
||||
// Copy makes a copy of the metadata
|
||||
@@ -84,39 +89,10 @@ func Copy(md Metadata) Metadata {
|
||||
return nmd
|
||||
}
|
||||
|
||||
// Del deletes key from metadata
|
||||
func Del(ctx context.Context, key string) context.Context {
|
||||
md, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
md = New(0)
|
||||
}
|
||||
md.Del(key)
|
||||
return context.WithValue(ctx, metadataKey{}, md)
|
||||
}
|
||||
|
||||
// Set add key with val to metadata
|
||||
func Set(ctx context.Context, key, val string) context.Context {
|
||||
md, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
md = New(0)
|
||||
}
|
||||
md.Set(key, val)
|
||||
return context.WithValue(ctx, metadataKey{}, md)
|
||||
}
|
||||
|
||||
// Get returns a single value from metadata in the context
|
||||
func Get(ctx context.Context, key string) (string, bool) {
|
||||
md, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
return "", ok
|
||||
}
|
||||
return md.Get(key)
|
||||
}
|
||||
|
||||
// New return new sized metadata
|
||||
func New(size int) Metadata {
|
||||
if size == 0 {
|
||||
size = DefaultMetadataSize
|
||||
size = defaultMetadataSize
|
||||
}
|
||||
return make(Metadata, size)
|
||||
}
|
||||
@@ -135,3 +111,19 @@ func Merge(omd Metadata, mmd Metadata, overwrite bool) Metadata {
|
||||
}
|
||||
return nmd
|
||||
}
|
||||
|
||||
func Pairs(kv ...string) (Metadata, bool) {
|
||||
if len(kv)%2 == 1 {
|
||||
return nil, false
|
||||
}
|
||||
md := New(len(kv) / 2)
|
||||
var k string
|
||||
for i, v := range kv {
|
||||
if i%2 == 0 {
|
||||
k = v
|
||||
continue
|
||||
}
|
||||
md.Set(k, v)
|
||||
}
|
||||
return md, true
|
||||
}
|
||||
|
@@ -2,11 +2,55 @@ package metadata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppend(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = AppendIncomingContext(ctx, "key1", "val1", "key2", "val2")
|
||||
md, ok := FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
t.Fatal("metadata empty")
|
||||
}
|
||||
if _, ok := md.Get("key1"); !ok {
|
||||
t.Fatal("key1 not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairs(t *testing.T) {
|
||||
md, ok := Pairs("key1", "val1", "key2", "val2")
|
||||
if !ok {
|
||||
t.Fatal("odd number of kv")
|
||||
}
|
||||
if _, ok = md.Get("key1"); !ok {
|
||||
t.Fatal("key1 not found")
|
||||
}
|
||||
}
|
||||
|
||||
func testCtx(ctx context.Context) {
|
||||
md := New(2)
|
||||
md.Set("Key1", "Val1_new")
|
||||
md.Set("Key3", "Val3")
|
||||
SetOutgoingContext(ctx, md)
|
||||
}
|
||||
|
||||
func TestPassing(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
md1 := New(2)
|
||||
md1.Set("Key1", "Val1")
|
||||
md1.Set("Key2", "Val2")
|
||||
|
||||
ctx = NewIncomingContext(ctx, md1)
|
||||
testCtx(ctx)
|
||||
md, ok := FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
t.Fatalf("missing metadata from outgoing context")
|
||||
}
|
||||
if v, ok := md.Get("Key1"); !ok || v != "Val1_new" {
|
||||
t.Fatalf("invalid metadata value %#+v", md)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMerge(t *testing.T) {
|
||||
omd := Metadata{
|
||||
"key1": "val1",
|
||||
@@ -32,26 +76,27 @@ func TestIterator(t *testing.T) {
|
||||
var k, v string
|
||||
|
||||
for iter.Next(&k, &v) {
|
||||
fmt.Printf("k: %s, v: %s\n", k, v)
|
||||
//fmt.Printf("k: %s, v: %s\n", k, v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMedataCanonicalKey(t *testing.T) {
|
||||
ctx := Set(context.TODO(), "x-request-id", "12345")
|
||||
v, ok := Get(ctx, "x-request-id")
|
||||
md := New(1)
|
||||
md.Set("x-request-id", "12345")
|
||||
v, ok := md.Get("x-request-id")
|
||||
if !ok {
|
||||
t.Fatalf("failed to get x-request-id")
|
||||
} else if v != "12345" {
|
||||
t.Fatalf("invalid metadata value: %s != %s", "12345", v)
|
||||
}
|
||||
|
||||
v, ok = Get(ctx, "X-Request-Id")
|
||||
v, ok = md.Get("X-Request-Id")
|
||||
if !ok {
|
||||
t.Fatalf("failed to get x-request-id")
|
||||
} else if v != "12345" {
|
||||
t.Fatalf("invalid metadata value: %s != %s", "12345", v)
|
||||
}
|
||||
v, ok = Get(ctx, "X-Request-ID")
|
||||
v, ok = md.Get("X-Request-ID")
|
||||
if !ok {
|
||||
t.Fatalf("failed to get x-request-id")
|
||||
} else if v != "12345" {
|
||||
@@ -61,9 +106,11 @@ func TestMedataCanonicalKey(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMetadataSet(t *testing.T) {
|
||||
ctx := Set(context.TODO(), "Key", "val")
|
||||
md := New(1)
|
||||
|
||||
val, ok := Get(ctx, "Key")
|
||||
md.Set("Key", "val")
|
||||
|
||||
val, ok := md.Get("Key")
|
||||
if !ok {
|
||||
t.Fatal("key Key not found")
|
||||
}
|
||||
@@ -78,15 +125,8 @@ func TestMetadataDelete(t *testing.T) {
|
||||
"Baz": "empty",
|
||||
}
|
||||
|
||||
ctx := NewContext(context.TODO(), md)
|
||||
ctx = Del(ctx, "Baz")
|
||||
|
||||
emd, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
t.Fatal("key Key not found")
|
||||
}
|
||||
|
||||
_, ok = emd["Baz"]
|
||||
md.Del("Baz")
|
||||
_, ok := md.Get("Baz")
|
||||
if ok {
|
||||
t.Fatal("key Baz not deleted")
|
||||
}
|
||||
@@ -137,42 +177,3 @@ func TestMetadataContext(t *testing.T) {
|
||||
t.Errorf("Expected metadata length 1 got %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeContext(t *testing.T) {
|
||||
type args struct {
|
||||
existing Metadata
|
||||
append Metadata
|
||||
overwrite bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want Metadata
|
||||
}{
|
||||
{
|
||||
name: "matching key, overwrite false",
|
||||
args: args{
|
||||
existing: Metadata{"Foo": "bar", "Sumo": "demo"},
|
||||
append: Metadata{"Sumo": "demo2"},
|
||||
overwrite: false,
|
||||
},
|
||||
want: Metadata{"Foo": "bar", "Sumo": "demo"},
|
||||
},
|
||||
{
|
||||
name: "matching key, overwrite true",
|
||||
args: args{
|
||||
existing: Metadata{"Foo": "bar", "Sumo": "demo"},
|
||||
append: Metadata{"Sumo": "demo2"},
|
||||
overwrite: true,
|
||||
},
|
||||
want: Metadata{"Foo": "bar", "Sumo": "demo2"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got, _ := FromContext(MergeContext(NewContext(context.TODO(), tt.args.existing), tt.args.append, tt.args.overwrite)); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("MergeContext() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@@ -1,22 +0,0 @@
|
||||
metrics
|
||||
=======
|
||||
|
||||
The metrics package provides a simple metrics "Reporter" interface which allows the user to submit counters, gauges and timings (along with key/value tags).
|
||||
|
||||
Implementations
|
||||
---------------
|
||||
|
||||
* Prometheus (pull): will be first
|
||||
* Prometheus (push): certainly achievable
|
||||
* InfluxDB: could quite easily be done
|
||||
* Telegraf: almost identical to the InfluxDB implementation
|
||||
* Micro: Could we provide metrics over Micro's server interface?
|
||||
|
||||
|
||||
Todo
|
||||
----
|
||||
|
||||
* Include a handler middleware which uses the Reporter interface to generate per-request level metrics
|
||||
- Throughput
|
||||
- Errors
|
||||
- Duration
|
@@ -2,6 +2,8 @@
|
||||
package meter
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -12,24 +14,28 @@ var (
|
||||
DefaultAddress = ":9090"
|
||||
// DefaultPath the meter endpoint where the Meter data will be made available
|
||||
DefaultPath = "/metrics"
|
||||
// timingObjectives is the default spread of stats we maintain for timings / histograms:
|
||||
//defaultTimingObjectives = map[float64]float64{0.0: 0, 0.5: 0.05, 0.75: 0.04, 0.90: 0.03, 0.95: 0.02, 0.98: 0.001, 1: 0}
|
||||
// default metric prefix
|
||||
// DefaultMetricPrefix holds the string that prepends to all metrics
|
||||
DefaultMetricPrefix = "micro_"
|
||||
// default label prefix
|
||||
// DefaultLabelPrefix holds the string that prepends to all labels
|
||||
DefaultLabelPrefix = "micro_"
|
||||
// DefaultSummaryQuantiles is the default spread of stats for summary
|
||||
DefaultSummaryQuantiles = []float64{0.5, 0.9, 0.97, 0.99, 1}
|
||||
// DefaultSummaryWindow is the default window for summary
|
||||
DefaultSummaryWindow = 5 * time.Minute
|
||||
)
|
||||
|
||||
// Meter is an interface for collecting and instrumenting metrics
|
||||
type Meter interface {
|
||||
Init(...Option) error
|
||||
Counter(string, map[string]string) Counter
|
||||
FloatCounter(string, map[string]string) FloatCounter
|
||||
Gauge(string, func() float64, map[string]string) Gauge
|
||||
Set(map[string]string) Meter
|
||||
Histogram(string, map[string]string) Histogram
|
||||
Summary(string, map[string]string) Summary
|
||||
SummaryExt(string, time.Duration, []float64, map[string]string) Summary
|
||||
Name() string
|
||||
Init(opts ...Option) error
|
||||
Counter(name string, opts ...Option) Counter
|
||||
FloatCounter(name string, opts ...Option) FloatCounter
|
||||
Gauge(name string, fn func() float64, opts ...Option) Gauge
|
||||
Set(opts ...Option) Meter
|
||||
Histogram(name string, opts ...Option) Histogram
|
||||
Summary(name string, opts ...Option) Summary
|
||||
SummaryExt(name string, window time.Duration, quantiles []float64, opts ...Option) Summary
|
||||
Write(w io.Writer, opts ...Option) error
|
||||
Options() Options
|
||||
String() string
|
||||
}
|
||||
@@ -69,3 +75,67 @@ type Summary interface {
|
||||
Update(float64)
|
||||
UpdateDuration(time.Time)
|
||||
}
|
||||
|
||||
// Labels holds the metrics labels with k, v
|
||||
type Labels struct {
|
||||
keys []string
|
||||
vals []string
|
||||
}
|
||||
|
||||
// Append adds labels to label set
|
||||
func (ls Labels) Append(nls Labels) Labels {
|
||||
for n := range nls.keys {
|
||||
ls.keys = append(ls.keys, nls.keys[n])
|
||||
ls.vals = append(ls.vals, nls.vals[n])
|
||||
}
|
||||
return ls
|
||||
}
|
||||
|
||||
// Len returns number of labels
|
||||
func (ls Labels) Len() int {
|
||||
return len(ls.keys)
|
||||
}
|
||||
|
||||
type labels Labels
|
||||
|
||||
func (ls labels) Len() int {
|
||||
return len(ls.keys)
|
||||
}
|
||||
|
||||
func (ls labels) Sort() {
|
||||
sort.Sort(ls)
|
||||
}
|
||||
|
||||
func (ls labels) Swap(i, j int) {
|
||||
ls.keys[i], ls.keys[j] = ls.keys[j], ls.keys[i]
|
||||
ls.vals[i], ls.vals[j] = ls.vals[j], ls.vals[i]
|
||||
}
|
||||
|
||||
func (ls labels) Less(i, j int) bool {
|
||||
return ls.keys[i] < ls.keys[j]
|
||||
}
|
||||
|
||||
// LabelIter holds the
|
||||
type LabelIter struct {
|
||||
labels Labels
|
||||
cnt int
|
||||
cur int
|
||||
}
|
||||
|
||||
// Iter returns labels iterator
|
||||
func (ls Labels) Iter() *LabelIter {
|
||||
labels(ls).Sort()
|
||||
return &LabelIter{labels: ls, cnt: len(ls.keys)}
|
||||
}
|
||||
|
||||
// Next advance itarator to new pos
|
||||
func (iter *LabelIter) Next(k, v *string) bool {
|
||||
if iter.cur+1 > iter.cnt {
|
||||
return false
|
||||
}
|
||||
|
||||
*k = iter.labels.keys[iter.cur]
|
||||
*v = iter.labels.vals[iter.cur]
|
||||
iter.cur++
|
||||
return true
|
||||
}
|
||||
|
@@ -2,13 +2,54 @@ package meter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNoopMeter(t *testing.T) {
|
||||
meter := NewMeter(Path("/noop"))
|
||||
assert.NotNil(t, meter)
|
||||
assert.Equal(t, "/noop", meter.Options().Path)
|
||||
assert.Implements(t, new(Meter), meter)
|
||||
m := NewMeter(Path("/noop"))
|
||||
if "/noop" != m.Options().Path {
|
||||
t.Fatalf("invalid options parsing: %v", m.Options())
|
||||
}
|
||||
|
||||
cnt := m.Counter("counter", Label("server", "noop"))
|
||||
cnt.Inc()
|
||||
}
|
||||
|
||||
func TestLabelsAppend(t *testing.T) {
|
||||
var ls Labels
|
||||
ls.keys = []string{"type", "server"}
|
||||
ls.vals = []string{"noop", "http"}
|
||||
|
||||
var nls Labels
|
||||
nls.keys = []string{"register"}
|
||||
nls.vals = []string{"gossip"}
|
||||
ls = ls.Append(nls)
|
||||
|
||||
//ls.Sort()
|
||||
|
||||
if ls.keys[0] != "type" || ls.vals[0] != "noop" {
|
||||
t.Fatalf("append error: %v", ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIterator(t *testing.T) {
|
||||
options := NewOptions(
|
||||
Label("name", "svc1"),
|
||||
Label("version", "0.0.1"),
|
||||
Label("id", "12345"),
|
||||
Label("type", "noop"),
|
||||
Label("server", "http"),
|
||||
Label("register", "gossip"),
|
||||
Label("aa", "kk"),
|
||||
Label("zz", "kk"),
|
||||
)
|
||||
|
||||
iter := options.Labels.Iter()
|
||||
var k, v string
|
||||
cnt := 0
|
||||
for iter.Next(&k, &v) {
|
||||
if cnt == 4 && (k != "server" || v != "http") {
|
||||
t.Fatalf("iter error: %s != %s || %s != %s", k, "server", v, "http")
|
||||
}
|
||||
cnt++
|
||||
}
|
||||
}
|
||||
|
@@ -1,22 +1,22 @@
|
||||
package meter
|
||||
|
||||
import (
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// NoopMeter is an noop implementation of Meter
|
||||
type noopMeter struct {
|
||||
opts Options
|
||||
md map[string]string
|
||||
}
|
||||
|
||||
// NewMeter returns a configured noop reporter:
|
||||
func NewMeter(opts ...Option) Meter {
|
||||
return &noopMeter{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
return &noopMeter{opts: NewOptions(opts...)}
|
||||
}
|
||||
|
||||
func (r *noopMeter) Name() string {
|
||||
return r.opts.Name
|
||||
}
|
||||
|
||||
// Init initialize options
|
||||
@@ -28,38 +28,72 @@ func (r *noopMeter) Init(opts ...Option) error {
|
||||
}
|
||||
|
||||
// Counter implements the Meter interface
|
||||
func (r *noopMeter) Counter(name string, md map[string]string) Counter {
|
||||
return &noopCounter{}
|
||||
func (r *noopMeter) Counter(name string, opts ...Option) Counter {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopCounter{labels: options.Labels}
|
||||
}
|
||||
|
||||
// FloatCounter implements the Meter interface
|
||||
func (r *noopMeter) FloatCounter(name string, md map[string]string) FloatCounter {
|
||||
return &noopFloatCounter{}
|
||||
func (r *noopMeter) FloatCounter(name string, opts ...Option) FloatCounter {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopFloatCounter{labels: options.Labels}
|
||||
}
|
||||
|
||||
// Gauge implements the Meter interface
|
||||
func (r *noopMeter) Gauge(name string, f func() float64, md map[string]string) Gauge {
|
||||
return &noopGauge{}
|
||||
func (r *noopMeter) Gauge(name string, f func() float64, opts ...Option) Gauge {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopGauge{labels: options.Labels}
|
||||
}
|
||||
|
||||
// Summary implements the Meter interface
|
||||
func (r *noopMeter) Summary(name string, md map[string]string) Summary {
|
||||
return &noopSummary{}
|
||||
func (r *noopMeter) Summary(name string, opts ...Option) Summary {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopSummary{labels: options.Labels}
|
||||
}
|
||||
|
||||
// SummaryExt implements the Meter interface
|
||||
func (r *noopMeter) SummaryExt(name string, window time.Duration, quantiles []float64, md map[string]string) Summary {
|
||||
return &noopSummary{}
|
||||
func (r *noopMeter) SummaryExt(name string, window time.Duration, quantiles []float64, opts ...Option) Summary {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopSummary{labels: options.Labels}
|
||||
}
|
||||
|
||||
// Histogram implements the Meter interface
|
||||
func (r *noopMeter) Histogram(name string, md map[string]string) Histogram {
|
||||
return &noopHistogram{}
|
||||
func (r *noopMeter) Histogram(name string, opts ...Option) Histogram {
|
||||
options := Options{}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return &noopHistogram{labels: options.Labels}
|
||||
}
|
||||
|
||||
// Set implements the Meter interface
|
||||
func (r *noopMeter) Set(md map[string]string) Meter {
|
||||
return &noopMeter{opts: r.opts, md: metadata.Copy(md)}
|
||||
func (r *noopMeter) Set(opts ...Option) Meter {
|
||||
m := &noopMeter{opts: r.opts}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (r *noopMeter) Write(w io.Writer, opts ...Option) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options implements the Meter interface
|
||||
@@ -72,7 +106,9 @@ func (r *noopMeter) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
type noopCounter struct{}
|
||||
type noopCounter struct {
|
||||
labels Labels
|
||||
}
|
||||
|
||||
func (r *noopCounter) Add(int) {
|
||||
|
||||
@@ -94,7 +130,9 @@ func (r *noopCounter) Set(uint64) {
|
||||
|
||||
}
|
||||
|
||||
type noopFloatCounter struct{}
|
||||
type noopFloatCounter struct {
|
||||
labels Labels
|
||||
}
|
||||
|
||||
func (r *noopFloatCounter) Add(float64) {
|
||||
|
||||
@@ -112,13 +150,17 @@ func (r *noopFloatCounter) Sub(float64) {
|
||||
|
||||
}
|
||||
|
||||
type noopGauge struct{}
|
||||
type noopGauge struct {
|
||||
labels Labels
|
||||
}
|
||||
|
||||
func (r *noopGauge) Get() float64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
type noopSummary struct{}
|
||||
type noopSummary struct {
|
||||
labels Labels
|
||||
}
|
||||
|
||||
func (r *noopSummary) Update(float64) {
|
||||
|
||||
@@ -128,7 +170,9 @@ func (r *noopSummary) UpdateDuration(time.Time) {
|
||||
|
||||
}
|
||||
|
||||
type noopHistogram struct{}
|
||||
type noopHistogram struct {
|
||||
labels Labels
|
||||
}
|
||||
|
||||
func (r *noopHistogram) Reset() {
|
||||
|
||||
|
@@ -11,21 +11,32 @@ type Option func(*Options)
|
||||
|
||||
// Options for metrics implementations:
|
||||
type Options struct {
|
||||
Address string
|
||||
Path string
|
||||
Metadata map[string]string
|
||||
//TimingObjectives map[float64]float64
|
||||
Logger logger.Logger
|
||||
Context context.Context
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// Name holds the meter name
|
||||
Name string
|
||||
// Address holds the address that serves metrics
|
||||
Address string
|
||||
// Path holds the path for metrics
|
||||
Path string
|
||||
// MetricPrefix holds the prefix for all metrics
|
||||
MetricPrefix string
|
||||
LabelPrefix string
|
||||
// LabelPrefix holds the prefix for all labels
|
||||
LabelPrefix string
|
||||
// Labels holds the default labels
|
||||
Labels Labels
|
||||
// WriteProcessMetrics flag to write process metrics
|
||||
WriteProcessMetrics bool
|
||||
// WriteFDMetrics flag to write fd metrics
|
||||
WriteFDMetrics bool
|
||||
}
|
||||
|
||||
// NewOptions prepares a set of options:
|
||||
func NewOptions(opt ...Option) Options {
|
||||
opts := Options{
|
||||
Address: DefaultAddress,
|
||||
Metadata: make(map[string]string, 3), // 3 elements contains service name, version and id
|
||||
Path: DefaultPath,
|
||||
Context: context.Background(),
|
||||
Logger: logger.DefaultLogger,
|
||||
@@ -61,15 +72,6 @@ func Address(value string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata will be added to every metric
|
||||
func Metadata(md map[string]string) Option {
|
||||
return func(o *Options) {
|
||||
for k, v := range md {
|
||||
o.Metadata[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// TimingObjectives defines the desired spread of statistics for histogram / timing metrics:
|
||||
func TimingObjectives(value map[float64]float64) Option {
|
||||
@@ -85,3 +87,32 @@ func Logger(l logger.Logger) Option {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// Label sets the label
|
||||
func Label(key, val string) Option {
|
||||
return func(o *Options) {
|
||||
o.Labels.keys = append(o.Labels.keys, key)
|
||||
o.Labels.vals = append(o.Labels.vals, val)
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
||||
// WriteProcessMetrics enable process metrics output for write
|
||||
func WriteProcessMetrics(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.WriteProcessMetrics = b
|
||||
}
|
||||
}
|
||||
|
||||
// WriteFDMetrics enable fd metrics output for write
|
||||
func WriteFDMetrics(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.WriteFDMetrics = b
|
||||
}
|
||||
}
|
||||
|
255
meter/wrapper/wrapper.go
Normal file
255
meter/wrapper/wrapper.go
Normal file
@@ -0,0 +1,255 @@
|
||||
package wrapper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
var (
|
||||
ClientRequestDurationSeconds = "client_request_duration_seconds"
|
||||
ClientRequestLatencyMicroseconds = "client_request_latency_microseconds"
|
||||
ClientRequestTotal = "client_request_total"
|
||||
ServerRequestDurationSeconds = "server_request_duration_seconds"
|
||||
ServerRequestLatencyMicroseconds = "server_request_latency_microseconds"
|
||||
ServerRequestTotal = "server_request_total"
|
||||
PublishMessageDurationSeconds = "publish_message_duration_seconds"
|
||||
PublishMessageLatencyMicroseconds = "publish_message_latency_microseconds"
|
||||
PublishMessageTotal = "publish_message_total"
|
||||
SubscribeMessageDurationSeconds = "subscribe_message_duration_seconds"
|
||||
SubscribeMessageLatencyMicroseconds = "subscribe_message_latency_microseconds"
|
||||
SubscribeMessageTotal = "subscribe_message_total"
|
||||
|
||||
labelSuccess = "success"
|
||||
labelFailure = "failure"
|
||||
labelStatus = "status"
|
||||
labelEndpoint = "endpoint"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Meter meter.Meter
|
||||
lopts []meter.Option
|
||||
}
|
||||
|
||||
type Option func(*Options)
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Meter: meter.DefaultMeter,
|
||||
lopts: make([]meter.Option, 0, 5),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func ServiceName(name string) Option {
|
||||
return func(o *Options) {
|
||||
o.lopts = append(o.lopts, meter.Label("name", name))
|
||||
}
|
||||
}
|
||||
|
||||
func ServiceVersion(version string) Option {
|
||||
return func(o *Options) {
|
||||
o.lopts = append(o.lopts, meter.Label("version", version))
|
||||
}
|
||||
}
|
||||
|
||||
func ServiceID(id string) Option {
|
||||
return func(o *Options) {
|
||||
o.lopts = append(o.lopts, meter.Label("id", id))
|
||||
}
|
||||
}
|
||||
|
||||
func Meter(m meter.Meter) Option {
|
||||
return func(o *Options) {
|
||||
o.Meter = m
|
||||
}
|
||||
}
|
||||
|
||||
type wrapper struct {
|
||||
client.Client
|
||||
callFunc client.CallFunc
|
||||
opts Options
|
||||
}
|
||||
|
||||
func NewClientWrapper(opts ...Option) client.Wrapper {
|
||||
return func(c client.Client) client.Client {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
Client: c,
|
||||
}
|
||||
return handler
|
||||
}
|
||||
}
|
||||
|
||||
func NewCallWrapper(opts ...Option) client.CallWrapper {
|
||||
return func(fn client.CallFunc) client.CallFunc {
|
||||
handler := &wrapper{
|
||||
opts: NewOptions(opts...),
|
||||
callFunc: fn,
|
||||
}
|
||||
return handler.CallFunc
|
||||
}
|
||||
}
|
||||
|
||||
func (w *wrapper) CallFunc(ctx context.Context, addr string, req client.Request, rsp interface{}, opts client.CallOptions) error {
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
|
||||
|
||||
ts := time.Now()
|
||||
err := w.callFunc(ctx, addr, req, rsp, opts)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(ClientRequestLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(ClientRequestDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(ClientRequestTotal, lopts...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *wrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
|
||||
|
||||
ts := time.Now()
|
||||
err := w.Client.Call(ctx, req, rsp, opts...)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(ClientRequestLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(ClientRequestDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(ClientRequestTotal, lopts...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *wrapper) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
|
||||
endpoint := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
|
||||
|
||||
ts := time.Now()
|
||||
stream, err := w.Client.Stream(ctx, req, opts...)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(ClientRequestLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(ClientRequestDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(ClientRequestTotal, lopts...).Inc()
|
||||
|
||||
return stream, err
|
||||
}
|
||||
|
||||
func (w *wrapper) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||
endpoint := p.Topic()
|
||||
|
||||
ts := time.Now()
|
||||
err := w.Client.Publish(ctx, p, opts...)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(PublishMessageLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(PublishMessageDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(PublishMessageTotal, lopts...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func NewHandlerWrapper(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.Endpoint()
|
||||
|
||||
ts := time.Now()
|
||||
err := fn(ctx, req, rsp)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(ServerRequestLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(ServerRequestDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(ServerRequestTotal, lopts...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func NewSubscriberWrapper(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()
|
||||
|
||||
ts := time.Now()
|
||||
err := fn(ctx, msg)
|
||||
te := time.Since(ts)
|
||||
|
||||
lopts := w.opts.lopts
|
||||
lopts = append(lopts, meter.Label(labelEndpoint, endpoint))
|
||||
|
||||
w.opts.Meter.Summary(SubscribeMessageLatencyMicroseconds, lopts...).Update(float64(te.Seconds()))
|
||||
w.opts.Meter.Histogram(SubscribeMessageDurationSeconds, lopts...).Update(float64(te.Seconds()))
|
||||
|
||||
if err == nil {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelSuccess))
|
||||
} else {
|
||||
lopts = append(lopts, meter.Label(labelStatus, labelFailure))
|
||||
}
|
||||
w.opts.Meter.Counter(SubscribeMessageTotal, lopts...).Inc()
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
119
micro.go
119
micro.go
@@ -1,119 +0,0 @@
|
||||
// Package micro is a pluggable framework for microservices
|
||||
package micro
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/broker"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
type serviceKey struct{}
|
||||
|
||||
// Service is an interface that wraps the lower level libraries
|
||||
// within micro. Its a convenience method for building
|
||||
// and initialising services.
|
||||
type Service interface {
|
||||
// The service name
|
||||
Name() string
|
||||
// Init initialises options
|
||||
Init(...Option) error
|
||||
// Options returns the current options
|
||||
Options() Options
|
||||
// Client is used to call services
|
||||
Client() client.Client
|
||||
// Server is for handling requests and events
|
||||
Server() server.Server
|
||||
// Broker is for broker usage
|
||||
Broker() broker.Broker
|
||||
// Run the service
|
||||
Run() error
|
||||
// The service implementation
|
||||
String() string
|
||||
}
|
||||
|
||||
// Function is a one time executing Service
|
||||
type Function interface {
|
||||
// Inherits Service interface
|
||||
Service
|
||||
// Done signals to complete execution
|
||||
Done() error
|
||||
// Handle registers an RPC handler
|
||||
Handle(v interface{}) error
|
||||
// Subscribe registers a subscriber
|
||||
Subscribe(topic string, v interface{}) error
|
||||
}
|
||||
|
||||
/*
|
||||
// Type Event is a future type for acting on asynchronous events
|
||||
type Event interface {
|
||||
// Publish publishes a message to the event topic
|
||||
Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error
|
||||
// Subscribe to the event
|
||||
Subscribe(ctx context.Context, v in
|
||||
}
|
||||
|
||||
// Resource is a future type for defining dependencies
|
||||
type Resource interface {
|
||||
// Name of the resource
|
||||
Name() string
|
||||
// Type of resource
|
||||
Type() string
|
||||
// Method of creation
|
||||
Create() error
|
||||
}
|
||||
*/
|
||||
|
||||
// Event is used to publish messages to a topic
|
||||
type Event interface {
|
||||
// Publish publishes a message to the event topic
|
||||
Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error
|
||||
}
|
||||
|
||||
var (
|
||||
// HeaderPrefix for all headers passed
|
||||
HeaderPrefix = "Micro-"
|
||||
)
|
||||
|
||||
// NewService creates and returns a new Service based on the packages within.
|
||||
func NewService(opts ...Option) Service {
|
||||
return newService(opts...)
|
||||
}
|
||||
|
||||
// FromContext retrieves a Service from the Context.
|
||||
func FromContext(ctx context.Context) (Service, bool) {
|
||||
if ctx == nil {
|
||||
return nil, false
|
||||
}
|
||||
s, ok := ctx.Value(serviceKey{}).(Service)
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// NewContext returns a new Context with the Service embedded within it.
|
||||
func NewContext(ctx context.Context, s Service) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, serviceKey{}, s)
|
||||
}
|
||||
|
||||
// NewFunction returns a new Function for a one time executing Service
|
||||
func NewFunction(opts ...Option) Function {
|
||||
return newFunction(opts...)
|
||||
}
|
||||
|
||||
// NewEvent creates a new event publisher
|
||||
func NewEvent(topic string, c client.Client) Event {
|
||||
return &event{c, topic}
|
||||
}
|
||||
|
||||
// RegisterHandler is syntactic sugar for registering a handler
|
||||
func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error {
|
||||
return s.Handle(s.NewHandler(h, opts...))
|
||||
}
|
||||
|
||||
// RegisterSubscriber is syntactic sugar for registering a subscriber
|
||||
func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error {
|
||||
return s.Subscribe(s.NewSubscriber(topic, h, opts...))
|
||||
}
|
@@ -1,3 +1,5 @@
|
||||
// +build ignore
|
||||
|
||||
// Package model is an interface for data modelling
|
||||
package model
|
||||
|
||||
|
@@ -1,3 +1,5 @@
|
||||
// +build ignore
|
||||
|
||||
// Package model is an interface for data modelling
|
||||
package model
|
||||
|
||||
|
@@ -15,6 +15,18 @@ type Option func(*Options)
|
||||
|
||||
// Options configure network
|
||||
type Options struct {
|
||||
// Router used for routing
|
||||
Router router.Router
|
||||
// Proxy holds the proxy
|
||||
Proxy proxy.Proxy
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Tunnel used for transfer data
|
||||
Tunnel tunnel.Tunnel
|
||||
// Id of the node
|
||||
Id string
|
||||
// Name of the network
|
||||
@@ -25,18 +37,6 @@ type Options struct {
|
||||
Advertise string
|
||||
// Nodes is a list of nodes to connect to
|
||||
Nodes []string
|
||||
// Tunnel is network tunnel
|
||||
Tunnel tunnel.Tunnel
|
||||
// Router is network router
|
||||
Router router.Router
|
||||
// Proxy is network proxy
|
||||
Proxy proxy.Proxy
|
||||
// Logger
|
||||
Logger logger.Logger
|
||||
// Meter
|
||||
Meter meter.Meter
|
||||
// Tracer
|
||||
Tracer tracer.Tracer
|
||||
}
|
||||
|
||||
// Id sets the id of the network node
|
||||
|
258
network/transport/memory.go
Normal file
258
network/transport/memory.go
Normal file
@@ -0,0 +1,258 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
maddr "github.com/unistack-org/micro/v3/util/addr"
|
||||
mnet "github.com/unistack-org/micro/v3/util/net"
|
||||
"github.com/unistack-org/micro/v3/util/rand"
|
||||
)
|
||||
|
||||
type memorySocket struct {
|
||||
ctx context.Context
|
||||
recv chan *Message
|
||||
exit chan bool
|
||||
lexit chan bool
|
||||
send chan *Message
|
||||
local string
|
||||
remote string
|
||||
timeout time.Duration
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type memoryClient struct {
|
||||
*memorySocket
|
||||
opts DialOptions
|
||||
}
|
||||
|
||||
type memoryListener struct {
|
||||
topts Options
|
||||
ctx context.Context
|
||||
lopts ListenOptions
|
||||
exit chan bool
|
||||
conn chan *memorySocket
|
||||
addr string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type memoryTransport struct {
|
||||
opts Options
|
||||
listeners map[string]*memoryListener
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Recv(m *Message) error {
|
||||
ms.RLock()
|
||||
defer ms.RUnlock()
|
||||
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
return errors.New("connection closed")
|
||||
case <-ms.lexit:
|
||||
return errors.New("server connection closed")
|
||||
case cm := <-ms.recv:
|
||||
*m = *cm
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Local() string {
|
||||
return ms.local
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Remote() string {
|
||||
return ms.remote
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Send(m *Message) error {
|
||||
ms.RLock()
|
||||
defer ms.RUnlock()
|
||||
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
return errors.New("connection closed")
|
||||
case <-ms.lexit:
|
||||
return errors.New("server connection closed")
|
||||
case ms.send <- m:
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Close() error {
|
||||
ms.Lock()
|
||||
defer ms.Unlock()
|
||||
select {
|
||||
case <-ms.exit:
|
||||
return nil
|
||||
default:
|
||||
close(ms.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Addr() string {
|
||||
return m.addr
|
||||
}
|
||||
|
||||
func (m *memoryListener) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
default:
|
||||
close(m.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Accept(fn func(Socket)) error {
|
||||
for {
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
case c := <-m.conn:
|
||||
go fn(&memorySocket{
|
||||
lexit: c.lexit,
|
||||
exit: c.exit,
|
||||
send: c.recv,
|
||||
recv: c.send,
|
||||
local: c.Remote(),
|
||||
remote: c.Local(),
|
||||
timeout: m.topts.Timeout,
|
||||
ctx: m.topts.Context,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Dial(ctx context.Context, addr string, opts ...DialOption) (Client, error) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
listener, ok := m.listeners[addr]
|
||||
if !ok {
|
||||
return nil, errors.New("could not dial " + addr)
|
||||
}
|
||||
|
||||
options := NewDialOptions(opts...)
|
||||
|
||||
client := &memoryClient{
|
||||
&memorySocket{
|
||||
send: make(chan *Message),
|
||||
recv: make(chan *Message),
|
||||
exit: make(chan bool),
|
||||
lexit: listener.exit,
|
||||
local: addr,
|
||||
remote: addr,
|
||||
timeout: m.opts.Timeout,
|
||||
ctx: m.opts.Context,
|
||||
},
|
||||
options,
|
||||
}
|
||||
|
||||
// pseudo connect
|
||||
select {
|
||||
case <-listener.exit:
|
||||
return nil, errors.New("connection error")
|
||||
case listener.conn <- client.memorySocket:
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Listen(ctx context.Context, addr string, opts ...ListenOption) (Listener, error) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
options := NewListenOptions(opts...)
|
||||
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addr, err = maddr.Extract(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// if zero port then randomly assign one
|
||||
if len(port) > 0 && port == "0" {
|
||||
var rng rand.Rand
|
||||
i := rng.Intn(20000)
|
||||
port = fmt.Sprintf("%d", 10000+i)
|
||||
}
|
||||
|
||||
// set addr with port
|
||||
addr = mnet.HostPort(addr, port)
|
||||
|
||||
if _, ok := m.listeners[addr]; ok {
|
||||
return nil, errors.New("already listening on " + addr)
|
||||
}
|
||||
|
||||
listener := &memoryListener{
|
||||
lopts: options,
|
||||
topts: m.opts,
|
||||
addr: addr,
|
||||
conn: make(chan *memorySocket),
|
||||
exit: make(chan bool),
|
||||
ctx: m.opts.Context,
|
||||
}
|
||||
|
||||
m.listeners[addr] = listener
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Options() Options {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memoryTransport) String() string {
|
||||
return "memory"
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Name() string {
|
||||
return m.opts.Name
|
||||
}
|
||||
|
||||
// NewTransport returns new memory transport with options
|
||||
func NewTransport(opts ...Option) Transport {
|
||||
options := NewOptions(opts...)
|
||||
|
||||
return &memoryTransport{
|
||||
opts: options,
|
||||
listeners: make(map[string]*memoryListener),
|
||||
}
|
||||
}
|
93
network/transport/memory_test.go
Normal file
93
network/transport/memory_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMemoryTransport(t *testing.T) {
|
||||
tr := NewTransport()
|
||||
ctx := context.Background()
|
||||
// bind / listen
|
||||
l, err := tr.Listen(ctx, "127.0.0.1:8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// accept
|
||||
go func() {
|
||||
if err := l.Accept(func(sock Socket) {
|
||||
for {
|
||||
var m Message
|
||||
if err := sock.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
if len(os.Getenv("INTEGRATION_TESTS")) == 0 {
|
||||
t.Logf("Server Received %s", string(m.Body))
|
||||
}
|
||||
if err := sock.Send(&Message{
|
||||
Body: []byte(`pong`),
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatalf("Unexpected error accepting %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// dial
|
||||
c, err := tr.Dial(ctx, "127.0.0.1:8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error dialing %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// send <=> receive
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := c.Send(&Message{
|
||||
Body: []byte(`ping`),
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
var m Message
|
||||
if err := c.Recv(&m); err != nil {
|
||||
return
|
||||
}
|
||||
if len(os.Getenv("INTEGRATION_TESTS")) == 0 {
|
||||
t.Logf("Client Received %s", string(m.Body))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestListener(t *testing.T) {
|
||||
tr := NewTransport()
|
||||
ctx := context.Background()
|
||||
// bind / listen on random port
|
||||
l, err := tr.Listen(ctx, ":0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// try again
|
||||
l2, err := tr.Listen(ctx, ":0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l2.Close()
|
||||
|
||||
// now make sure it still fails
|
||||
l3, err := tr.Listen(ctx, ":8080")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error listening %v", err)
|
||||
}
|
||||
defer l3.Close()
|
||||
|
||||
if _, err := tr.Listen(ctx, ":8080"); err == nil {
|
||||
t.Fatal("Expected error binding to :8080 got nil")
|
||||
}
|
||||
}
|
@@ -1,77 +0,0 @@
|
||||
package transport
|
||||
|
||||
import "context"
|
||||
|
||||
type noopTransport struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
// NewTransport creates new noop transport
|
||||
func NewTransport(opts ...Option) Transport {
|
||||
return &noopTransport{opts: NewOptions(opts...)}
|
||||
}
|
||||
|
||||
func (t *noopTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&t.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *noopTransport) Options() Options {
|
||||
return t.opts
|
||||
}
|
||||
|
||||
func (t *noopTransport) Dial(ctx context.Context, addr string, opts ...DialOption) (Client, error) {
|
||||
options := NewDialOptions(opts...)
|
||||
return &noopClient{opts: options}, nil
|
||||
}
|
||||
|
||||
func (t *noopTransport) Listen(ctx context.Context, addr string, opts ...ListenOption) (Listener, error) {
|
||||
options := NewListenOptions(opts...)
|
||||
return &noopListener{opts: options}, nil
|
||||
}
|
||||
|
||||
func (t *noopTransport) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
type noopClient struct {
|
||||
opts DialOptions
|
||||
}
|
||||
|
||||
func (c *noopClient) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *noopClient) Local() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *noopClient) Remote() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *noopClient) Recv(*Message) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *noopClient) Send(*Message) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type noopListener struct {
|
||||
opts ListenOptions
|
||||
}
|
||||
|
||||
func (l *noopListener) Addr() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (l *noopListener) Accept(fn func(Socket)) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *noopListener) Close() error {
|
||||
return nil
|
||||
}
|
@@ -11,30 +11,26 @@ import (
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
)
|
||||
|
||||
// Options struct holds the transport options
|
||||
type Options struct {
|
||||
// Addrs is the list of intermediary addresses to connect to
|
||||
Addrs []string
|
||||
// Codec is the codec interface to use where headers are not supported
|
||||
// by the transport and the entire payload must be encoded
|
||||
Codec codec.Codec
|
||||
// Secure tells the transport to secure the connection.
|
||||
// In the case TLSConfig is not specified best effort self-signed
|
||||
// certs should be used
|
||||
Secure bool
|
||||
// TLSConfig to secure the connection. The assumption is that this
|
||||
// is mTLS keypair
|
||||
TLSConfig *tls.Config
|
||||
// Timeout sets the timeout for Send/Recv
|
||||
Timeout time.Duration
|
||||
// Logger sets the logger
|
||||
Logger logger.Logger
|
||||
// Meter sets the meter
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Tracer
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Codec used for marshal/unmarshal messages
|
||||
Codec codec.Codec
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Context holds external options
|
||||
Context context.Context
|
||||
// TLSConfig holds tls.TLSConfig options
|
||||
TLSConfig *tls.Config
|
||||
// Name holds the transport name
|
||||
Name string
|
||||
// Addrs holds the transport addrs
|
||||
Addrs []string
|
||||
// Timeout holds the timeout
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// NewOptions returns new options
|
||||
@@ -55,18 +51,12 @@ func NewOptions(opts ...Option) Options {
|
||||
|
||||
// DialOptions struct
|
||||
type DialOptions struct {
|
||||
// Tells the transport this is a streaming connection with
|
||||
// multiple calls to send/recv and that send may not even be called
|
||||
Stream bool
|
||||
// Timeout for dialing
|
||||
Timeout time.Duration
|
||||
|
||||
// TODO: add tls options when dialling
|
||||
// Currently set in global options
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context holds the external options
|
||||
Context context.Context
|
||||
// Timeout holds the timeout
|
||||
Timeout time.Duration
|
||||
// Stream flag
|
||||
Stream bool
|
||||
}
|
||||
|
||||
// NewDialOptions returns new DialOptions
|
||||
@@ -87,10 +77,10 @@ func NewDialOptions(opts ...DialOption) DialOptions {
|
||||
type ListenOptions struct {
|
||||
// TODO: add tls options when listening
|
||||
// Currently set in global options
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context holds the external options
|
||||
Context context.Context
|
||||
// TLSConfig holds the *tls.Config options
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
// NewListenOptions returns new ListenOptions
|
||||
@@ -176,3 +166,10 @@ func Tracer(t tracer.Tracer) Option {
|
||||
o.Tracer = t
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
@@ -11,7 +11,7 @@ import (
|
||||
var (
|
||||
// DefaultTransport is the global default transport
|
||||
DefaultTransport Transport = NewTransport()
|
||||
// Default dial timeout
|
||||
// DefaultDialTimeout the default dial timeout
|
||||
DefaultDialTimeout = time.Second * 5
|
||||
)
|
||||
|
||||
|
@@ -17,17 +17,16 @@ type tunBroker struct {
|
||||
}
|
||||
|
||||
type tunSubscriber struct {
|
||||
topic string
|
||||
handler broker.Handler
|
||||
opts broker.SubscribeOptions
|
||||
|
||||
closed chan bool
|
||||
opts broker.SubscribeOptions
|
||||
listener tunnel.Listener
|
||||
handler broker.Handler
|
||||
closed chan bool
|
||||
topic string
|
||||
}
|
||||
|
||||
type tunEvent struct {
|
||||
topic string
|
||||
message *broker.Message
|
||||
topic string
|
||||
}
|
||||
|
||||
// used to access tunnel from options context
|
||||
@@ -41,6 +40,10 @@ func (t *tunBroker) Init(opts ...broker.Option) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *tunBroker) Name() string {
|
||||
return t.opts.Name
|
||||
}
|
||||
|
||||
func (t *tunBroker) Options() broker.Options {
|
||||
return t.opts
|
||||
}
|
||||
@@ -171,6 +174,7 @@ func (t *tunEvent) Error() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewBroker returns new tunnel broker
|
||||
func NewBroker(opts ...broker.Option) (broker.Broker, error) {
|
||||
options := broker.NewOptions(opts...)
|
||||
|
||||
|
@@ -13,31 +13,33 @@ import (
|
||||
var (
|
||||
// DefaultAddress is default tunnel bind address
|
||||
DefaultAddress = ":0"
|
||||
// The shared default token
|
||||
// DefaultToken the shared default token
|
||||
DefaultToken = "go.micro.tunnel"
|
||||
)
|
||||
|
||||
// Option func
|
||||
// Option func signature
|
||||
type Option func(*Options)
|
||||
|
||||
// Options provides network configuration options
|
||||
type Options struct {
|
||||
// Id is tunnel id
|
||||
Id string
|
||||
// Address is tunnel address
|
||||
Address string
|
||||
// Nodes are remote nodes
|
||||
Nodes []string
|
||||
// The shared auth token
|
||||
Token string
|
||||
// Transport listens to incoming connections
|
||||
Transport transport.Transport
|
||||
// Logger
|
||||
// Logger used for logging
|
||||
Logger logger.Logger
|
||||
// Meter
|
||||
// Meter used for metrics
|
||||
Meter meter.Meter
|
||||
// Tracer
|
||||
// Tracer used for tracing
|
||||
Tracer tracer.Tracer
|
||||
// Transport used for communication
|
||||
Transport transport.Transport
|
||||
// Token the shared auth token
|
||||
Token string
|
||||
// Name holds the tunnel name
|
||||
Name string
|
||||
// Id holds the tunnel id
|
||||
Id string
|
||||
// Address holds the tunnel address
|
||||
Address string
|
||||
// Nodes holds the tunnel nodes
|
||||
Nodes []string
|
||||
}
|
||||
|
||||
// DialOption func
|
||||
@@ -60,9 +62,9 @@ type ListenOption func(*ListenOptions)
|
||||
|
||||
// ListenOptions provides listen options
|
||||
type ListenOptions struct {
|
||||
// specify mode of the session
|
||||
// Mode specify mode of the session
|
||||
Mode Mode
|
||||
// The read timeout
|
||||
// Timeout the read timeout
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
@@ -159,7 +161,7 @@ func DialWait(b bool) DialOption {
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultOptions returns router default options
|
||||
// NewOptions returns router default options with filled values
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Id: uuid.New().String(),
|
||||
@@ -181,3 +183,10 @@ func Tracer(t tracer.Tracer) Option {
|
||||
o.Tracer = t
|
||||
}
|
||||
}
|
||||
|
||||
// Name sets the name
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Name = n
|
||||
}
|
||||
}
|
||||
|
@@ -88,7 +88,7 @@ func NewTransport(opts ...transport.Option) transport.Transport {
|
||||
}
|
||||
|
||||
// initialise
|
||||
t.Init(opts...)
|
||||
//t.Init(opts...)
|
||||
|
||||
return t
|
||||
}
|
||||
|
@@ -10,15 +10,16 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultTunnel contains default tunnel implementation
|
||||
DefaultTunnel Tunnel
|
||||
)
|
||||
|
||||
const (
|
||||
// send over one link
|
||||
// Unicast send over one link
|
||||
Unicast Mode = iota
|
||||
// send to all channel listeners
|
||||
// Multicast send to all channel listeners
|
||||
Multicast
|
||||
// send to all links
|
||||
// Broadcast send to all links
|
||||
Broadcast
|
||||
)
|
||||
|
||||
@@ -33,7 +34,7 @@ var (
|
||||
ErrLinkNotFound = errors.New("link not found")
|
||||
// ErrLinkDisconnected is returned when a link we attempt to send to is disconnected
|
||||
ErrLinkDisconnected = errors.New("link not connected")
|
||||
// ErrLinkLoppback is returned when attempting to send an outbound message over loopback link
|
||||
// ErrLinkLoopback is returned when attempting to send an outbound message over loopback link
|
||||
ErrLinkLoopback = errors.New("link is loopback")
|
||||
// ErrLinkRemote is returned when attempting to send a loopback message over remote link
|
||||
ErrLinkRemote = errors.New("link is remote")
|
||||
@@ -87,7 +88,7 @@ type Link interface {
|
||||
transport.Socket
|
||||
}
|
||||
|
||||
// The listener provides similar constructs to the transport.Listener
|
||||
// Listener provides similar constructs to the transport.Listener
|
||||
type Listener interface {
|
||||
Accept() (Session, error)
|
||||
Channel() string
|
||||
|
699
options.go
699
options.go
@@ -2,72 +2,88 @@ package micro
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/unistack-org/micro/v3/auth"
|
||||
"github.com/unistack-org/micro/v3/broker"
|
||||
"github.com/unistack-org/micro/v3/client"
|
||||
"github.com/unistack-org/micro/v3/config"
|
||||
"github.com/unistack-org/micro/v3/debug/profile"
|
||||
"github.com/unistack-org/micro/v3/logger"
|
||||
"github.com/unistack-org/micro/v3/metadata"
|
||||
"github.com/unistack-org/micro/v3/meter"
|
||||
"github.com/unistack-org/micro/v3/registry"
|
||||
"github.com/unistack-org/micro/v3/register"
|
||||
"github.com/unistack-org/micro/v3/router"
|
||||
"github.com/unistack-org/micro/v3/runtime"
|
||||
"github.com/unistack-org/micro/v3/selector"
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
"github.com/unistack-org/micro/v3/store"
|
||||
"github.com/unistack-org/micro/v3/tracer"
|
||||
// "github.com/unistack-org/micro/v3/profiler"
|
||||
// "github.com/unistack-org/micro/v3/runtime"
|
||||
)
|
||||
|
||||
// Options for micro service
|
||||
type Options struct {
|
||||
Auth auth.Auth
|
||||
Broker broker.Broker
|
||||
Logger logger.Logger
|
||||
Meter meter.Meter
|
||||
Configs []config.Config
|
||||
Client client.Client
|
||||
Server server.Server
|
||||
Store store.Store
|
||||
Registry registry.Registry
|
||||
Tracer tracer.Tracer
|
||||
Router router.Router
|
||||
Runtime runtime.Runtime
|
||||
Profile profile.Profile
|
||||
|
||||
// Before and After funcs
|
||||
BeforeStart []func(context.Context) error
|
||||
BeforeStop []func(context.Context) error
|
||||
AfterStart []func(context.Context) error
|
||||
AfterStop []func(context.Context) error
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
// Context holds external options or cancel stuff
|
||||
Context context.Context
|
||||
// Metadata holds service metadata
|
||||
Metadata metadata.Metadata
|
||||
// Version holds service version
|
||||
Version string
|
||||
// Name holds service name
|
||||
Name string
|
||||
// Brokers holds brokers
|
||||
Brokers []broker.Broker
|
||||
// Loggers holds loggers
|
||||
Loggers []logger.Logger
|
||||
// Meters holds meter
|
||||
Meters []meter.Meter
|
||||
// Configs holds config
|
||||
Configs []config.Config
|
||||
// Clients holds clients
|
||||
Clients []client.Client
|
||||
// Auths holds auths
|
||||
Auths []auth.Auth
|
||||
// Stores holds stores
|
||||
Stores []store.Store
|
||||
// Registers holds registers
|
||||
Registers []register.Register
|
||||
// Tracers holds tracers
|
||||
Tracers []tracer.Tracer
|
||||
// Routers holds routers
|
||||
Routers []router.Router
|
||||
// BeforeStart holds funcs that runs before service starts
|
||||
BeforeStart []func(context.Context) error
|
||||
// BeforeStop holds funcs that runs before service stops
|
||||
BeforeStop []func(context.Context) error
|
||||
// AfterStart holds funcs that runs after service starts
|
||||
AfterStart []func(context.Context) error
|
||||
// AfterStop holds funcs that runs after service stops
|
||||
AfterStop []func(context.Context) error
|
||||
// Servers holds servers
|
||||
Servers []server.Server
|
||||
}
|
||||
|
||||
// NewOptions returns new Options filled with defaults and overrided by provided opts
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
Server: server.DefaultServer,
|
||||
Client: client.DefaultClient,
|
||||
Broker: broker.DefaultBroker,
|
||||
Registry: registry.DefaultRegistry,
|
||||
Router: router.DefaultRouter,
|
||||
Auth: auth.DefaultAuth,
|
||||
Logger: logger.DefaultLogger,
|
||||
Tracer: tracer.DefaultTracer,
|
||||
Meter: meter.DefaultMeter,
|
||||
Configs: []config.Config{config.DefaultConfig},
|
||||
Store: store.DefaultStore,
|
||||
Context: context.Background(),
|
||||
Servers: []server.Server{server.DefaultServer},
|
||||
Clients: []client.Client{client.DefaultClient},
|
||||
Brokers: []broker.Broker{broker.DefaultBroker},
|
||||
Registers: []register.Register{register.DefaultRegister},
|
||||
Routers: []router.Router{router.DefaultRouter},
|
||||
Auths: []auth.Auth{auth.DefaultAuth},
|
||||
Loggers: []logger.Logger{logger.DefaultLogger},
|
||||
Tracers: []tracer.Tracer{tracer.DefaultTracer},
|
||||
Meters: []meter.Meter{meter.DefaultMeter},
|
||||
Configs: []config.Config{config.DefaultConfig},
|
||||
Stores: []store.Store{store.DefaultStore},
|
||||
//Runtime runtime.Runtime
|
||||
//Profile profile.Profile
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
//nolint:errcheck
|
||||
o(&options)
|
||||
}
|
||||
|
||||
@@ -75,274 +91,619 @@ func NewOptions(opts ...Option) Options {
|
||||
}
|
||||
|
||||
// Option func
|
||||
type Option func(*Options)
|
||||
type Option func(*Options) error
|
||||
|
||||
// Broker to be used for service
|
||||
func Broker(b broker.Broker) Option {
|
||||
return func(o *Options) {
|
||||
o.Broker = b
|
||||
if o.Client != nil {
|
||||
// Update Client and Server
|
||||
o.Client.Init(client.Broker(b))
|
||||
// Broker to be used for client and server
|
||||
func Broker(b broker.Broker, opts ...BrokerOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
bopts := brokerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&bopts)
|
||||
}
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Broker(b))
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range bopts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.Broker(b)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, cli := range o.Clients {
|
||||
for _, oc := range bopts.clients {
|
||||
if cli.Name() == oc || all {
|
||||
if err = cli.Init(client.Broker(b)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type brokerOptions struct {
|
||||
servers []string
|
||||
clients []string
|
||||
}
|
||||
|
||||
// BrokerOption func signature
|
||||
type BrokerOption func(*brokerOptions)
|
||||
|
||||
// BrokerClient specifies clients for broker
|
||||
func BrokerClient(n string) BrokerOption {
|
||||
return func(o *brokerOptions) {
|
||||
o.clients = append(o.clients, n)
|
||||
}
|
||||
}
|
||||
|
||||
// BrokerServer specifies servers for broker
|
||||
func BrokerServer(n string) BrokerOption {
|
||||
return func(o *brokerOptions) {
|
||||
o.servers = append(o.servers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// Client to be used for service
|
||||
func Client(c client.Client) Option {
|
||||
return func(o *Options) {
|
||||
o.Client = c
|
||||
func Client(c ...client.Client) Option {
|
||||
return func(o *Options) error {
|
||||
o.Clients = c
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Clients to be used for service
|
||||
func Clients(c ...client.Client) Option {
|
||||
return func(o *Options) error {
|
||||
o.Clients = c
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Context specifies a context for the service.
|
||||
// Can be used to signal shutdown of the service and for extra option values.
|
||||
func Context(ctx context.Context) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
// TODO: Pass context to underline stuff ?
|
||||
o.Context = ctx
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// Profile to be used for debug profile
|
||||
func Profile(p profile.Profile) Option {
|
||||
return func(o *Options) {
|
||||
o.Profile = p
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// Server to be used for service
|
||||
func Server(s server.Server) Option {
|
||||
return func(o *Options) {
|
||||
o.Server = s
|
||||
func Server(s ...server.Server) Option {
|
||||
return func(o *Options) error {
|
||||
o.Servers = s
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Servers to be used for service
|
||||
func Servers(s ...server.Server) Option {
|
||||
return func(o *Options) error {
|
||||
o.Servers = s
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Store sets the store to use
|
||||
func Store(s store.Store) Option {
|
||||
return func(o *Options) {
|
||||
o.Store = s
|
||||
func Store(s ...store.Store) Option {
|
||||
return func(o *Options) error {
|
||||
o.Stores = s
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Stores sets the store to use
|
||||
func Stores(s ...store.Store) Option {
|
||||
return func(o *Options) error {
|
||||
o.Stores = s
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Logger set the logger to use
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
//nolint:gocyclo
|
||||
func Logger(l logger.Logger, opts ...LoggerOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
lopts := loggerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&lopts)
|
||||
}
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range lopts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, cli := range o.Clients {
|
||||
for _, oc := range lopts.clients {
|
||||
if cli.Name() == oc || all {
|
||||
if err = cli.Init(client.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, brk := range o.Brokers {
|
||||
for _, ob := range lopts.brokers {
|
||||
if brk.Name() == ob || all {
|
||||
if err = brk.Init(broker.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, reg := range o.Registers {
|
||||
for _, or := range lopts.registers {
|
||||
if reg.Name() == or || all {
|
||||
if err = reg.Init(register.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, str := range o.Stores {
|
||||
for _, or := range lopts.stores {
|
||||
if str.Name() == or || all {
|
||||
if err = str.Init(store.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, mtr := range o.Meters {
|
||||
for _, or := range lopts.meters {
|
||||
if mtr.Name() == or || all {
|
||||
if err = mtr.Init(meter.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, trc := range o.Tracers {
|
||||
for _, ot := range lopts.tracers {
|
||||
if trc.Name() == ot || all {
|
||||
if err = trc.Init(tracer.Logger(l)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// LoggerOption func signature
|
||||
type LoggerOption func(*loggerOptions)
|
||||
|
||||
// loggerOptions
|
||||
type loggerOptions struct {
|
||||
servers []string
|
||||
clients []string
|
||||
brokers []string
|
||||
registers []string
|
||||
stores []string
|
||||
meters []string
|
||||
tracers []string
|
||||
}
|
||||
|
||||
/*
|
||||
func LoggerServer(n string) LoggerOption {
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
// Meter set the meter to use
|
||||
func Meter(m meter.Meter) Option {
|
||||
return func(o *Options) {
|
||||
o.Meter = m
|
||||
func Meter(m ...meter.Meter) Option {
|
||||
return func(o *Options) error {
|
||||
o.Meters = m
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Registry sets the registry for the service
|
||||
// Meters set the meter to use
|
||||
func Meters(m ...meter.Meter) Option {
|
||||
return func(o *Options) error {
|
||||
o.Meters = m
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Register sets the register for the service
|
||||
// and the underlying components
|
||||
func Registry(r registry.Registry) Option {
|
||||
return func(o *Options) {
|
||||
o.Registry = r
|
||||
if o.Router != nil {
|
||||
// Update router
|
||||
o.Router.Init(router.Registry(r))
|
||||
//nolint:gocyclo
|
||||
func Register(r register.Register, opts ...RegisterOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
ropts := registerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&ropts)
|
||||
}
|
||||
if o.Server != nil {
|
||||
// Update server
|
||||
o.Server.Init(server.Registry(r))
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
if o.Broker != nil {
|
||||
// Update Broker
|
||||
o.Broker.Init(broker.Registry(r))
|
||||
for _, rtr := range o.Routers {
|
||||
for _, os := range ropts.routers {
|
||||
if rtr.Name() == os || all {
|
||||
if err = rtr.Init(router.Register(r)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range ropts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.Register(r)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, brk := range o.Brokers {
|
||||
for _, os := range ropts.brokers {
|
||||
if brk.Name() == os || all {
|
||||
if err = brk.Init(broker.Register(r)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Tracer sets the tracer for the service
|
||||
func Tracer(t tracer.Tracer) Option {
|
||||
return func(o *Options) {
|
||||
o.Tracer = t
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Tracer(t))
|
||||
}
|
||||
if o.Client != nil {
|
||||
o.Client.Init(client.Tracer(t))
|
||||
}
|
||||
type registerOptions struct {
|
||||
routers []string
|
||||
servers []string
|
||||
brokers []string
|
||||
}
|
||||
|
||||
// RegisterOption func signature
|
||||
type RegisterOption func(*registerOptions)
|
||||
|
||||
// RegisterRouter speciefies routers for register
|
||||
func RegisterRouter(n string) RegisterOption {
|
||||
return func(o *registerOptions) {
|
||||
o.routers = append(o.routers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterServer specifies servers for register
|
||||
func RegisterServer(n string) RegisterOption {
|
||||
return func(o *registerOptions) {
|
||||
o.servers = append(o.servers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterBroker specifies broker for register
|
||||
func RegisterBroker(n string) RegisterOption {
|
||||
return func(o *registerOptions) {
|
||||
o.brokers = append(o.brokers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// Tracer sets the tracer
|
||||
//nolint:gocyclo
|
||||
func Tracer(t tracer.Tracer, opts ...TracerOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
topts := tracerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&topts)
|
||||
}
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range topts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.Tracer(t)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, cli := range o.Clients {
|
||||
for _, os := range topts.clients {
|
||||
if cli.Name() == os || all {
|
||||
if err = cli.Init(client.Tracer(t)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, str := range o.Stores {
|
||||
for _, os := range topts.stores {
|
||||
if str.Name() == os || all {
|
||||
if err = str.Init(store.Tracer(t)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, brk := range o.Brokers {
|
||||
for _, os := range topts.brokers {
|
||||
if brk.Name() == os || all {
|
||||
if err = brk.Init(broker.Tracer(t)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type tracerOptions struct {
|
||||
clients []string
|
||||
servers []string
|
||||
brokers []string
|
||||
stores []string
|
||||
}
|
||||
|
||||
// TracerOption func signature
|
||||
type TracerOption func(*tracerOptions)
|
||||
|
||||
// TracerClient sets the clients for tracer
|
||||
func TracerClient(n string) TracerOption {
|
||||
return func(o *tracerOptions) {
|
||||
o.clients = append(o.clients, n)
|
||||
}
|
||||
}
|
||||
|
||||
// TracerServer sets the servers for tracer
|
||||
func TracerServer(n string) TracerOption {
|
||||
return func(o *tracerOptions) {
|
||||
o.servers = append(o.servers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// TracerBroker sets the broker for tracer
|
||||
func TracerBroker(n string) TracerOption {
|
||||
return func(o *tracerOptions) {
|
||||
o.brokers = append(o.brokers, n)
|
||||
}
|
||||
}
|
||||
|
||||
// TracerStore sets the store for tracer
|
||||
func TracerStore(n string) TracerOption {
|
||||
return func(o *tracerOptions) {
|
||||
o.stores = append(o.stores, n)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// Auth sets the auth for the service
|
||||
func Auth(a auth.Auth) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.Auth = a
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Auth(a))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// Config sets the config for the service
|
||||
func Config(c ...config.Config) Option {
|
||||
return func(o *Options) error {
|
||||
o.Configs = c
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Configs sets the configs for the service
|
||||
func Configs(c ...config.Config) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.Configs = c
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// Selector sets the selector for the service client
|
||||
func Selector(s selector.Selector) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
if o.Client != nil {
|
||||
o.Client.Init(client.Selector(s))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
/*
|
||||
// Runtime sets the runtime
|
||||
func Runtime(r runtime.Runtime) Option {
|
||||
return func(o *Options) {
|
||||
o.Runtime = r
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// Router sets the router
|
||||
func Router(r router.Router) Option {
|
||||
return func(o *Options) {
|
||||
o.Router = r
|
||||
// Update client
|
||||
if o.Client != nil {
|
||||
o.Client.Init(client.Router(r))
|
||||
func Router(r router.Router, opts ...RouterOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
ropts := routerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&ropts)
|
||||
}
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
for _, cli := range o.Clients {
|
||||
for _, os := range ropts.clients {
|
||||
if cli.Name() == os || all {
|
||||
if err = cli.Init(client.Router(r)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type routerOptions struct {
|
||||
clients []string
|
||||
}
|
||||
|
||||
// RouterOption func signature
|
||||
type RouterOption func(*routerOptions)
|
||||
|
||||
// RouterClient sets the clients for router
|
||||
func RouterClient(n string) RouterOption {
|
||||
return func(o *routerOptions) {
|
||||
o.clients = append(o.clients, n)
|
||||
}
|
||||
}
|
||||
|
||||
// Address sets the address of the server
|
||||
func Address(addr string) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Address(addr))
|
||||
return func(o *Options) error {
|
||||
switch len(o.Servers) {
|
||||
case 0:
|
||||
return fmt.Errorf("cant set address on nil server")
|
||||
case 1:
|
||||
break
|
||||
default:
|
||||
return fmt.Errorf("cant set same address for multiple servers")
|
||||
}
|
||||
return o.Servers[0].Init(server.Address(addr))
|
||||
}
|
||||
}
|
||||
|
||||
// Name of the service
|
||||
func Name(n string) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Name(n))
|
||||
}
|
||||
return func(o *Options) error {
|
||||
o.Name = n
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Version of the service
|
||||
func Version(v string) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Version(v))
|
||||
}
|
||||
return func(o *Options) error {
|
||||
o.Version = v
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata associated with the service
|
||||
func Metadata(md metadata.Metadata) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.Metadata(md))
|
||||
}
|
||||
return func(o *Options) error {
|
||||
o.Metadata = metadata.Copy(md)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterTTL specifies the TTL to use when registering the service
|
||||
func RegisterTTL(t time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.RegisterTTL(t))
|
||||
func RegisterTTL(td time.Duration, opts ...RegisterOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
ropts := registerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&ropts)
|
||||
}
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range ropts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.RegisterTTL(td)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterInterval specifies the interval on which to re-register
|
||||
func RegisterInterval(t time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
if o.Server != nil {
|
||||
o.Server.Init(server.RegisterInterval(t))
|
||||
func RegisterInterval(td time.Duration, opts ...RegisterOption) Option {
|
||||
return func(o *Options) error {
|
||||
var err error
|
||||
ropts := registerOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&ropts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WrapClient is a convenience method for wrapping a Client with
|
||||
// some middleware component. A list of wrappers can be provided.
|
||||
// Wrappers are applied in reverse order so the last is executed first.
|
||||
func WrapClient(w ...client.Wrapper) Option {
|
||||
return func(o *Options) {
|
||||
// apply in reverse
|
||||
for i := len(w); i > 0; i-- {
|
||||
o.Client = w[i-1](o.Client)
|
||||
all := false
|
||||
if len(opts) == 0 {
|
||||
all = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WrapCall is a convenience method for wrapping a Client CallFunc
|
||||
func WrapCall(w ...client.CallWrapper) Option {
|
||||
return func(o *Options) {
|
||||
o.Client.Init(client.WrapCall(w...))
|
||||
}
|
||||
}
|
||||
|
||||
// WrapHandler adds a handler Wrapper to a list of options passed into the server
|
||||
func WrapHandler(w ...server.HandlerWrapper) Option {
|
||||
return func(o *Options) {
|
||||
var wrappers []server.Option
|
||||
|
||||
for _, wrap := range w {
|
||||
wrappers = append(wrappers, server.WrapHandler(wrap))
|
||||
for _, srv := range o.Servers {
|
||||
for _, os := range ropts.servers {
|
||||
if srv.Name() == os || all {
|
||||
if err = srv.Init(server.RegisterInterval(td)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Init once
|
||||
o.Server.Init(wrappers...)
|
||||
}
|
||||
}
|
||||
|
||||
// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server
|
||||
func WrapSubscriber(w ...server.SubscriberWrapper) Option {
|
||||
return func(o *Options) {
|
||||
var wrappers []server.Option
|
||||
|
||||
for _, wrap := range w {
|
||||
wrappers = append(wrappers, server.WrapSubscriber(wrap))
|
||||
}
|
||||
|
||||
// Init once
|
||||
o.Server.Init(wrappers...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeStart run funcs before service starts
|
||||
func BeforeStart(fn func(context.Context) error) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.BeforeStart = append(o.BeforeStart, fn)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeStop run funcs before service stops
|
||||
func BeforeStop(fn func(context.Context) error) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.BeforeStop = append(o.BeforeStop, fn)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// AfterStart run funcs after service starts
|
||||
func AfterStart(fn func(context.Context) error) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.AfterStart = append(o.AfterStart, fn)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// AfterStop run funcs after service stops
|
||||
func AfterStop(fn func(context.Context) error) Option {
|
||||
return func(o *Options) {
|
||||
return func(o *Options) error {
|
||||
o.AfterStop = append(o.AfterStop, fn)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@@ -7,16 +7,17 @@ import (
|
||||
"net/http/pprof"
|
||||
"sync"
|
||||
|
||||
"github.com/unistack-org/micro/v3/debug/profile"
|
||||
profile "github.com/unistack-org/micro/v3/profiler"
|
||||
)
|
||||
|
||||
type httpProfile struct {
|
||||
server *http.Server
|
||||
sync.Mutex
|
||||
running bool
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultAddress for http profiler
|
||||
DefaultAddress = ":6060"
|
||||
)
|
||||
|
||||
@@ -60,7 +61,8 @@ func (h *httpProfile) String() string {
|
||||
return "http"
|
||||
}
|
||||
|
||||
func NewProfile(opts ...profile.Option) profile.Profile {
|
||||
// NewProfile returns new http profiler
|
||||
func NewProfile(opts ...profile.Option) profile.Profiler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
20
profiler/noop.go
Normal file
20
profiler/noop.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package profiler
|
||||
|
||||
type noopProfiler struct{}
|
||||
|
||||
func (p *noopProfiler) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *noopProfiler) Stop() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *noopProfiler) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
// NewProfiler returns new noop profiler
|
||||
func NewProfiler(opts ...Option) Profiler {
|
||||
return &noopProfiler{}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user