-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashservice.go
More file actions
240 lines (202 loc) · 5.2 KB
/
hashservice.go
File metadata and controls
240 lines (202 loc) · 5.2 KB
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
package main
import (
"context"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
var addr = flag.String("addr", ":8080", "http service address")
var delay = flag.Int("delay", 5000, "Milliseconds to delay hashing")
type stats struct {
Total int `json:"total"`
Average float64 `json:"average"`
}
func hashAndEncode(s string) string {
sBytes := []byte(s)
hashBytes := sha512.Sum512(sBytes)
return base64.StdEncoding.EncodeToString(hashBytes[:])
}
// Generate sequential IDs
type counter struct {
sync.Mutex
n int
}
func (c *counter) next() int {
c.Lock()
c.n++
result := c.n
c.Unlock()
return result
}
func (c *counter) reset() {
c.Lock()
c.n = 0
c.Unlock()
}
var hashIdCounter counter
// Store hashed/encoded values, addressable by ID
type mapCache struct {
sync.RWMutex
m map[int]string
// Sum of all processing times for element of m
totalTime time.Duration
}
func newMapCache() *mapCache {
mc := new(mapCache)
mc.m = make(map[int]string)
return mc
}
func (mc *mapCache) set(id int, value string, startTime time.Time) {
mc.Lock()
mc.m[id] = value
procTime := time.Now().Sub(startTime)
mc.totalTime += procTime
mc.Unlock()
}
func (mc *mapCache) get(id int) (string, bool) {
mc.RLock()
value, ok := mc.m[id]
mc.RUnlock()
return value, ok
}
func (mc *mapCache) getStats() (int64, time.Duration) {
mc.RLock()
count := len(mc.m)
totalTime := mc.totalTime
mc.RUnlock()
return int64(count), totalTime
}
func (mc *mapCache) reset() {
mc.Lock()
mc.m = make(map[int]string)
mc.totalTime = time.Duration(0)
mc.Unlock()
}
var hashCache = newMapCache()
// Re-initialize state for unit tests
func reset() {
hashCache.reset()
hashIdCounter.reset()
}
func doHashAsync(id int, s string) {
time.Sleep(time.Duration(*delay) * time.Millisecond)
startTime := time.Now()
hashCache.set(id, hashAndEncode(s), startTime)
}
func setupShutdown() (http.HandlerFunc, chan struct{}) {
stop := make(chan struct{})
handler := func(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(w, "GET method is required", http.StatusMethodNotAllowed)
return
}
close(stop)
}
return handler, stop
}
// Hash/encode password and return it in response
func hashSyncHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(w, "POST method is required", http.StatusMethodNotAllowed)
return
}
time.Sleep(time.Duration(*delay) * time.Millisecond)
req.ParseForm()
pw, ok := req.PostForm["password"]
if !ok {
http.Error(w, "password parameter is required", http.StatusBadRequest)
return
}
w.Write([]byte(hashAndEncode(pw[0])))
}
// Schedule hashing of password, return ID to be used for retrieval
func hashAsyncStartHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(w, "POST method is required", http.StatusMethodNotAllowed)
return
}
req.ParseForm()
pw, ok := req.PostForm["password"]
if !ok {
http.Error(w, "password parameter is required", http.StatusBadRequest)
return
}
id := hashIdCounter.next()
go doHashAsync(id, pw[0])
w.Write([]byte(strconv.Itoa(id)))
}
// Retrieve a hashed password using its ID
func hashAsyncFinishHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(w, "GET method is required", http.StatusMethodNotAllowed)
return
}
comps := strings.Split(req.URL.Path, "/")
if len(comps) != 3 {
http.Error(w, "Invalid path: "+req.URL.Path, http.StatusBadRequest)
return
}
id, err := strconv.Atoi(string(comps[2]))
if err != nil {
http.Error(w, "Invalid ID: path: "+req.URL.Path, http.StatusBadRequest)
return
}
hashedValue, ok := hashCache.get(id)
if !ok {
msg := fmt.Sprintf("Id %d not found", id)
http.Error(w, msg, http.StatusNotFound)
return
}
w.Write([]byte(hashedValue))
}
func statsHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(w, "GET method is required", http.StatusMethodNotAllowed)
return
}
count, totalTime := hashCache.getStats()
var avg float64
if count != 0 {
avg = float64(totalTime) / (float64(count * int64(time.Millisecond)))
}
statsJson, err := json.Marshal(stats{int(count), avg})
if err != nil {
msg := fmt.Sprintf("json error: %v count: %v avg: %v", err, count, avg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Write(statsJson)
}
func newServeMux() (*http.ServeMux, chan struct{}) {
mux := http.NewServeMux()
shutdownHandler, stop := setupShutdown()
mux.Handle("/shutdown", shutdownHandler)
mux.Handle("/hash", http.HandlerFunc(hashAsyncStartHandler))
mux.Handle("/hash/", http.HandlerFunc(hashAsyncFinishHandler))
mux.Handle("/stats", http.HandlerFunc(statsHandler))
// Synchronous POST endpoint from Step 2 of exercise
mux.Handle("/hashsync", http.HandlerFunc(hashSyncHandler))
return mux, stop
}
func main() {
flag.Parse()
mux, stop := newServeMux()
srv := &http.Server{Addr: *addr, Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Printf("INFO: hashservice: ListenAndServe(): %s", err)
}
}()
<-stop
if err := srv.Shutdown(context.Background()); err != nil {
log.Printf("INFO: hashservice: Shutdown() error: %s", err)
}
}