/
sendgrid.go
520 lines (462 loc) · 13.8 KB
/
sendgrid.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package main
import (
"database/sql"
_ "github.com/jmoiron/sqlx"
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/gin-contrib/cors"
_ "github.com/mattn/go-isatty"
_ "github.com/joho/godotenv/autoload"
_ "github.com/lib/pq"
"github.com/MakeNowJust/heredoc"
"github.com/yvasiyarov/gorelic"
"log"
"net/http"
"os"
"time"
"strconv"
"github.com/jmoiron/sqlx"
"strings"
"regexp"
"encoding/json"
)
type Event struct {
ID uint
CreatedAt time.Time
UpdatedAt time.Time
Event string
Email string
Category string `json:"category"`
Timestamp int64
Happened_at time.Time
Url string
UniqId string `json:"uniq_id"`
SmtpId string `json:"smtp-id"`
SgMessageId string `json:"sg_message_id"`
IP string `json:"ip"`
UserAgent string `json:"useragent"`
}
type Events []Event
type SearchSuggestion struct {
Field string `db:"field"`
}
type SearchSuggestions []SearchSuggestion
var (
db *sql.DB
dbx *sqlx.DB
err interface{}
eventDB chan (Event)
quitDB chan (int)
)
const numOfUpdates = 20
func main() {
// prepare NewRelic
configureNewRelic()
// prepare DB
db, err = prepareDB()
if err != nil {
return
}
defer closeDB(db, dbx)
eventDB = make(chan Event)
quitDB = make(chan int)
go updateDb()
r := gin.Default()
r.Use(CORSMiddleware())
r.POST("/api/sendgrid_event", processEvent)
r.GET("/search/search_suggestions", processSearchSuggestion)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Println("SERVING on port", port)
http.ListenAndServe(":"+port, r)
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
fmt.Println("OPTIONS")
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
func prepareDB() (db *sql.DB, err error) {
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalf("DB connection error: %v\n", err)
return
}
err = db.Ping() // really connect to db
if err != nil {
log.Fatalf("DB real connection error: %v\n", err)
return
}
dbx, err = sqlx.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalf("DB connection error: %v\n", err)
return
}
err = dbx.Ping() // really connect to db
if err != nil {
log.Fatalf("DB real connection error: %v\n", err)
return
}
db.SetMaxOpenConns(numOfUpdates)
db.SetMaxIdleConns(numOfUpdates)
dbx.SetMaxOpenConns(numOfUpdates)
dbx.SetMaxIdleConns(numOfUpdates)
return
}
func closeDB(db *sql.DB, dbx *sqlx.DB) {
quitDB <- 0
db.Close()
dbx.Close()
}
func processEvent(c *gin.Context) {
events := Events{}
if err := c.ShouldBindJSON(&events); err != nil {
fmt.Println("marshal error:", err)
return
}
for _, event := range events {
eventDB <- event
}
}
func processSearchSuggestion(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/res")
query := c.DefaultQuery("term", "")
if query == "" {
c.String(http.StatusOK, "[]")
return
}
couponsTotal, couponIds := ProductSearchIds(query, 3, false)
vacationsTotal, vacationIds := ProductSearchIds(query, 3, true)
productsTotal, productIds := ShopProductSearchIds(query, 6)
var res []string
if couponsTotal > 0 {
for _, x := range filterCoupons(couponIds) {
res = append(res, x.Field)
}
}
if vacationsTotal > 0 {
for _, x := range filterCoupons(vacationIds) {
res = append(res, x.Field)
}
}
if productsTotal > 0 {
for _, x := range filterShopProducts(productIds) {
res = append(res, x.Field)
}
}
type Suggestion struct {
Href string `json:"href"`
Label string `json:"label"`
}
var suggestion Suggestion
var suggestions []string
re := regexp.MustCompile("(?i)" + query)
for _, x := range res {
json.Unmarshal([]byte(x), &suggestion)
suggestion.Label = re.ReplaceAllString(suggestion.Label, "<b style='background: yellow;'>" + query + "</b>")
j, _ := json.Marshal(suggestion)
suggestions = append(suggestions, string(j))
}
c.String(http.StatusOK, "[%s]", strings.Join(suggestions, ","))
}
func getAO(prefix string) (result string) {
type AOResult struct {
Id int `db:"id"`
Ancestry string `db:"ancestry"`
}
type AOIds struct {
Id int `db:"id"`
}
var (
adultsOnlyCategory AOResult
adultsOnlySubCatIds []int = []int{}
adultsOnlyCatIds []AOIds
productsOnlySubCatIds []int
productSubCatIds []AOIds
)
result = "AND 1=1"
if err = dbx.Get(&adultsOnlyCategory, `SELECT "categories".id, "categories".ancestry FROM "categories" WHERE "categories".system_name = 'adults-only' LIMIT 1`); err != nil {
return
}
request := heredoc.Docf(`
SELECT "categories".id
FROM "categories"
WHERE (("categories"."ancestry" ILIKE '%s/%d/%%' OR "categories"."ancestry" = '%s/%d') OR "categories"."id" = %d) AND "categories"."is_active" = true
`, adultsOnlyCategory.Ancestry, adultsOnlyCategory.Id, adultsOnlyCategory.Ancestry, adultsOnlyCategory.Id, adultsOnlyCategory.Id)
if err = dbx.Select(&adultsOnlyCatIds, request); err != nil {
return
}
for _, a := range adultsOnlyCatIds {
adultsOnlySubCatIds = append(adultsOnlySubCatIds, a.Id)
}
request = heredoc.Docf(`
SELECT "sub_categories".id
FROM "sub_categories"
INNER JOIN "categories_sub_categories" ON "sub_categories"."id" = "categories_sub_categories"."sub_category_id"
WHERE "categories_sub_categories"."category_id" IN (%s) ORDER BY categories_sub_categories.priority
`, arrayToString(adultsOnlySubCatIds, ","))
if err = dbx.Select(&adultsOnlyCatIds, request); err != nil {
return
}
for _, a := range adultsOnlyCatIds {
productsOnlySubCatIds = append(productsOnlySubCatIds, a.Id)
}
request = heredoc.Docf(`
SELECT "%sproducts_sub_categories"."product_id" id
FROM "%sproducts_sub_categories"
WHERE "%sproducts_sub_categories"."sub_category_id" IN (%s)
`, prefix, prefix, prefix, arrayToString(productsOnlySubCatIds, ","))
if err = dbx.Select(&productSubCatIds, request); err != nil && err != sql.ErrNoRows {
return
}
if len(productSubCatIds) > 0 {
var pairs []int
for _, x := range productSubCatIds {
pairs = append(pairs, x.Id)
}
return heredoc.Docf(`
"%sproducts"."id" NOT IN (%s)
`, prefix, arrayToString(pairs, ","))
} else {
return
}
}
func filterShopProducts(ids []int) (result SearchSuggestions) {
var (
adults string = getAO("shop_")
order []string
)
for i, p := range ids {
order = append(order, fmt.Sprintf("(%d,%d)", p, i))
}
request := heredoc.Docf(`
SELECT '{"href":"/shop/sales/' || "shop_products".sale_id || '/products/' || "shop_products"."id" || '","label":"' || "shop_products"."title" || '"}' field
FROM "shop_products"
JOIN (values %s) AS x(id, ordering) ON "shop_products".id = x.id
WHERE "shop_products"."id" IN (%s) %s
ORDER BY x.ordering
`, strings.Join(order, ","), arrayToString(ids, ","), adults)
if err = dbx.Select(&result, request); err != nil && err != sql.ErrNoRows {
result = SearchSuggestions{}
return
}
return
}
func filterCoupons(ids []int) (result SearchSuggestions) {
var (
adults string = getAO("")
order []string
)
for i, p := range ids {
order = append(order, fmt.Sprintf("(%d,%d)", p, i))
}
request := heredoc.Docf(`
SELECT '{"href":"/products/' || "products"."system_name" || '","label":"' || "products"."title" || '"}' field
FROM "products"
JOIN (values %s) AS x(id, ordering) ON "products".id = x.id
WHERE "products"."id" IN (%s) %s
ORDER BY x.ordering
`, strings.Join(order, ","), arrayToString(ids, ","), adults)
if err = dbx.Select(&result, request); err != nil && err != sql.ErrNoRows {
result = SearchSuggestions{}
return
}
return
}
func ProductSearchIds(unsanitizedTerm string, limit int, vacation bool) (total int, ids []int) {
var request string
v := "f"
if vacation {
v = "t"
}
limitQ := ""
if limit > 0 {
limitQ = fmt.Sprintf(" LIMIT %d", limit)
}
if len(unsanitizedTerm) == 0 {
request = heredoc.Docf(`
WITH coupons AS (
SELECT *
FROM products
WHERE ready = 't' AND visible = 't' AND LOCALTIMESTAMP BETWEEN valid_from AND valid_until
AND vacation = '%s'
)
SELECT id, (SELECT COUNT(1) FROM coupons) AS total
FROM coupons
ORDER BY id DESC
%s
`, v, limitQ)
} else {
term := sanitize(unsanitizedTerm)
request = heredoc.Docf(`
WITH coupons AS (
SELECT *, ((ts_rank(("products"."tsv"), (to_tsquery('simple', ''' ' || '%s' || ' ''' || ':*')), 0))) AS pg_search_rank
FROM products
WHERE ready = 't' AND visible = 't' AND LOCALTIMESTAMP BETWEEN valid_from AND valid_until
AND vacation = '%s'
AND (
tsv @@ to_tsquery('simple', ''' ' || '%s' || ' ''' || ':*') OR
tsv @@ to_tsquery('simple', ''' ' || reverse('%s') || ' ''' || ':*')
)
)
SELECT id, (SELECT COUNT(1) FROM coupons) AS total, pg_search_rank
FROM coupons
ORDER BY pg_search_rank DESC
%s
`, term, v, term, term, limitQ)
}
type Results struct {
Id string `db:"id"`
Total string `db:"total"`
PgSearchRank string `db:"pg_search_rank"`
}
results := []Results{}
if err = dbx.Select(&results, request); err != nil {
return
}
if len(results) == 0 {
return
}
total, _ = strconv.Atoi(results[0].Total)
for _, r := range results {
id, _ := strconv.Atoi(r.Id)
ids = append(ids, id)
}
return
}
func ShopProductSearchIds(unsanitizedTerm string, limit int) (total int, ids []int) {
var request string
limitQ := ""
if limit > 0 {
limitQ = fmt.Sprintf(" LIMIT %d", limit)
}
query := sanitize(unsanitizedTerm)
var finalSaleIds []int = []int{}
request = heredoc.Docf(`
SELECT "shop_products"."id"
FROM "shop_products"
INNER JOIN "shop_products_sub_categories" ON "shop_products"."id" = "shop_products_sub_categories"."product_id"
WHERE "shop_products_sub_categories"."sub_category_id" IN
(SELECT "sub_categories".id FROM "sub_categories" WHERE "sub_categories"."system_name" = 'final-sale')
`)
if err = dbx.Select(&finalSaleIds, request); err != nil {
return
}
if len(finalSaleIds) == 0 {
finalSaleIds = []int{0}
}
request = heredoc.Docf(`
WITH search_products AS (
SELECT shop_products.id, shop_catalogs.quantity_bought,
ts_rank("shop_products"."tsv", (to_tsquery('simple', ''' ' || '%s' || ' ''' || ':*')), 0) +
ts_rank("shop_products"."tsv", (to_tsquery('simple', ''' ' || reverse('%s') || ' ''' || ':*')), 0) AS pg_search_rank
FROM shop_products
INNER JOIN shop_option_types ON shop_option_types.product_id = shop_products.id
INNER JOIN shop_catalogs ON shop_catalogs.option_type_id = shop_option_types.id
JOIN shop_sales ON shop_products.sale_id = shop_sales.id
WHERE (shop_sales.hidden = 'f' OR shop_products.id IN (%s)) AND shop_sales.status = 'READY' AND
LOCALTIMESTAMP BETWEEN shop_sales.start_date AND shop_sales.end_date AND shop_products.delivery_product = false
AND (
tsv @@ to_tsquery('simple', ''' ' || '%s' || ' ''' || ':*') OR
tsv @@ to_tsquery('simple', ''' ' || reverse('%s') || ' ''' || ':*')
)
),
grouped AS ( SELECT id, SUM(quantity_bought) AS quantity_bought, pg_search_rank FROM search_products GROUP BY id, pg_search_rank)
SELECT id, quantity_bought, (SELECT COUNT(1) FROM grouped) AS total
FROM grouped
ORDER BY pg_search_rank DESC
%s
`, query, query, arrayToString(finalSaleIds, ","), query, query, limitQ)
type Results struct {
Id string `db:"id"`
QuantityBought string `db:"quantity_bought"`
Total string `db:"total"`
}
results := []Results{}
if err = dbx.Select(&results, request); err != nil {
return
}
if len(results) == 0 {
return
}
total, _ = strconv.Atoi(results[0].Total)
for _, r := range results {
id, _ := strconv.Atoi(r.Id)
ids = append(ids, id)
}
return
}
func arrayToString(a []int, delim string) string {
return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]")
//return strings.Trim(strings.Join(strings.Split(fmt.Sprint(a), " "), delim), "[]")
//return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(a)), delim), "[]")
}
func sanitize(term string) (query string) {
query = ""
for _, ch := range term {
if ch == '\'' || ch == '?' || ch == '\\' || ch == ':' || ch == ';' {
query += " "
} else {
query += string(ch)
}
}
return
}
func updateDb() {
for {
select {
case <-quitDB:
return
case event := <-eventDB:
email := event.Email
timestamp := event.Timestamp
if email == "" || timestamp == 0 {
return
}
unixDate := time.Unix(timestamp, 0)
occurredAt := unixDate.Format(time.RFC3339)
url := event.Url
switch event.Event {
case "open":
q := fmt.Sprintf("UPDATE email_subscriptions SET opened_at = '%s' WHERE email = '%s'", occurredAt, email)
_, err = db.Exec(q)
if err != nil {
log.Fatalf("Unable to register open event: %v\n", err)
}
case "click":
clicked_url := url[0:min(len(url)-1, 254)]
q := fmt.Sprintf("UPDATE email_subscriptions SET (clicked_at, last_clicked_url) = ('%s', '%s') WHERE email = '%s'", occurredAt, clicked_url, email)
_, err = db.Exec(q)
if err != nil {
log.Fatalf("Unable to register click event: %v\n", err)
}
}
}
}
}
func min(a, b int) int {
if a <= b {
return a
} else {
return b
}
}
func configureNewRelic() {
agent := gorelic.NewAgent()
agent.Verbose = true
agent.NewrelicLicense = os.Getenv("NEW_RELIC_LICENSE_KEY")
agent.NewrelicName = "Go baligam events handler"
agent.Run()
}