-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
144 lines (118 loc) · 4.8 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
package main
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"time"
chi "github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/icco/gutil/logging"
"github.com/icco/reportd/lib"
"github.com/namsral/flag"
"go.uber.org/zap"
)
var (
service = "reportd"
log = logging.Must(logging.NewLogger(service))
project = flag.String("project", os.Getenv("PROJECT_ID"), "Project ID containing the bigquery dataset to upload to.")
dataset = flag.String("dataset", os.Getenv("DATASET"), "The bigquery dataset to upload to.")
aTable = flag.String("analytics_table", os.Getenv("ANALYTICS_TABLE"), "The bigquery table to upload analytics to.")
rTable = flag.String("reports_table", os.Getenv("REPORTS_TABLE"), "The bigquery table to upload reports to.")
)
func main() {
flag.Parse()
port := "8080"
if fromEnv := os.Getenv("PORT"); fromEnv != "" {
port = fromEnv
}
log.Infow("Starting up", "host", fmt.Sprintf("http://localhost:%s", port))
ctx := context.Background()
if err := lib.UpdateReportsBQSchema(ctx, *project, *dataset, *rTable); err != nil {
log.Errorw("report table update", zap.Error(err))
}
if err := lib.UpdateAnalyticsBQSchema(ctx, *project, *dataset, *aTable); err != nil {
log.Errorw("analytics table update", zap.Error(err))
}
r := chi.NewRouter()
r.Use(middleware.RealIP)
r.Use(logging.Middleware(log.Desugar(), *project))
r.Use(cors.New(cors.Options{
AllowCredentials: true,
OptionsPassthrough: true,
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
MaxAge: 300, // Maximum value not ignored by any of major browsers
}).Handler)
r.Use(middleware.Timeout(30 * time.Second))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`hi! Please see <a href="https://github.com/icco/reportd">github.com/icco/reportd</a> for more information.`))
})
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok."))
})
// Needed because some browsers fire off an OPTIONS request before sending a
// POST to validate CORS.
r.Options("/report/{bucket}", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
})
r.Options("/analytics/{bucket}", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
})
r.Get("/report/{bucket}", func(w http.ResponseWriter, r *http.Request) {
bucket := chi.URLParam(r, "bucket")
newURL := fmt.Sprintf("/view/%s", bucket)
http.Redirect(w, r, newURL, http.StatusPermanentRedirect)
})
r.Post("/report/{bucket}", func(w http.ResponseWriter, r *http.Request) {
bucket := chi.URLParam(r, "bucket")
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
bodyStr := buf.String()
ct := r.Header.Get("content-type")
data, err := lib.ParseReport(ct, bodyStr, bucket)
if err != nil {
log.Errorw("error seen during report parse", "content-type", ct, "user-agent", r.UserAgent(), "bodyJson", bodyStr, zap.Error(err))
http.Error(w, "processing error", 500)
return
}
// Log the report.
log.Infow("report recieved", "content-type", ct, "bucket", bucket, "user-agent", r.UserAgent(), "report", data)
if err := lib.WriteReportToBigQuery(r.Context(), *project, *dataset, *rTable, []*lib.Report{data}); err != nil {
log.Errorw("error during report upload", "dataset", *dataset, "project", *project, "table", *rTable, "bodyJson", bodyStr, zap.Error(err))
http.Error(w, "uploading error", 500)
return
}
})
r.Get("/analytics/{bucket}", func(w http.ResponseWriter, r *http.Request) {
bucket := chi.URLParam(r, "bucket")
newURL := fmt.Sprintf("/view/%s", bucket)
http.Redirect(w, r, newURL, http.StatusPermanentRedirect)
})
r.Post("/analytics/{bucket}", func(w http.ResponseWriter, r *http.Request) {
bucket := chi.URLParam(r, "bucket")
ct := r.Header.Get("content-type")
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
bodyStr := buf.String()
data, err := lib.ParseAnalytics(bodyStr, bucket)
if err != nil {
log.Errorw("error seen during analytics parse", zap.Error(err), "content-type", ct, "user-agent", r.UserAgent(), "bodyJson", bodyStr)
http.Error(w, "processing error", 500)
return
}
// Log the report.
log.Infow("analytics recieved", "content-type", ct, "bucket", bucket, "user-agent", r.UserAgent(), "analytics", data)
if err := lib.WriteAnalyticsToBigQuery(r.Context(), *project, *dataset, *aTable, []*lib.WebVital{data}); err != nil {
log.Errorw("error during analytics upload", "dataset", *dataset, "project", *project, "table", *aTable, "bodyJson", bodyStr, zap.Error(err))
http.Error(w, "uploading error", 500)
return
}
})
log.Fatal(http.ListenAndServe(":"+port, r))
}