forked from code-golf/code-golf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
228 lines (204 loc) · 6.21 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
package main
import (
"crypto/tls"
"database/sql"
"log"
"math/rand"
"net/http"
"os"
"time"
"github.com/code-golf/code-golf/github"
"github.com/code-golf/code-golf/middleware"
"github.com/code-golf/code-golf/routes"
"github.com/go-chi/chi/v5"
_ "github.com/lib/pq"
"golang.org/x/crypto/acme/autocert"
)
func main() {
log.SetFlags(log.Ltime)
rand.Seed(time.Now().UTC().UnixNano())
db, err := sql.Open("postgres", "")
if err != nil {
panic(err)
}
r := chi.NewRouter()
r.Use(
middleware.Logger,
middleware.Recoverer,
middleware.RedirectHost,
middleware.Static,
middleware.RedirectSlashes,
middleware.Compress(5),
// middleware.Downtime,
middleware.DatabaseHandler(db),
middleware.GolferHandler,
)
r.NotFound(routes.NotFound)
r.Get("/", routes.Index)
r.Get("/{hole}", routes.Hole)
r.Get("/ng/{hole}", routes.HoleNG)
r.Get("/about", routes.About)
r.Route("/admin", func(r chi.Router) {
r.Use(middleware.AdminArea)
r.Get("/", routes.Admin)
r.Get("/solutions", routes.AdminSolutions)
r.Get("/solutions/run", routes.AdminSolutionsRun)
})
r.Route("/api", func(r chi.Router) {
r.Use(middleware.API)
r.Get("/", routes.API)
r.Get("/langs", routes.APILangs)
r.Get("/langs/{lang}", routes.APILang)
r.Get("/suggestions/golfers", routes.APISuggestionsGolfers)
})
r.Get("/assets/{asset}", routes.Asset)
r.Get("/callback", routes.Callback)
r.Get("/callback/dev", routes.CallbackDev)
r.Get("/feeds", routes.Feeds)
r.Get("/feeds/{feed}", routes.Feed)
r.Route("/golfer", func(r chi.Router) {
r.Use(middleware.GolferArea)
r.Post("/cancel-delete", routes.GolferCancelDelete)
r.Post("/delete", routes.GolferDelete)
r.Get("/settings", routes.GolferSettings)
r.Post("/settings", routes.GolferSettingsPost)
})
r.Route("/golfers/{name}", func(r chi.Router) {
r.Use(middleware.GolferInfoHandler)
r.Get("/", routes.GolferCheevos)
r.Get("/holes", routes.GolferHoles)
r.Get("/holes/{scoring}", routes.GolferHoles)
})
r.Get("/healthz", routes.Healthz)
r.Get("/ideas", routes.Ideas)
r.Get("/log-out", routes.LogOut)
r.Get("/random", routes.Random)
r.Get("/ng/random", routes.NGRandom)
r.Route("/rankings", func(r chi.Router) {
// Redirect some old URLs that got out.
r.Get("/", redir("/rankings/holes/all/all/bytes"))
r.Get("/holes", redir("/rankings/holes/all/all/bytes"))
r.Get("/holes-ng", redir("/rankings/holes-ng/all/all/bytes"))
r.Get("/holes/all/all/all", redir("/rankings/holes/all/all/bytes"))
r.Get("/medals", redir("/rankings/medals/all/all/all"))
r.Get("/cheevos", routes.RankingsCheevos)
r.Get("/cheevos/all", redir("/rankings/cheevos"))
r.Get("/cheevos/{cheevo}", routes.RankingsCheevos)
r.Get("/holes/{hole}/{lang}/{scoring}", routes.RankingsHoles)
r.Get("/holes-ng/{hole}/{lang}/{scoring}", routes.RankingsHolesNG)
r.Get("/medals/{hole}/{lang}/{scoring}", routes.RankingsMedals)
r.Get("/solutions", routes.RankingsSolutions)
})
r.Get("/recent", routes.Recent)
r.Get("/recent/{lang}", routes.Recent)
r.Get("/scores/{hole}/{lang}", routes.Scores)
r.Get("/scores/{hole}/{lang}/all", routes.ScoresAll)
r.Get("/scores/{hole}/{lang}/{scoring}", routes.Scores)
r.Get("/scores/{hole}/{lang}/{scoring}/{page}", routes.Scores)
r.Get("/scores/{hole}/{lang}/{scoring}/mini", routes.ScoresMini)
r.Get("/sitemap.xml", routes.Sitemap)
r.Post("/solution", routes.Solution)
r.Get("/stats", routes.Stats)
r.Get("/users/{name}", routes.User)
certManager := autocert.Manager{
Cache: autocert.DirCache("certs"),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(
"code.golf", "www.code.golf",
// Legacy domain.
"code-golf.io", "www.code-golf.io",
),
}
server := &http.Server{
Addr: ":1443",
Handler: r,
TLSConfig: &tls.Config{
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // HTTP/2-required.
},
CurvePreferences: []tls.CurveID{tls.CurveP256, tls.X25519},
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
},
}
var crt, key string
if _, dev := os.LookupEnv("DEV"); dev {
crt = "localhost.pem"
key = "localhost-key.pem"
} else {
server.TLSConfig.GetCertificate = certManager.GetCertificate
}
// Every minute.
go func() {
for range time.Tick(time.Minute) {
for _, view := range []string{"medals", "rankings"} {
if _, err := db.Exec(
"REFRESH MATERIALIZED VIEW CONCURRENTLY " + view,
); err != nil {
log.Println(err)
}
}
}
}()
// Every 5 minutes.
go func() {
// Various GitHub API requests.
for range time.Tick(5 * time.Minute) {
github.Run(db)
}
}()
// Every hour.
go func() {
for range time.Tick(time.Hour) {
for _, job := range [...]struct{ name, sql string }{
{
"expired sessions",
`DELETE FROM sessions
WHERE last_used < TIMEZONE('UTC', NOW()) - INTERVAL '30 days'`,
},
{
"superfluous users",
`DELETE FROM users u
WHERE NOT EXISTS (SELECT FROM sessions WHERE user_id = u.id)
AND NOT EXISTS (SELECT FROM trophies WHERE user_id = u.id)`,
},
{
"users scheduled for deletion",
"DELETE FROM users WHERE delete < TIMEZONE('UTC', NOW())",
},
} {
if res, err := db.Exec(job.sql); err != nil {
log.Println(err)
} else if rows, _ := res.RowsAffected(); rows != 0 {
log.Printf("Deleted %d %s\n", rows, job.name)
}
}
}
}()
// Configure core dumps so that defAsm can read them to dump registers.
// Note this affects the host, maybe one day Linux will namespace these.
// See https://stackoverflow.com/a/39152041
if err := os.WriteFile(
"/proc/sys/kernel/core_pattern", []byte("/tmp/core"), 0644,
); err != nil {
log.Println(err)
}
if err := os.WriteFile(
"/proc/sys/kernel/core_uses_pid", []byte("0"), 0644,
); err != nil {
log.Println(err)
}
log.Println("Listening…")
// Redirect HTTP to HTTPS and handle ACME challenges.
go func() {
panic(http.ListenAndServe(":1080", certManager.HTTPHandler(nil)))
}()
// Serve HTTPS.
panic(server.ListenAndServeTLS(crt, key))
}
func redir(url string) http.HandlerFunc {
return http.RedirectHandler(url, http.StatusPermanentRedirect).ServeHTTP
}