-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
346 lines (300 loc) · 8.67 KB
/
main.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"log"
"math/rand"
"net"
"sync"
"time"
"github.com/peter-crist/cloud-native-go/fanout"
pb "github.com/peter-crist/cloud-native-go/proto"
"github.com/peter-crist/cloud-native-go/circuitbreaker"
"github.com/peter-crist/cloud-native-go/debounce"
"github.com/peter-crist/cloud-native-go/fanin"
"github.com/peter-crist/cloud-native-go/retry"
"github.com/peter-crist/cloud-native-go/throttle"
"github.com/peter-crist/cloud-native-go/timeout"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
var (
port string = "5300"
)
func main() {
listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
opts := []grpc.ServerOption{}
s := grpc.NewServer(opts...)
pb.RegisterChatServer(s, &server{})
// TODO pull this out into separate cmd for demoing
conn := retry.Retry(slowConnection, 3, 10*time.Second)
_, err = conn(context.Background()) //parent context passed in
if err != nil {
log.Fatalf("failed to connect")
}
log.Printf("gRPC server listening on port %s...\n", port)
if err := s.Serve(listener); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
type server struct{}
//Send takes a message, performs a pseudo-slow operation, and returns the SHA of the message input
func (s *server) Send(
ctx context.Context,
req *pb.SendRequest,
) (
resp *pb.SendResponse,
err error,
) {
slowConnectionWithContext(ctx)
msg := req.GetMessage()
log.Printf("Received: %v", msg)
bv := []byte(msg)
hasher := sha1.New()
hasher.Write(bv)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
return &pb.SendResponse{
Message: fmt.Sprintf("Message sent: %s", msg),
Sha: sha,
}, nil
}
//CircuitBreaker takes in a request which specifies the desired failureThreshold and demonstrates
//the CircuitBreaker pattern with a pseudorandomally failing dependency
func (s *server) DemoCircuitBreaker(
ctx context.Context,
req *pb.CircuitBreakerRequest,
) (
*pb.CircuitBreakerResponse,
error,
) {
var (
resp string
err error
)
conn := circuitbreaker.Breaker(slowConnectionWithContext, uint(req.GetFailureThreshold()))
for i := 0; i < int(req.GetAttempts()); i++ {
ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Second*time.Duration(req.Timeout))
defer cancel()
resp, err = conn(ctxWithTimeout)
log.Printf("⏱ Waiting 0.5s before trying to connect again.\n\n")
time.Sleep(time.Millisecond * 500) //pause to simulate slower connection attempts to showcase resetting the breaker
}
log.Printf("🥳 %d connection attempts complete 🥳\n", req.GetAttempts())
if err != nil {
return nil, fmt.Errorf("Failed to connect to dependency after %d attempts", req.GetAttempts())
}
return &pb.CircuitBreakerResponse{Message: resp}, nil
}
func (s *server) DemoDebounce(
ctx context.Context,
req *pb.DebounceRequest,
) (
*pb.DebounceResponse,
error,
) {
var resp string
attempts := req.GetAttempts()
log.Println(req.GetDuration())
conn := debounce.DebounceFirst(
func(ctx context.Context) (string, error) {
return "success", nil
},
time.Second*time.Duration(req.GetDuration()),
)
log.Printf("💻 Spamming %d connection attempts\n", attempts)
for i := 0; i < int(attempts); i++ {
resp, _ = conn(ctx)
log.Printf("⏱ Waiting %dms before a new connection attempt...\n", req.GetDelay())
time.Sleep(time.Millisecond * time.Duration(req.GetDelay()))
}
log.Printf("🥳 %d/%d connection attempts complete 🥳\n", attempts, attempts)
return &pb.DebounceResponse{Message: resp}, nil
}
func (s *server) DemoRetry(
ctx context.Context,
req *pb.RetryRequest,
) (
*pb.RetryResponse,
error,
) {
conn := retry.Retry(
emulateTransientError,
int(req.GetCount()),
time.Millisecond*time.Duration(req.GetDelay()),
)
resp, err := conn(ctx)
if err != nil {
return nil, err
}
return &pb.RetryResponse{Message: resp}, nil
}
func (s *server) DemoThrottle(
ctx context.Context,
req *pb.ThrottleRequest,
) (
*pb.ThrottleResponse,
error,
) {
var resp string
conn := throttle.Throttle(
func(ctx context.Context) (string, error) {
return "success", nil
},
uint(req.GetMax()),
uint(req.GetRefill()),
time.Second*time.Duration(req.GetDuration()),
)
attempts := req.GetAttempts()
log.Printf("💻 Spamming %d attempts\n", attempts)
for i := 0; i < int(attempts); i++ {
resp, _ = conn(ctx)
log.Printf("⏱ Waiting %dms before a new attempt...\n", 200)
time.Sleep(time.Millisecond * 200)
}
log.Printf("🥳 %d/%d connection attempts complete 🥳\n", attempts, attempts)
return &pb.ThrottleResponse{Message: resp}, nil
}
func (s *server) DemoTimeout(
ctx context.Context,
req *pb.TimeoutRequest,
) (
*pb.TimeoutResponse,
error,
) {
var resp string
conn := timeout.Timeout(
slowFunction(time.Second * time.Duration(req.Duration)),
)
ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Second*time.Duration(req.Timeout))
defer cancel()
resp, err := conn(ctxWithTimeout, "input1")
if err != nil {
return nil, err
}
return &pb.TimeoutResponse{Message: resp}, nil
}
func (s *server) DemoFanIn(
ctx context.Context,
req *pb.FanInRequest,
) (
*pb.FanInResponse,
error,
) {
var resp string
sources := make([]<-chan int, 0) // Create an empty channel slice
for i := 1; i <= int(req.SourceCount); i++ {
ch := make(chan int)
sources = append(sources, ch) // Create a channel; add to sources
go func(channel_id int) { // Run a toy goroutine for each
defer close(ch) // Close ch when the routine ends
rand.Seed(time.Now().UnixNano())
count := rand.Intn(9) + 1
log.Printf("Source #%d set to count up to %d", channel_id, count)
for j := 1; j <= count; j++ {
// Each sent value will correspond to its specific channel indicated by the initial digits
// Ex. 34 is the 3rd source with and 4th value
val := channel_id*10 + j
log.Printf("➕ Adding %d to source channel #%d ➕", val, channel_id)
ch <- val
time.Sleep(time.Second)
}
log.Printf("✅ All %d values pushed to channel #%d. Closing channel... ✅", count, channel_id)
}(i)
}
dest := fanin.Funnel(sources...)
for d := range dest {
log.Printf("📖 Reading %d off destination channel 📖", d)
}
log.Printf("🥳 All values successfully fanned-in 🥳")
return &pb.FanInResponse{Message: resp}, nil
}
func (s *server) DemoFanOut(
ctx context.Context,
req *pb.FanOutRequest,
) (
*pb.FanOutResponse,
error,
) {
source := make(chan int) // The input channel
dests := fanout.Split(source, int(req.GetDestinationCount())) // Retrieve output channels
go func() { // Send the number 1..n to source
defer close(source)
for i := 1; i <= int(req.GetSourceCount()); i++ {
source <- i
}
}()
var wg sync.WaitGroup // Use WaitGroup to wait until
wg.Add(len(dests)) // the output channels all close
for i, ch := range dests {
go func(i int, d <-chan int) {
defer wg.Done()
for val := range d {
fmt.Printf("#%d channel got value %d\n", i, val)
}
}(i, ch)
}
wg.Wait()
return &pb.FanOutResponse{Message: "Complete"}, nil
}
func emulateTransientError(ctx context.Context) (string, error) {
//randomly return error
rand.Seed(time.Now().UnixNano())
prob := 3
isError := rand.Intn(10) > prob //roughly 1 in 3 calls will return an error
if isError {
return "", errors.New("❌ FAILED ❌")
}
return "✅ SUCCESS ✅", nil
}
func slowConnectionWithContext(ctx context.Context) (string, error) {
rand.Seed(time.Now().UnixNano())
duration := rand.Intn(10)
log.Printf("Simulating a long connection attempt for %d seconds", duration)
for i := 0; i < duration; i++ {
select {
case <-ctx.Done():
log.Println("Failed to connect in time...")
return "", ctx.Err()
default:
log.Printf("%ds elapsed...", i+1)
time.Sleep(time.Second * 1)
}
}
success := "Connection complete!"
log.Println(success)
return success, nil
}
func slowFunction(d time.Duration) timeout.SlowFunction {
return func(s string) (string, error) {
log.Printf("Received argument: %v", s)
log.Printf("Emulating slow function for %s", d)
time.Sleep(d)
return "✅ Slow Function completed ✅", nil
}
}
func slowConnection(ctx context.Context) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
rand.Seed(time.Now().UnixNano())
duration := rand.Intn(10)
log.Printf("Simulating a long connection attempt for %d seconds", duration)
for i := 0; i < duration; i++ {
select {
case <-ctx.Done():
log.Println("Failed to connect in time...")
return "", ctx.Err()
default:
log.Printf("%ds elapsed...", i+1)
time.Sleep(time.Second * 1)
}
}
success := "Connection complete!"
log.Println(success)
return success, nil
}