Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
497 lines (429 loc) · 12.6 KB
/
Copy pathmain.go
File metadata and controls
497 lines (429 loc) · 12.6 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
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
package main
import (
"context"
"crypto/md5"
"crypto/rand"
"embed"
"encoding/json"
"fmt"
"html/template"
"io"
"log/slog"
"math"
"net/http"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/apex/gateway/v2"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
//go:embed static
var static embed.FS
// NextBus describes when the bus is coming
type NextBus struct {
EstimatedArrival string `json:"EstimatedArrival"`
Load string `json:"Load"`
}
// Service is one bus route calling at a stop
type Service struct {
ServiceNo string `json:"ServiceNo"`
NextBus NextBus `json:"NextBus"`
NextBus2 NextBus `json:"NextBus2"`
NextBus3 NextBus `json:"NextBus3"`
}
// SGBusArrivals describes the response from the datamall API
type SGBusArrivals struct {
BusStopCode string `json:"BusStopCode"`
Services []Service `json:"Services"`
}
// A fictional bus stop that always has buses coming. It never reaches
// datamall, so the render can be checked - by hand, by the tests, or by the
// deploy - without depending on LTA being up or on an ACCOUNTKEY. It is
// marked noindex and named as a test stop so nobody mistakes it for live data.
const (
testStopCode = "99999"
testStopName = "Test Bus Stop"
)
// testArrivals makes up buses relative to now, so the stop always looks live.
// Every offset carries a half minute: on a whole minute the countdown would
// already read one lower by the time the page renders.
func testArrivals(now time.Time) (arrivals SGBusArrivals) {
sgt := now.In(time.FixedZone("SGT", 8*60*60))
at := func(d time.Duration) string { return sgt.Add(d).Format(time.RFC3339) }
arrivals.BusStopCode = testStopCode
// deliberately not in arrival order, so the sort has something to do
arrivals.Services = []Service{
{
ServiceNo: "666",
NextBus: NextBus{EstimatedArrival: at(5*time.Minute + 30*time.Second), Load: "SDA"},
NextBus2: NextBus{EstimatedArrival: at(17*time.Minute + 30*time.Second), Load: "LSD"},
NextBus3: NextBus{EstimatedArrival: at(32*time.Minute + 30*time.Second), Load: "SEA"},
},
{
ServiceNo: "42",
NextBus: NextBus{EstimatedArrival: at(time.Minute + 30*time.Second), Load: "SEA"},
},
}
sortByArrival(arrivals.Services)
return
}
type Server struct {
mux *http.ServeMux
busStops BusStops
index *template.Template
// now is the clock, swapped out in tests
now func() time.Time
}
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
bytes int
}
func (rw *responseWriter) WriteHeader(code int) {
if !rw.wroteHeader {
rw.status = code
rw.wroteHeader = true
rw.ResponseWriter.WriteHeader(code)
}
}
func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.wroteHeader {
rw.WriteHeader(http.StatusOK)
}
n, err := rw.ResponseWriter.Write(b)
rw.bytes += n
return n, err
}
func (rw *responseWriter) Status() int {
return rw.status
}
func (rw *responseWriter) BytesWritten() int {
return rw.bytes
}
func getLogger(logLevel string) *slog.Logger {
levelVar := slog.LevelVar{}
if logLevel != "" {
if err := levelVar.UnmarshalText([]byte(logLevel)); err != nil {
panic(fmt.Sprintf("Invalid log level %s: %v", logLevel, err))
}
}
if _, ok := os.LookupEnv("AWS_LAMBDA_FUNCTION_NAME"); ok {
return slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: levelVar.Level(),
}))
}
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: levelVar.Level(),
}))
}
func main() {
slog.SetDefault(getLogger(os.Getenv("LOGLEVEL")))
server, err := NewServer("static/all.json")
if err != nil {
slog.Error("failed to create server", "error", err)
os.Exit(1)
}
handler := server.middlewareChain(server.mux)
if _, ok := os.LookupEnv("AWS_LAMBDA_FUNCTION_NAME"); ok {
slog.Info("starting server", "version", os.Getenv("VERSION"))
lambda.Start(lambdaHandler(handler))
return
} else {
slog.Info("starting local server", "version", os.Getenv("VERSION"), "port", os.Getenv("PORT"))
err = http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), handler)
}
slog.Error("error listening", "error", err)
}
func NewServer(busStopsPath string) (*Server, error) {
bs, err := loadBusJSON(busStopsPath)
if err != nil {
return nil, fmt.Errorf("load bus stops: %w", err)
}
if len(bs) == 0 {
return nil, fmt.Errorf("bus stop data is empty")
}
srv := Server{
mux: http.NewServeMux(),
busStops: bs,
now: time.Now,
}
funcs := template.FuncMap{
"version": func() string { return os.Getenv("VERSION") },
"totalStops": func() int { return len(srv.busStops) },
"nameBusStop": func(id string) string {
if id == testStopCode {
return testStopName
}
return srv.busStops.nameBusStop(id)
},
"isTestStop": func(id string) bool { return id == testStopCode },
"styleBusStop": styleBusStop,
"loadClass": loadClass,
"countdown": formatCountdown,
}
srv.index, err = template.New("").Funcs(funcs).ParseFS(static, "static/index.html")
if err != nil {
return nil, fmt.Errorf("parse index template: %w", err)
}
srv.routes()
return &srv, nil
}
func (s *Server) routes() {
s.mux.Handle("/{$}", uniqueVisitor(http.HandlerFunc(s.handleIndex)))
s.mux.HandleFunc("/closest", s.handleClosest)
s.mux.HandleFunc("/icon", handleIcon)
fileServer := http.FileServer(http.FS(static))
s.mux.Handle("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "public, max-age=86400")
fileServer.ServeHTTP(w, r)
}))
}
func (s *Server) middlewareChain(handler http.Handler) http.Handler {
return logRequest(recoverPanic(handler))
}
func recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
slog.Error("recovered from panic", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func (s *Server) handleClosest(w http.ResponseWriter, r *http.Request) {
lat, err := strconv.ParseFloat(r.URL.Query().Get("lat"), 32)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
lng, err := strconv.ParseFloat(r.URL.Query().Get("lng"), 32)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
closest := s.busStops.closest(Point{lat: lat, lng: lng})
http.Redirect(w, r, fmt.Sprintf("/?id=%s", closest.BusStopCode), http.StatusFound)
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
id := r.URL.Query().Get("id")
var arriving SGBusArrivals
if id == testStopCode {
arriving = testArrivals(s.now())
} else if id != "" {
var err error
arriving, err = busArrivals(id)
if err != nil {
slog.Warn("failed to retrieve bus timings", "error", err)
http.Error(w, fmt.Sprintf("datamall API is returning, %s", err.Error()), http.StatusFailedDependency)
return
}
}
w.Header().Set("X-Version", os.Getenv("VERSION"))
data := struct {
SGBusArrivals
Now time.Time
}{arriving, s.now()}
if err := s.index.ExecuteTemplate(w, "index.html", data); err != nil {
slog.Error("template failed to render", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Match app.js: truncate toward zero, using seconds through +/-60 seconds.
func formatCountdown(arrival string, now time.Time) string {
at, err := time.Parse(time.RFC3339, arrival)
if err != nil {
return arrival
}
seconds := at.Sub(now).Seconds()
if math.Abs(seconds) > 60 {
return fmt.Sprintf("%dm", int(seconds/60))
}
return fmt.Sprintf("%ds", int(seconds))
}
func busArrivals(stopID string) (arrivals SGBusArrivals, err error) {
if stopID == "" {
return arrivals, fmt.Errorf("invalid stop ID")
}
url := fmt.Sprintf("https://datamall2.mytransport.sg/ltaodataservice/v3/BusArrival?BusStopCode=%s", stopID)
client := &http.Client{
Timeout: 2 * time.Second,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return
}
req.Header.Add("AccountKey", os.Getenv("ACCOUNTKEY"))
res, err := client.Do(req)
if err != nil {
return
}
defer func() {
if err := res.Body.Close(); err != nil {
slog.Error("failed to close response body", "error", err)
}
}()
if res.StatusCode != http.StatusOK {
return arrivals, fmt.Errorf("bad response: %d", res.StatusCode)
}
return parseArrivals(res.Body)
}
// parseArrivals decodes a datamall response, soonest bus first
func parseArrivals(r io.Reader) (arrivals SGBusArrivals, err error) {
err = json.NewDecoder(r).Decode(&arrivals)
if err != nil {
slog.Error("failed to decode response", "error", err)
return
}
sortByArrival(arrivals.Services)
return
}
// sortByArrival puts the buses arriving soonest first
func sortByArrival(services []Service) {
sort.Slice(services, func(i, j int) bool {
return services[i].NextBus.EstimatedArrival < services[j].NextBus.EstimatedArrival
})
}
type Point struct {
lat float64
lng float64
}
// BusStop describes a Singaporean (LTA) bus stop
type BusStop struct {
BusStopCode string `json:"BusStopCode"`
RoadName string `json:"RoadName"`
Description string `json:"Description"`
Latitude float64 `json:"Latitude"`
Longitude float64 `json:"Longitude"`
}
type BusStops []BusStop
func loadBusJSON(jsonfile string) (bs BusStops, err error) {
content, err := static.ReadFile(jsonfile)
if err != nil {
return
}
err = json.Unmarshal(content, &bs)
if err != nil {
return
}
return
}
func (bs BusStops) closest(location Point) BusStop {
c := -1
closestSoFar := math.Inf(1)
for i := range bs {
distance := location.distance(Point{bs[i].Latitude, bs[i].Longitude})
if distance < closestSoFar {
// Set the return
c = i
// Record closest distance
closestSoFar = distance
}
}
return bs[c]
}
func (bs BusStops) nameBusStop(busStopID string) (description string) {
for _, p := range bs {
if busStopID == p.BusStopCode {
return p.Description
}
}
return ""
}
func styleBusStop(busStopID string) (style template.CSS) {
data := []byte(busStopID)
return template.CSS(fmt.Sprintf("background-color: #%.3x; padding: 0.2em", md5.Sum(data)))
}
func loadClass(load string) string {
switch load {
case "SEA":
return "load-seats"
case "SDA":
return "load-standing"
case "LSD":
return "load-full"
default:
return ""
}
}
func (p Point) distance(p2 Point) float64 {
latd := p2.lat - p.lat
lngd := p2.lng - p.lng
return latd*latd + lngd*lngd
}
func logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{
ResponseWriter: w,
status: http.StatusOK,
}
defer func() {
// Log response headers
for name, values := range rw.Header() {
for _, value := range values {
slog.Debug("response header", "name", name, "value", value)
}
}
slog.Info("response",
"req_method", r.Method,
"req_ip", r.RemoteAddr,
"req_path", r.RequestURI,
"res_status", rw.Status(),
"res_size", rw.BytesWritten(),
"res_content_type", rw.Header().Get("Content-Type"),
"duration", time.Since(start).Milliseconds(),
)
}()
next.ServeHTTP(rw, r)
})
}
func uniqueVisitor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, _ := r.Cookie("visitor")
if cookie == nil || cookie.Value == "" {
cookie = &http.Cookie{
Name: "visitor",
Value: "visitor-" + rand.Text(),
Path: "/",
Expires: time.Now().Add(365 * 24 * time.Hour),
}
http.SetCookie(w, cookie)
}
// Keep the existing log field and message for visitors.sh, including
// first visits that never load an asset or return to the page.
slog.Info("return visitor", "unique", cookie.Value)
next.ServeHTTP(w, r)
})
}
// lambdaHandler keeps cookies only in the HTTP API v2 cookies field. The
// gateway also copies them into Headers at WriteHeader time, duplicating them.
func lambdaHandler(handler http.Handler) func(context.Context, events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
return func(ctx context.Context, event events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
r, err := gateway.NewRequest(ctx, event)
if err != nil {
return events.APIGatewayV2HTTPResponse{}, err
}
w := gateway.NewResponse()
handler.ServeHTTP(w, r)
response := w.End()
for key := range response.Headers {
if strings.EqualFold(key, "Set-Cookie") {
delete(response.Headers, key)
}
}
for key := range response.MultiValueHeaders {
if strings.EqualFold(key, "Set-Cookie") {
delete(response.MultiValueHeaders, key)
}
}
return response, nil
}
}