forked from ardanlabs/practical-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtb.go
69 lines (62 loc) · 1.56 KB
/
rtb.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
package main
import (
"context"
"fmt"
"strings"
"time"
)
func main() {
// We have 50 msec to return an answer
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
url := "https://go.dev" // return the 7¢ ad
// url := "http://go.dev" // return the default ad
bid := bidOn(ctx, url)
fmt.Println(bid)
}
// If algo didn't finish in time, return a default bid
func bidOn(ctx context.Context, url string) Bid {
// CONTROLLER
// - BUFFERED CHANNEL (buffer = N WRITERS)
// - N ASYNC WRITER*
// - (1 READER* |X| 1 TIMEOUT)
// BUFFER => decouples writers and reader
// if TIMEOUT all writes continue, the data is absorbed by the channel buffer and because the channel gets out of all scopes it's garbage collected.
bestBidChan := make(chan Bid, 1)
go func() {
// WRITER
// has ref to channel
// is the only writer
defer close(bestBidChan) // being the only writer it should close the channel
bestBidChan <- bestBid(url) // it will NOT hang because we've got the buffer
}()
select {
case bid := <-bestBidChan:
// CONTROLLER.OK
return bid
case <-ctx.Done():
// CONTROLLER.TIMEOUT
return defaultBid
}
}
var defaultBid = Bid{
AdURL: "http://adsЯus.com/default",
Price: 3,
}
// Written by Algo team, time to completion varies
func bestBid(url string) Bid {
// Simulate work
d := 100 * time.Millisecond
if strings.HasPrefix(url, "https://") {
d = 20 * time.Millisecond
}
time.Sleep(d)
return Bid{
AdURL: "http://adsЯus.com/ad17",
Price: 7,
}
}
type Bid struct {
AdURL string
Price int // In ¢
}