-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
266 lines (232 loc) · 6.43 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
// Copyright 2016 Andrew O'Neill, Nordstrom
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"text/template"
"time"
"github.com/Nordstrom/choices"
"github.com/foolusion/elwinprotos/storage"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
const (
storageAddr = "elwin-storage:80"
listenAddr = ":8080"
genEndpoint = "/"
bookmarkletEndpoint = "/bookmarklet"
globalSalt = "choices"
grpcTimeout = 500 * time.Millisecond
envJavascriptFile = "JAVASCRIPT_FILE"
envURL = "URL"
)
var (
config = struct {
cc *grpc.ClientConn
client storage.ElwinStorageClient
}{}
ErrNotFound = errors.New("could not generate a matching cookie value")
)
var bookmarkletTmpl *template.Template
func init() {
http.HandleFunc(genEndpoint, genHandler)
http.HandleFunc(bookmarkletEndpoint, bookmarkletHandler)
choices.SetGlobalSalt(globalSalt)
}
func main() {
var err error
config.cc, err = grpc.Dial(storageAddr, grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
config.client = storage.NewElwinStorageClient(config.cc)
f, err := os.Open(os.Getenv(envJavascriptFile))
if err != nil {
log.Fatal(err)
}
out, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
str := strings.Replace(string(out), `"`, `%22`, -1)
bookmarkletTmpl = template.Must(template.New("bookmarklet").Parse(bookmarkletHTML))
_ = template.Must(bookmarkletTmpl.New("javascript").Parse(str))
log.Println(http.ListenAndServe(listenAddr, nil))
}
func bookmarkletHandler(w http.ResponseWriter, _ *http.Request) {
if err := bookmarkletTmpl.Execute(w, os.Getenv(envURL)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
var bookmarkletHTML = `<!doctype html>
<html lang="en">
<head>
<title>bookmarklets - gen</title>
</head>
<body>
<h1>Gen Bookmarklet</h1>
<p>Drag this link to the bookmark bar</p>
<a href="javascript:{{template "javascript" .}}">Elwin</a>
</body>
</html>
`
func genHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
ar := &storage.AllRequest{Environment: storage.Production}
ctx, cancel := context.WithTimeout(context.Background(), grpcTimeout)
defer cancel()
resp, err := config.client.All(ctx, ar)
if err != nil {
var errCode int
switch grpc.Code(err) {
case codes.Canceled, codes.DeadlineExceeded:
errCode = http.StatusRequestTimeout
case codes.InvalidArgument:
errCode = http.StatusBadRequest
default:
errCode = http.StatusInternalServerError
}
http.Error(w, err.Error(), errCode)
return
}
var namespaces []choices.Namespace
for _, namespace := range resp.GetNamespaces() {
cns, err := choices.FromNamespace(namespace)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
namespaces = append(namespaces, cns)
}
ev, err := gen(namespaces)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
enc := json.NewEncoder(w)
if err := enc.Encode(ev); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
type experimentValue struct {
NamespaceName string `json:"namespaceName"`
ExperimentName string `json:"experimentName"`
Labels string `json:"labels"`
Params map[string][]param `json:"params"`
}
type param struct {
Name string `json:"name"`
Value string `json:"value"`
}
func gen(ns []choices.Namespace) ([]experimentValue, error) {
buf := make([]byte, 256)
if _, err := rand.Read(buf); err != nil {
return nil, errors.Wrap(err, "could not read random bytes")
}
var expVal []experimentValue
for _, n := range ns {
for _, e := range n.Experiments {
ev := experimentValue{
NamespaceName: n.Name,
ExperimentName: e.Name,
Labels: strings.Join(n.Labels, ", "),
Params: make(map[string][]param, 16),
}
cookies, err := cookie(buf, n.Name, e)
if err != nil {
return nil, errors.Wrap(err, "could not generate cookie values")
}
for key, cookie := range cookies {
ev.Params[cookie] = unkey(key)
}
expVal = append(expVal, ev)
}
}
return expVal, nil
}
type paramKey struct {
param
more interface{}
}
func key(params ...param) paramKey {
var more interface{}
if len(params) > 1 {
more = key(params[1:]...)
}
return paramKey{param: params[0], more: more}
}
func unkey(p paramKey) []param {
var ps []param
for {
ps = append(ps, p.param)
if p.more == nil {
return ps
}
p = p.more.(paramKey)
}
}
func cookie(buf []byte, namespace string, experiment choices.Experiment) (map[paramKey]string, error) {
num := uniqueParams(experiment.Params)
cookies := make(map[paramKey]string, 16)
for i := 1; i < len(buf); i++ {
if len(cookies) == num {
return cookies, nil
}
userID := hex.EncodeToString(buf[:i])
if !choices.InSegment(namespace, userID, experiment.Segments) {
continue
}
var paramKeys []param
for _, p := range experiment.Params {
val, err := genValues(p.Value, namespace, experiment.Name, p.Name, userID)
if err != nil {
return nil, errors.Wrap(err, "could not generate value")
}
paramKeys = append(paramKeys, param{Name: p.Name, Value: val})
}
k := key(paramKeys...)
if _, ok := cookies[k]; !ok {
cookies[k] = userID
}
}
return nil, ErrNotFound
}
func uniqueParams(params []choices.Param) int {
res := 1
for _, param := range params {
switch v := param.Value.(type) {
case *choices.Uniform:
res *= len(v.Choices)
case *choices.Weighted:
res *= len(v.Choices)
}
}
return res
}
func genValues(v choices.Value, namespace, experiment, param, userID string) (string, error) {
h, err := choices.HashExperience(namespace, experiment, param, userID)
if err != nil {
return "", err
}
return v.Value(h)
}