-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (155 loc) · 4.01 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
package main
import (
"context"
"encoding/csv"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"dev.acmcsuf.com/fullyhacks-qrms/server"
"dev.acmcsuf.com/fullyhacks-qrms/sqldb"
"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
"libdb.so/hserve"
"libdb.so/xcsv"
)
var (
addr = ":5767"
db = "fullyhacks-qrms.db"
rootTokenFile = "root-token.txt"
verbose = false
)
func init() {
flag.StringVar(&addr, "addr", addr, "address to listen on")
flag.StringVar(&db, "db", db, "path to the database file")
flag.StringVar(&rootTokenFile, "root-token-file", rootTokenFile, "path to the root token file")
flag.BoolVar(&verbose, "verbose", verbose, "enable verbose logging")
flag.Usage = func() {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "Usage: %s [flags] [command]\n", filepath.Base(os.Args[0]))
fmt.Fprintln(out)
fmt.Fprintln(out, "Commands:")
fmt.Fprintln(out, " import-users <file> Import users from a CSV file")
fmt.Fprintln(out, " serve Start the server")
fmt.Fprintln(out)
fmt.Fprintln(out, "Flags:")
flag.PrintDefaults()
}
flag.Parse()
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
opts := &tint.Options{
Level: slog.LevelInfo,
NoColor: !isatty.IsTerminal(os.Stderr.Fd()),
}
if verbose {
opts.Level = slog.LevelDebug
}
logger := slog.New(tint.NewHandler(os.Stderr, opts))
slog.SetDefault(logger)
switch flag.Arg(0) {
case "import-users":
if err := importUsers(ctx, logger); err != nil {
logger.Error("Failed to import users", "error", err)
os.Exit(1)
}
case "serve":
fallthrough
default:
if err := startServer(ctx, logger); err != nil {
logger.Error("Failed to start server", "error", err)
os.Exit(1)
}
}
}
func importUsers(ctx context.Context, logger *slog.Logger) error {
file := flag.Arg(1)
if file == "" {
return fmt.Errorf("no file provided")
}
db, err := openDB()
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
f, err := os.Open(file)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
csvReader := csv.NewReader(f)
header, err := csvReader.Read()
if err != nil {
return fmt.Errorf("failed to read header: %w", err)
}
expectedHeader := []string{"Name", "School", "Email", "Food", "Major"}
type Record struct {
Name string
X1 string
Email string
}
if !slices.Equal(header, expectedHeader) {
return fmt.Errorf("unexpected header %v, expecting %v", header, expectedHeader)
}
records, err := xcsv.Unmarshal[Record](csvReader)
if err != nil {
return fmt.Errorf("failed to unmarshal records: %w", err)
}
var errored bool
err = db.Tx(func(q *sqldb.Queries) error {
for _, record := range records {
user := sqldb.NewUser(record.Name, record.Email)
if err := q.AddUser(ctx, sqldb.AddUserParams{
Email: record.Email,
Code: user.Code,
Name: record.Name,
}); err != nil {
slog.Error(
"Failed to insert user",
"error", err,
"user.code", user.Code,
"user.name", record.Name,
"user.email", record.Email)
errored = true
}
}
return nil
})
if err != nil {
return fmt.Errorf("failed to add users: %w", err)
}
if errored {
return fmt.Errorf("failed to add some users")
}
return nil
}
func startServer(ctx context.Context, logger *slog.Logger) error {
db, err := openDB()
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
rootToken, err := os.ReadFile(rootTokenFile)
if err != nil {
return fmt.Errorf("failed to read root token file: %w", err)
}
handler := server.NewHandler(server.Args{
Database: db,
Logger: logger.With("component", "server"),
RootToken: strings.TrimSpace(string(rootToken)),
})
logger.Info("Starting server", "addr", addr)
return hserve.ListenAndServe(ctx, addr, handler)
}
func openDB() (*sqldb.Database, error) {
slog.Debug(
"Opening database",
"path", db)
return sqldb.Open(db)
}