-
Notifications
You must be signed in to change notification settings - Fork 4
/
rtbapp.go
192 lines (156 loc) · 5.66 KB
/
rtbapp.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
package main
import (
"encoding/json"
"fmt"
"github.com/evandigby/rtb"
"github.com/evandigby/rtb/amqp"
"github.com/evandigby/rtb/inmemory"
rtbr "github.com/evandigby/rtb/redis"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
)
// Temporary in memory state for testing
type RtbApp struct {
domain string
redisNetwork string
redisAddress string
campaignProvider rtb.CampaignProvider
banker rtb.Banker
pacer rtb.Pacer
updateTicker *time.Ticker
accountBids chan *rtb.BidResponse
bidTotals map[int64]int64
logger rtb.BidLogProducer
bidLoggerChannel chan *rtb.BidLogItem // Limits the number of connections to loggers
}
type RtbAppOptions struct {
Domain string
PeriodicUpdates bool
UpdateFrequencyInSeconds int
PacerOptions struct {
UsePacer bool
TimeSegmentInSeconds int
}
DataAccessOptions struct {
Network string
Address string
ConnectionPoolSize int
}
LoggingOptions struct {
AmqpAddress string
File *os.File
Verbose bool
FullBidResponse bool
LogTransactions bool
TransactionLogFile *os.File
TransactionLogCSV bool
}
}
func (app *RtbApp) CreateDefaultCampaigns() {
app.campaignProvider.CreateCampaign(100101, rtb.CpmToMicroCents(0.32), rtb.DollarsToMicroCents(35.50), []rtb.Target{rtb.Target{Type: rtb.Placement, Value: "Words With Friends 2 iPad"}})
app.campaignProvider.CreateCampaign(100102, rtb.CpmToMicroCents(0.04), rtb.DollarsToMicroCents(5.25), []rtb.Target{rtb.Target{Type: rtb.CreativeSize, Value: "728x90"}})
app.campaignProvider.CreateCampaign(100103, rtb.CpmToMicroCents(0.32), rtb.DollarsToMicroCents(15.00), []rtb.Target{rtb.Target{Type: rtb.Country, Value: "USA"}})
app.campaignProvider.CreateCampaign(100104, rtb.CpmToMicroCents(0.15), rtb.DollarsToMicroCents(22.00), []rtb.Target{rtb.Target{Type: rtb.OS, Value: "Android"}})
app.campaignProvider.CreateCampaign(100105, rtb.CpmToMicroCents(0.02), rtb.DollarsToMicroCents(2.25), []rtb.Target{rtb.Target{Type: rtb.Country, Value: "CAN"}})
}
func (app *RtbApp) bidRequestForHttpRequest(r *http.Request) *rtb.BidRequest {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
var bidRequest rtb.BidRequest
err = json.Unmarshal(body, &bidRequest)
return &bidRequest
}
func (app *RtbApp) BidRequestHandler(w http.ResponseWriter, r *http.Request) {
startTime := time.Now().UTC().UnixNano()
bidRequest := app.bidRequestForHttpRequest(r)
bidder := inmemory.NewBidRequestBidder(bidRequest, app.campaignProvider, app.pacer, time.Now().UTC())
b, remainingDailyBudgetsInMicroCents, err := bidder.Bid()
if err == nil && b != nil {
js, err := json.Marshal(b)
if err == nil {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
// Push the bid onto our stats and transaction logging process
app.accountBids <- b
} else {
w.WriteHeader(http.StatusNoContent)
}
} else {
w.WriteHeader(http.StatusNoContent)
}
if app.logger != nil {
app.bidLoggerChannel <- &rtb.BidLogItem{Domain: app.domain, BidRequest: bidRequest, BidResponse: b, RemainingDailyBudgetsInMicroCents: remainingDailyBudgetsInMicroCents, StartTimestampInNanoseconds: startTime, EndTimestampInNanoseconds: time.Now().UTC().UnixNano()}
}
}
func (app *RtbApp) PrintCampaigns(campaigns []int64) {
fmt.Println()
for _, val := range campaigns {
c := app.campaignProvider.ReadCampaign(val)
remaining := app.banker.RemainingDailyBudgetInMicroCents(c.Id())
fmt.Printf("Campaign Id: %v / CPM: $%v / Remaining Daily Budget: $%v / Total Bids: %v\n", c.Id(), rtb.MicroCentsToDollarsRounded(c.BidCpmInMicroCents(), 2), rtb.MicroCentsToDollarsRounded(remaining, 5), app.bidTotals[c.Id()])
}
}
func (app *RtbApp) PrintUpdates() {
for {
<-app.updateTicker.C
app.PrintCampaigns(app.campaignProvider.ListCampaigns())
}
}
func (app *RtbApp) BidTotalUpdater() {
for {
rsp := <-app.accountBids
if rsp.Seatbid != nil {
for _, rsp := range rsp.Seatbid {
if rsp.Bid != nil {
for _, bid := range rsp.Bid {
campaignId, _ := strconv.ParseInt(bid.Cid, 10, 64)
total := app.bidTotals[campaignId] + 1
app.bidTotals[campaignId] = total
}
}
}
}
}
}
func (app *RtbApp) LogBids() {
for {
logItem := <-app.bidLoggerChannel
app.logger.LogItem(logItem)
}
}
func NewRtbApp(options RtbAppOptions) *RtbApp {
app := new(RtbApp)
app.domain = options.Domain
app.redisAddress = options.DataAccessOptions.Address
app.redisNetwork = options.DataAccessOptions.Network
if options.LoggingOptions.Verbose || options.LoggingOptions.FullBidResponse {
if options.LoggingOptions.File != nil {
app.logger = inmemory.NewFileBidLogger(options.LoggingOptions.File, options.LoggingOptions.FullBidResponse)
} else {
app.logger = amqp.NewAmqpBidLogger(options.LoggingOptions.AmqpAddress, options.Domain)
}
app.bidLoggerChannel = make(chan *rtb.BidLogItem)
go app.LogBids()
}
da := rtbr.NewRedisDataAccess(app.redisNetwork, app.redisAddress, app.domain, options.DataAccessOptions.ConnectionPoolSize)
app.banker = rtbr.NewRedisBanker(da)
app.campaignProvider = rtbr.NewRedisCampaignProvider(da, app.banker)
if options.PacerOptions.UsePacer {
app.pacer = rtbr.NewRedisPacer(app.campaignProvider, da, app.banker, time.Duration(options.PacerOptions.TimeSegmentInSeconds)*time.Second)
}
app.CreateDefaultCampaigns()
if options.PeriodicUpdates {
app.updateTicker = time.NewTicker(time.Duration(options.UpdateFrequencyInSeconds) * time.Second)
go app.BidTotalUpdater()
go app.PrintUpdates()
}
app.accountBids = make(chan *rtb.BidResponse)
app.bidTotals = make(map[int64]int64)
return app
}