forked from TechEmpower/FrameworkBenchmarks
/
falcore.go
291 lines (249 loc) · 7.96 KB
/
falcore.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
package main
import (
"database/sql"
"html/template"
"io"
"log"
"math/rand"
"net/http"
"sort"
"strconv"
"sync"
"time"
"github.com/fitstar/falcore"
"github.com/fitstar/falcore/responder"
_ "github.com/go-sql-driver/mysql"
)
type Message struct {
Message string `json:"message"`
}
type World struct {
Id uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
type Fortune struct {
Id uint16 `json:"id"`
Message string `json:"message"`
}
const (
// Database
connectionString = "benchmarkdbuser:benchmarkdbpass@tcp(tfb-database:3306)/hello_world?collation=utf8mb4_bin"
worldSelect = "SELECT id, randomNumber FROM World WHERE id = ?"
worldUpdate = "UPDATE World SET randomNumber = ? WHERE id = ?"
fortuneSelect = "SELECT id, message FROM Fortune;"
worldRowCount = 10000
maxConnectionCount = 256
helloWorldString = "Hello, World!"
)
var (
// Templates
tmpl = template.Must(template.ParseFiles("templates/layout.html", "templates/fortune.html"))
// Database
worldStatement *sql.Stmt
fortuneStatement *sql.Stmt
updateStatement *sql.Stmt
helloWorldBytes = []byte(helloWorldString)
)
type stats struct {
Count time.Duration
Sum time.Duration
}
// for profiling
var reqCount = 0
var statMap = make(map[string]*stats)
var compCallbackMutex = &sync.Mutex{}
func CompletionCallback(req *falcore.Request, res *http.Response) {
l := req.PipelineStageStats
compCallbackMutex.Lock()
incrStat(statMap, "overhead", req.Overhead)
incrStat(statMap, "tots", req.EndTime.Sub(req.StartTime))
for e := l.Front(); e != nil; e = e.Next() {
pss, _ := e.Value.(*falcore.PipelineStageStat)
dur := pss.EndTime.Sub(pss.StartTime)
incrStat(statMap, pss.Name, dur)
}
reqCount++
if reqCount%10000 == 0 {
for k, v := range statMap {
log.Printf("%v: %v\n", k, v.Sum/v.Count)
}
log.Println("")
}
compCallbackMutex.Unlock()
}
func incrStat(statMap map[string]*stats, name string, dur time.Duration) {
if s, ok := statMap[name]; ok {
s.Count++
s.Sum += dur
} else {
statMap[name] = &stats{1, dur}
}
}
func main() {
db, err := sql.Open("mysql", connectionString)
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
db.SetMaxIdleConns(maxConnectionCount)
worldStatement, err = db.Prepare(worldSelect)
if err != nil {
log.Fatal(err)
}
fortuneStatement, err = db.Prepare(fortuneSelect)
if err != nil {
log.Fatal(err)
}
updateStatement, err = db.Prepare(worldUpdate)
if err != nil {
log.Fatal(err)
}
pipeline := falcore.NewPipeline()
pipeline.Upstream.PushBack(dbFilter)
pipeline.Upstream.PushBack(queriesFilter)
pipeline.Upstream.PushBack(jsonFilter)
pipeline.Upstream.PushBack(fortuneFilter)
pipeline.Upstream.PushBack(updateFilter)
pipeline.Upstream.PushBack(plaintextFilter)
pipeline.Downstream.PushBack(requiredHeaders)
/*
http.HandleFunc("/db", dbHandler)
http.HandleFunc("/queries", queriesHandler)
http.HandleFunc("/json", jsonHandler)
http.HandleFunc("/fortune", fortuneHandler)
http.HandleFunc("/update", updateHandler)
http.HandleFunc("/plaintext", plaintextHandler)
*/
server := falcore.NewServer(8080, pipeline)
// uncomment for printing internal peromance stats
//server.CompletionCallback = CompletionCallback
if err := server.ListenAndServe(); err != nil {
log.Println("Could not start server:", err)
}
//if err := http.ListenAndServe(":8080", server); err != nil {
// log.Println("Could not start server:", err)
//}
}
var requiredHeaders = falcore.NewResponseFilter(func(req *falcore.Request, res *http.Response) {
res.Header.Set("Server", "falcore")
res.Header.Set("Date", time.Now().Format(time.RFC1123))
})
// Test 1: JSON serialization
var jsonFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/json" {
resp, _ := responder.JSONResponse(req.HttpRequest, 200, nil, &Message{helloWorldString})
return resp
}
return nil
})
// Test 2: Single database query
var dbFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/db" {
var world World
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
resp, _ := responder.JSONResponse(req.HttpRequest, 200, nil, &world)
return resp
}
return nil
})
// Test 3: Multiple database queries
var queriesFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/queries" {
n := 1
if nStr := req.HttpRequest.URL.Query().Get("queries"); len(nStr) > 0 {
n, _ = strconv.Atoi(nStr) // rvalue is 0 if nStr is non-number.
}
// In the case of nStr is non-number string, n will be 0. So need to change n to 1.
if n == 0 {
n = 1
}
// In the case of nStr is number and its value is higher than 500, change n to 500
if n > 500 {
n = 500
}
world := make([]World, n)
for i := 0; i < n; i++ {
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
}
resp, _ := responder.JSONResponse(req.HttpRequest, 200, nil, &world)
return resp
}
return nil
})
// Test 4: Fortunes
var fortuneFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/fortune" {
rows, err := fortuneStatement.Query()
if err != nil {
log.Fatalf("Error preparing statement: %v", err)
}
fortunes := make(Fortunes, 0, 16)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.Id, &fortune.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err.Error())
}
fortunes = append(fortunes, &fortune)
}
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(ByMessage{fortunes})
pipeReader, pipeWriter := io.Pipe()
// TODO maybe figure out err handling
go func() {
tmpl.Execute(pipeWriter, fortunes)
pipeWriter.Close()
}()
textHtml := http.Header{"Content-Type": []string{"text/html;charset=utf-8"}}
return falcore.SimpleResponse(req.HttpRequest, 200, textHtml, -1, pipeReader)
}
return nil
})
// Test 5: Database updates
var updateFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/update" {
n := 1
if nStr := req.HttpRequest.URL.Query().Get("queries"); len(nStr) > 0 {
n, _ = strconv.Atoi(nStr)
}
if n <= 1 {
var world World
worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber)
world.RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
updateStatement.Exec(world.RandomNumber, world.Id)
resp, _ := responder.JSONResponse(req.HttpRequest, 200, nil, &world)
return resp
} else {
world := make([]World, n)
for i := 0; i < n; i++ {
if err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
world[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := updateStatement.Exec(world[i].RandomNumber, world[i].Id); err != nil {
log.Fatalf("Error updating world row: %s", err.Error())
}
}
resp, _ := responder.JSONResponse(req.HttpRequest, 200, nil, world)
return resp
}
}
return nil
})
// Test 6: Plaintext
var plaintextFilter = falcore.NewRequestFilter(func(req *falcore.Request) *http.Response {
if req.HttpRequest.URL.Path == "/plaintext" {
textPlain := http.Header{"Content-Type": []string{"text/plain"}}
return falcore.ByteResponse(req.HttpRequest, 200, textPlain, helloWorldBytes)
}
return nil
})
type Fortunes []*Fortune
func (s Fortunes) Len() int { return len(s) }
func (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByMessage struct{ Fortunes }
func (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }