-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.odin
695 lines (624 loc) · 17.4 KB
/
main.odin
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
package main
import "core:container/lru"
import "core:fmt"
import "core:log"
import "core:mem"
import "core:net"
import "core:os"
import "core:path/filepath"
import "core:slice"
import "core:strings"
import "core:time"
import http "./shared/odin-http"
import pq "./shared/odin-postgresql"
LOGGER_OPTIONS: log.Options : {
.Level,
.Terminal_Color,
.Line,
.Short_File_Path,
}
CACHE_TEMPLATE_CAP :: 10
DEV :: #config(DEV, ODIN_DEBUG)
TRACK_LEAKS :: DEV
DOCKER :: !DEV
HTTP_CACHE_CSS :: !DEV
HTTP_CACHE_HTML :: !DEV
HTTP_CACHE_JS :: !DEV
CACHE_STATIC :: !DEV // TODO
CACHE_TEMPLATE :: !DEV
LOGGER_LEVEL: log.Level : .Debug when #config(DEBUG_LEVEL, DEV) else .Info
pool: Pg_Pool_Atomic
when CACHE_TEMPLATE {
cache_template: lru.Cache(string, string)
}
main :: proc() {
logger := log.create_console_logger(LOGGER_LEVEL, LOGGER_OPTIONS)
defer log.destroy_console_logger(logger)
context.logger = logger
when TRACK_LEAKS {
track: mem.Tracking_Allocator
mem.tracking_allocator_init(&track, context.allocator)
context.allocator = mem.tracking_allocator(&track)
}
when CACHE_TEMPLATE {
lru.init(&cache_template, CACHE_TEMPLATE_CAP)
log.debug(cache_template)
cache_template.on_remove = proc(key, value: string, _: rawptr) {
delete(value)
}
defer lru.destroy(&cache_template, true)
}
core_count := os.processor_core_count()
pool_init(&pool, core_count, 1 when DEV else core_count)
defer pool_destroy(&pool)
serve()
when TRACK_LEAKS {
for _, leak in track.allocation_map {
log.warnf("%v leaked %v bytes\n", leak.location, leak.size)
}
for bad_free in track.bad_free_array {
log.errorf(
"%v allocation %p was freed badly\n",
bad_free.location,
bad_free.memory,
)
}
}
}
serve :: proc() {
s: http.Server
// Register a graceful shutdown when the program receives a SIGINT signal.
http.server_shutdown_on_interrupt(&s)
unauthed: http.Router
http.router_init(&unauthed)
defer http.router_destroy(&unauthed)
http.route_get(&unauthed, "/google_login", http.handler(google_login))
http.route_get(
&unauthed,
"/google_callback",
http.handler(google_callback),
)
http.route_get(&unauthed, "(.*)", http.handler(static))
authed: http.Router
http.router_init(&authed)
defer http.router_destroy(&authed)
// Routes are tried in order.
// Route matching is implemented using an implementation of Lua patterns, see the docs on them here:
// https://www.lua.org/pil/20.2.html
// They are very similar to regex patterns but a bit more limited, which makes them much easier to implement since Odin does not have a regex implementation.
// TODO: merge routine and exercises to a single route
http.route_get(&authed, "/", http.handler(routines))
http.route_get(&authed, "/edit", http.handler(edit))
http.route_get(&authed, "/routine", http.handler(routine))
http.route_get(&authed, "/logout", http.handler(logout))
http.route_post(
&authed,
"/routine_exercise",
http.handler(post_routine_exercise),
)
http.route_post(&authed, "/routine", http.handler(post_routine))
http.route_post(&authed, "/set", http.handler(post_set))
http.route_delete(
&authed,
"/routine_exercise",
http.handler(delete_routine_exercise),
)
http.route_delete(&authed, "/routine", http.handler(delete_routine))
http.route_delete(&authed, "/set", http.handler(delete_set))
http.route_patch(&authed, "/weekday", http.handler(toggle_weekday))
routed := authed_unauthed_handler(
&{authed = &authed, unauthed = &unauthed},
)
log.info("Listening on http://localhost:6969")
traced := http.middleware_proc(&routed, trace_handler_proc)
address := net.IP4_Address{0, 0, 0, 0} when DOCKER else net.IP4_Loopback
err := http.listen_and_serve(&s, traced, net.Endpoint{address, 6969})
log.assertf(err == nil, "server stopped with error: %v", err)
}
trace_handler_proc :: proc(
handler: ^http.Handler,
req: ^http.Request,
res: ^http.Response,
) {
log.info(req.url.raw)
next, ok_next := handler.next.?
if ok_next do next.handle(next, req, res)
}
sets :: proc(req: ^http.Request, res: ^http.Response) {
conn := pool_get(&pool)
defer pool_release(&pool, conn)
// TODO: remove workout_id from form, currently we will fetch it per set
// TODO: how will this figure out we are not in an old workout?
// TODO: maybe add chache for this
Form :: struct {
exercise_id: i32,
}
form, ok_form := url_decode(Form, req.url.query, context.temp_allocator)
log.debug(form)
if !ok_form {
http.respond_with_status(res, .Not_Found)
return
}
user_id := local_user_id
cmd := fmt.ctprintf(
`
WITH recent_workout AS (
SELECT w.id AS workout_id
FROM workouts w
JOIN sets s ON w.id = s.workout_id
WHERE s.exercise_id = %[0]d
ORDER BY s.end_datetime DESC
LIMIT 1
),
chosen_workout AS (
SELECT workout_id
FROM recent_workout
WHERE EXISTS (
SELECT 1
FROM sets s
WHERE s.workout_id = recent_workout.workout_id
AND s.end_datetime >= NOW() - INTERVAL '1 hour'
)
UNION ALL
SELECT NULL -- This will be used for cases when no recent workout is found
LIMIT 1
),
existing_sets AS (
SELECT s.id, s.weight, s.reps
FROM sets s
JOIN chosen_workout cw ON s.workout_id = cw.workout_id
WHERE s.exercise_id = %[0]d
)
SELECT es.id, es.weight, es.reps
FROM existing_sets es
UNION ALL
SELECT
NULL::INTEGER AS id,
NULL::SMALLINT AS weight,
NULL::SMALLINT AS reps
WHERE FALSE;`,
form.exercise_id,
)
query_res := exec_bin(conn, cmd)
if pq.result_status(query_res) != .Tuples_OK {
log.error(pq.error_message(conn))
http.respond_with_status(res, .Internal_Server_Error)
return
}
defer pq.clear(query_res)
Id_Weight_Reps :: struct {
id: i32,
weight, reps: i16,
}
sets := results(Id_Weight_Reps, query_res, context.temp_allocator)
b := strings.builder_make(context.temp_allocator)
w := strings.to_writer(&b)
for set in sets {
fmt.wprintf(
w,
`
<tr>
<td>%[0]d</td>
<td>%[1]d</td>
<td>
<button
hx-target="closest tr"
hx-swap="delete"
hx-delete="/set?set_id=%[2]d"
class="btn btn-sm btn-block btn-error btn-outline"
>
X
</button>
</td>
</tr>`,
set.weight,
set.reps,
set.id,
)
}
http.respond_html(res, strings.to_string(b), .Created)
}
post_set :: proc(req: ^http.Request, res: ^http.Response) {
conn := pool_get(&pool)
defer pool_release(&pool, conn)
// TODO: remove workout_id from form, currently we will fetch it per set
Form :: struct {
workout_id, exercise_id: i32,
weight, reps: i16,
}
CheckedForm :: struct {
using f: Form,
ok: bool,
}
form: CheckedForm
http.body(
req,
0x200,
&form,
proc(user_data: rawptr, body: http.Body, err: http.Body_Error) {
c := cast(^CheckedForm)user_data
c.f, c.ok = url_decode(Form, body, context.temp_allocator)
},
)
log.debug(form)
if !form.ok {
http.respond_with_status(res, .Not_Found)
return
}
user_id := local_user_id
cmd := fmt.ctprintf(
`
WITH recent_workout AS (
SELECT w.id AS workout_id, MAX(s.end_datetime) AS last_set_time
FROM workouts w
JOIN sets s ON w.id = s.workout_id
WHERE s.exercise_id = %[0]d
GROUP BY w.id
ORDER BY last_set_time DESC
LIMIT 1
),
new_workout AS (
INSERT INTO workouts (user_id, start_datetime)
SELECT %[3]d, NOW() -- Replace %[3]d with the user_id parameter
WHERE NOT EXISTS (
SELECT 1
FROM recent_workout rw
WHERE rw.last_set_time >= NOW() - INTERVAL '1 hour'
)
RETURNING id AS workout_id
),
chosen_workout AS (
SELECT workout_id FROM recent_workout
WHERE last_set_time >= NOW() - INTERVAL '1 hour'
UNION ALL
SELECT workout_id FROM new_workout
LIMIT 1
)
-- Perform the insert here
INSERT INTO sets (workout_id, exercise_id, weight, reps, end_datetime)
SELECT
cw.workout_id,
%[0]d,
%[1]d,
%[2]d,
CURRENT_TIMESTAMP
FROM chosen_workout cw
RETURNING id;
`,
form.exercise_id,
form.weight,
form.reps,
user_id,
)
query_res := exec_bin(conn, cmd)
if pq.result_status(query_res) != .Tuples_OK {
log.error(pq.error_message(conn))
http.respond_with_status(res, .Internal_Server_Error)
return
}
defer pq.clear(query_res)
set_id := result(i32, query_res, 0, 0)
html := fmt.tprintf(
`
<tr>
<td>%[0]d</td>
<td>%[1]d</td>
<td>
<button
hx-target="closest tr"
hx-swap="delete"
hx-delete="/set?set_id=%[2]d"
class="btn btn-sm btn-block btn-error btn-outline"
>
X
</button>
</td>
</tr>`,
form.weight,
form.reps,
set_id,
)
http.respond_html(res, html, .Created)
}
delete_set :: proc(req: ^http.Request, res: ^http.Response) {
conn := pool_get(&pool)
defer pool_release(&pool, conn)
Form :: struct {
set_id: i32,
}
form, ok_form := url_decode(Form, req.url.query, context.temp_allocator)
cmd := fmt.ctprintf(`
DELETE FROM sets
WHERE id = %d`, form.set_id)
query_res := exec_bin(conn, cmd)
if pq.result_status(query_res) != .Command_OK {
log.error(pq.error_message(conn))
http.respond_with_status(res, .Internal_Server_Error)
return
}
defer pq.clear(query_res)
http.respond_with_status(res, .OK)
}
Exercise_Query :: struct {
id: i32,
name: string,
weight, reps: i16,
}
Routine_Data :: struct {
name: string,
exercises: []Exercise_Query,
}
routine_templater :: proc(routine_data: ^Routine_Data) -> Templater {
t: Templater
t.user_data = routine_data
t.template = proc(t: ^Templater, w: io.Writer) {
data := cast(^Routine_Data)t.user_data
fmt.wprint(w, `<main class="px-8 pt-4 min-h-[80dvh] pb-20">`);{
fmt.wprintf(
w,
`
<div hx-boost="true" class="breadcrumbs text-sm">
<ul>
<li><a href="/">Home</a></li>
<li>%[0]s</li>
</ul>
</div>`,
data.name,
)
if len(data.exercises) == 0 {
html := get_template("no-exercises")
fmt.wprint(w, html)
return
}
fmt.wprintf(w, `<ul class="grid gap-4 py-4">`);{
// TODO: the sets are still lazy
template := get_template("exercise-with-sets")
for e in data.exercises {
fmt.wprintf(w, template, e.id, e.name, e.weight, e.reps)
}
};fmt.wprintf(w, `</ul>`)
};fmt.wprint(w, `</main>`)
}
return t
}
routine :: proc(req: ^http.Request, res: ^http.Response) {
Form :: struct {
routine_id: i32,
}
form, ok_form := url_decode(Form, req.url.query, context.temp_allocator)
if !ok_form {
http.respond_with_status(res, .Not_Found)
return
}
conn := pool_get(&pool)
defer pool_release(&pool, conn)
cmd := fmt.ctprintf(
`
SELECT name
FROM routines
WHERE id = %d`,
form.routine_id,
)
query_res := exec_bin(conn, cmd)
if pq.result_status(query_res) != .Tuples_OK {
log.error(pq.error_message(conn))
http.respond_with_status(res, .Internal_Server_Error)
return
}
defer pq.clear(query_res)
if pq.n_tuples(query_res) != 1 do return
assert(pq.n_fields(query_res) == 1)
name := result(string, query_res, 0, 0, context.temp_allocator)
cmd_2 := fmt.ctprintf(
`
WITH most_recent_sets AS (
SELECT DISTINCT ON (s.exercise_id)
s.exercise_id,
s.weight,
s.reps,
s.end_datetime
FROM
sets s
JOIN
workouts w ON s.workout_id = w.id
JOIN
routines_exercises re ON re.exercise_id = s.exercise_id
WHERE
re.routine_id = %[0]d
ORDER BY
s.exercise_id, s.end_datetime DESC
)
SELECT
e.id AS exercise_id,
e.name AS exercise_name,
COALESCE(most_recent_sets.weight, 0)::SMALLINT AS recent_weight,
COALESCE(most_recent_sets.reps, 1)::SMALLINT AS recent_reps
FROM
exercises e
JOIN
routines_exercises re ON e.id = re.exercise_id
LEFT JOIN
most_recent_sets ON e.id = most_recent_sets.exercise_id
WHERE
re.routine_id = %[0]d
ORDER BY
e.id; `,
form.routine_id,
)
query_res_2 := exec_bin(conn, cmd_2)
if pq.result_status(query_res_2) != .Tuples_OK {
http.respond_with_status(res, .Internal_Server_Error)
log.error(pq.error_message(conn))
return
}
defer pq.clear(query_res_2)
if pq.n_tuples(query_res_2) > 0 do assert(pq.n_fields(query_res_2) == 4)
exercises := results(Exercise_Query, query_res_2, context.temp_allocator)
log.debug(exercises)
b := strings.builder_make(context.temp_allocator)
w := strings.to_writer(&b)
routine_data := Routine_Data{name, exercises}
layout_data := Layout_Data {
Head_Data{title = name, scripts = {"htmx@2.0.0.js"}},
Top_Nav_Data {
profile_picture = "https://lh3.googleusercontent.com/a/AAcHTtcIA7reOrDrtSslK5DfbBWfqLtWbqxx4O1TVMQA1yO7Pg=s96-c",
},
routine_templater(&routine_data),
Bottom_Nav_Data{selection = .Home},
}
layout_templater := layout_templater(&layout_data)
layout_templater.template(&layout_templater, w)
http.respond_html(res, strings.to_string(b))
}
routines :: proc(req: ^http.Request, res: ^http.Response) {
conn := pool_get(&pool)
defer pool_release(&pool, conn)
user_id := local_user_id
cmd := fmt.ctprintf(
`
SELECT id, name, weekdays
FROM routines
WHERE user_id = %[0]d;`,
user_id,
)
rs_res := exec_bin(conn, cmd)
if pq.result_status(rs_res) != .Tuples_OK {
log.error(pq.error_message(conn))
http.respond_with_status(res, .Internal_Server_Error)
return
}
defer pq.clear(rs_res)
// TODO: results should return an ok
b := strings.builder_make(context.temp_allocator)
w := strings.to_writer(&b)
routines := results(
Routine_Id_Name_Weekdays,
rs_res,
context.temp_allocator,
)
// sort by weekday server timezone
// user_ptr := context.user_ptr
// context.user_ptr = &form.weekday
slice.sort_by_key(
routines,
proc(using r: Routine_Id_Name_Weekdays) -> u16 {
// // weekday := (cast(^time.Weekday)context.user_ptr)^
// weekday := time.Weekday.Wednesday
// earliest := earliest_weekday(r.weekdays)
// x := transmute(u16)r.weekdays +
// (7 if cast(u8)weekday > cast(u8)earliest else 0)
// log.debugf(
// "ws: %v, w: %d, e: %d n0: %d, n1: %d",
// r.weekdays,
// cast(u8)weekday,
// cast(u8)earliest,
// transmute(u16)r.weekdays,
// x,
// )
// return x
return transmute(u16)weekdays
},
)
routines_data := Routines_Data{routines}
layout_data := Layout_Data {
Head_Data{title = "Routines", scripts = {"htmx@2.0.0.js"}},
Top_Nav_Data {
profile_picture = "https://lh3.googleusercontent.com/a/AAcHTtcIA7reOrDrtSslK5DfbBWfqLtWbqxx4O1TVMQA1yO7Pg=s96-c",
},
routines_templater(&routines_data),
Bottom_Nav_Data{selection = .Home},
}
layout_templater := layout_templater(&layout_data)
layout_templater.template(&layout_templater, w)
http.respond_html(res, strings.to_string(b))
}
Routine_Id_Name_Weekdays :: struct {
id: i32,
name: string,
weekdays: Weekdays,
}
Routines_Data :: struct {
routines: []Routine_Id_Name_Weekdays,
}
routines_templater :: proc(routines_data: ^Routines_Data) -> Templater {
t: Templater
t.user_data = routines_data
t.template = proc(t: ^Templater, w: io.Writer) {
data := cast(^Routines_Data)t.user_data
fmt.wprint(w, `<main class="px-8 pt-4 min-h-[80dvh] pb-20">`);{
if len(data.routines) == 0 {
html := get_template("no-routines")
return
}
fmt.wprintf(w, `<ul hx-boost="true" class="grid gap-4 py-4">`);{
for r in data.routines {
fmt.wprintf(
w,
`
<li>
<a
href="/routine?routine_id=%[0]d"
class="btn btn-block btn-outline btn-accent"
>
%[1]s
</a>
</li> `,
r.id,
r.name,
)
}
};fmt.wprintf(w, `</ul>`)
};fmt.wprint(w, `</main>`)
}
return t
}
earliest_weekday :: proc(weekdays: Weekdays) -> time.Weekday {
for w in time.Weekday do if w in weekdays do return .Monday
unreachable()
}
static :: proc(req: ^http.Request, res: ^http.Response) {
path := req.url.path
ext := filepath.ext(req.url.path)
switch ext {
case "":
path = strings.concatenate({path, ".html"}, context.temp_allocator)
when HTTP_CACHE_HTML {
cache_control :: "public, max-age=31536000"
http.headers_set(&res.headers, "Cache-Control", cache_control)
}
case ".js":
when HTTP_CACHE_JS {
cache_control :: "public, max-age=31536000"
http.headers_set(&res.headers, "Cache-Control", cache_control)
}
case ".css":
when HTTP_CACHE_CSS {
cache_control :: "public, max-age=31536000"
http.headers_set(&res.headers, "Cache-Control", cache_control)
}
case ".png":
cache_control :: "public, max-age=31536000"
http.headers_set(&res.headers, "Cache-Control", cache_control)
}
http.respond_dir(res, "/", "./static", path)
}
get_template :: proc(path: string, loc := #caller_location) -> string {
when CACHE_TEMPLATE {
cached_bytes, ok_cache := lru.get(&cache_template, path)
if ok_cache do return cached_bytes
}
template_path := strings.concatenate(
{"./templates/", path, ".html"},
context.temp_allocator,
)
bytes, ok := os.read_entire_file_from_filename(
template_path,
context.allocator when CACHE_TEMPLATE else context.temp_allocator,
loc = loc,
)
log.assertf(ok, "%s template", path)
when CACHE_TEMPLATE {
lru.set(&cache_template, path, transmute(string)bytes)
}
return transmute(string)bytes
}