forked from go-kit/kit
/
service.go
164 lines (138 loc) · 4.38 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package addsvc
// This file contains the Service definition, and a basic service
// implementation. It also includes service middlewares.
import (
"errors"
"time"
"golang.org/x/net/context"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
)
// Service describes a service that adds things together.
type Service interface {
Sum(ctx context.Context, a, b int) (int, error)
Concat(ctx context.Context, a, b string) (string, error)
}
// Business-domain errors like these may be served in two ways: returned
// directly by endpoints, or bundled into the response struct. Both methods can
// be made to work, but errors returned directly by endpoints are counted by
// middlewares that check errors, like circuit breakers.
//
// If you don't want that behavior -- and you probably don't -- then it's better
// to bundle errors into the response struct.
var (
// ErrTwoZeroes is an arbitrary business rule for the Add method.
ErrTwoZeroes = errors.New("can't sum two zeroes")
// ErrIntOverflow protects the Add method. We've decided that this error
// indicates a misbehaving service and should count against e.g. circuit
// breakers. So, we return it directly in endpoints, to illustrate the
// difference. In a real service, this probably wouldn't be the case.
ErrIntOverflow = errors.New("integer overflow")
// ErrMaxSizeExceeded protects the Concat method.
ErrMaxSizeExceeded = errors.New("result exceeds maximum size")
)
// These annoying helper functions are required to translate Go error types to
// and from strings, which is the type we use in our IDLs to represent errors.
// There is special casing to treat empty strings as nil errors.
func str2err(s string) error {
if s == "" {
return nil
}
return errors.New(s)
}
func err2str(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// NewBasicService returns a naïve, stateless implementation of Service.
func NewBasicService() Service {
return basicService{}
}
type basicService struct{}
const (
intMax = 1<<31 - 1
intMin = -(intMax + 1)
maxLen = 102400
)
// Sum implements Service.
func (s basicService) Sum(_ context.Context, a, b int) (int, error) {
if a == 0 && b == 0 {
return 0, ErrTwoZeroes
}
if (b > 0 && a > (intMax-b)) || (b < 0 && a < (intMin-b)) {
return 0, ErrIntOverflow
}
return a + b, nil
}
// Concat implements Service.
func (s basicService) Concat(_ context.Context, a, b string) (string, error) {
if len(a)+len(b) > maxLen {
return "", ErrMaxSizeExceeded
}
return a + b, nil
}
// Middleware describes a service (as opposed to endpoint) middleware.
type Middleware func(Service) Service
// ServiceLoggingMiddleware returns a service middleware that logs the
// parameters and result of each method invocation.
func ServiceLoggingMiddleware(logger log.Logger) Middleware {
return func(next Service) Service {
return serviceLoggingMiddleware{
logger: logger,
next: next,
}
}
}
type serviceLoggingMiddleware struct {
logger log.Logger
next Service
}
func (mw serviceLoggingMiddleware) Sum(ctx context.Context, a, b int) (v int, err error) {
defer func(begin time.Time) {
mw.logger.Log(
"method", "Sum",
"a", a, "b", b, "result", v, "error", err,
"took", time.Since(begin),
)
}(time.Now())
return mw.next.Sum(ctx, a, b)
}
func (mw serviceLoggingMiddleware) Concat(ctx context.Context, a, b string) (v string, err error) {
defer func(begin time.Time) {
mw.logger.Log(
"method", "Concat",
"a", a, "b", b, "result", v, "error", err,
"took", time.Since(begin),
)
}(time.Now())
return mw.next.Concat(ctx, a, b)
}
// ServiceInstrumentingMiddleware returns a service middleware that instruments
// the number of integers summed and characters concatenated over the lifetime of
// the service.
func ServiceInstrumentingMiddleware(ints, chars metrics.Counter) Middleware {
return func(next Service) Service {
return serviceInstrumentingMiddleware{
ints: ints,
chars: chars,
next: next,
}
}
}
type serviceInstrumentingMiddleware struct {
ints metrics.Counter
chars metrics.Counter
next Service
}
func (mw serviceInstrumentingMiddleware) Sum(ctx context.Context, a, b int) (int, error) {
v, err := mw.next.Sum(ctx, a, b)
mw.ints.Add(float64(v))
return v, err
}
func (mw serviceInstrumentingMiddleware) Concat(ctx context.Context, a, b string) (string, error) {
v, err := mw.next.Concat(ctx, a, b)
mw.chars.Add(float64(len(v)))
return v, err
}