henwen/internal/back/store.go

457 lines
10 KiB
Go
Raw Permalink Normal View History

2020-04-01 06:35:15 +00:00
package back
2020-03-24 14:59:27 +00:00
import (
"context"
2020-03-31 14:47:40 +00:00
"errors"
2020-10-04 22:03:16 +00:00
"fmt"
2020-03-31 14:47:40 +00:00
"log"
2020-03-24 14:59:27 +00:00
"os"
2020-03-31 14:47:40 +00:00
"crawshaw.io/sqlite"
2020-03-24 14:59:27 +00:00
"crawshaw.io/sqlite/sqlitex"
2021-03-04 04:22:09 +00:00
"github.com/matthewhartstonge/argon2"
2020-04-21 14:25:15 +00:00
"github.com/rickb777/date"
2020-03-24 14:59:27 +00:00
)
2020-09-28 03:40:55 +00:00
var ErrNotFound = errors.New("not found")
2020-10-04 22:03:16 +00:00
type UnauthorizedError struct {
EventID string
AdminCode string
}
func (u UnauthorizedError) Error() string {
return fmt.Sprintf("unauthorized: EventID = %s, AdminCode = %s", u.EventID, u.AdminCode)
}
2021-03-04 04:22:09 +00:00
func hash(password string) (string, error) {
hashed, err := (&argon2.Config{
HashLength: 32,
// We don't need a salt because our random passwords are not
// susceptible to dictionary attacks.
SaltLength: 0,
TimeCost: 3,
MemoryCost: 64 * 1024,
Parallelism: 4,
Mode: argon2.ModeArgon2id,
Version: argon2.Version13,
}).HashEncoded([]byte(password))
return string(hashed), err
}
2020-04-01 06:25:01 +00:00
type GenString func(length int) (string, error)
2020-03-24 14:59:27 +00:00
type Store struct {
pool *sqlitex.Pool
genString GenString
}
func NewStore(filename string, genString GenString) (*Store, error) {
var needCreate bool
2020-04-02 02:39:29 +00:00
if _, err := os.Stat(filename); os.IsNotExist(err) {
2020-03-24 14:59:27 +00:00
needCreate = true
}
// If the file exists, then assume it was created properly.
pool, err := sqlitex.Open(filename, 0, 10)
if err != nil {
return nil, err
}
store := &Store{
pool: pool,
genString: genString,
}
if needCreate {
2020-03-31 14:47:40 +00:00
log.Println("creating schema")
2020-03-24 14:59:27 +00:00
err = store.createSchema()
if err != nil {
defer pool.Close()
return nil, err
}
}
return store, nil
}
2020-04-16 20:49:28 +00:00
func NewMemoryStore(genString GenString) (*Store, error) {
pool, err := sqlitex.Open("file::memory:?mode=memory&cache=shared", 0, 10)
if err != nil {
return nil, err
}
store := &Store{
pool: pool,
genString: genString,
}
2020-09-27 21:44:04 +00:00
2020-04-16 20:49:28 +00:00
err = store.createSchema()
if err != nil {
defer pool.Close()
return nil, err
}
return store, nil
}
2020-03-24 14:59:27 +00:00
func (s *Store) Close() error {
return s.pool.Close()
}
const schema = `
CREATE TABLE event (
2020-09-29 15:25:21 +00:00
id TEXT NOT NULL PRIMARY KEY,
2021-03-04 04:22:09 +00:00
admin_code_hash TEXT NOT NULL,
2020-03-24 14:59:27 +00:00
name TEXT NOT NULL,
2020-04-01 04:36:41 +00:00
description TEXT NOT NULL,
2020-03-24 14:59:27 +00:00
earliest_date DATE NOT NULL,
2020-09-29 15:25:21 +00:00
latest_date DATE NOT NULL
2020-03-24 14:59:27 +00:00
);
CREATE TABLE response (
2020-10-04 22:21:57 +00:00
id TEXT NOT NULL,
2020-09-29 15:25:21 +00:00
event_id TEXT NOT NULL,
2020-09-27 21:44:04 +00:00
guest_name TEXT NOT NULL,
2020-03-24 14:59:27 +00:00
2020-10-04 22:21:57 +00:00
PRIMARY KEY (id, event_id),
2020-03-24 14:59:27 +00:00
FOREIGN KEY (event_id) REFERENCES event(id)
);
CREATE TABLE response_time (
2020-10-04 22:21:57 +00:00
event_id TEXT NOT NULL,
2020-09-29 15:25:21 +00:00
response_id TEXT NOT NULL,
2020-04-17 02:36:48 +00:00
date DATE NOT NULL,
2020-03-24 14:59:27 +00:00
time INTEGER NOT NULL,
2020-04-17 02:36:48 +00:00
CHECK (0 <= time < 24),
2020-10-04 22:21:57 +00:00
UNIQUE (response_id, date, time),
FOREIGN KEY(event_id, response_id) REFERENCES response(event_id, id)
2020-04-17 02:36:48 +00:00
);
CREATE TRIGGER enforce_valid_response_dates
BEFORE INSERT ON response_time
BEGIN
SELECT
CASE
2020-09-27 21:44:04 +00:00
WHEN NEW.date NOT BETWEEN event.earliest_date AND event.latest_date
2020-04-17 02:36:48 +00:00
THEN RAISE(ABORT, 'response date is out of range')
END
FROM response
JOIN event ON response.event_id = event.id
WHERE response.id = NEW.response_id;
END;`
2020-03-24 14:59:27 +00:00
func (s *Store) createSchema() error {
conn := s.pool.Get(context.Background())
defer s.pool.Put(conn)
return sqlitex.ExecScript(conn, schema)
}
type CreateEventCommand struct {
2020-04-21 14:25:15 +00:00
Name string
Description string
Earliest, Latest date.Date
2020-03-24 14:59:27 +00:00
}
type CreateEventResult struct {
2020-09-29 15:25:21 +00:00
EventID, AdminCode string
2020-03-24 14:59:27 +00:00
}
2020-04-01 06:10:55 +00:00
const dbDateLayout = "2006-01-02"
2020-04-01 04:36:41 +00:00
2020-03-24 14:59:27 +00:00
func (s *Store) CreateEvent(ctx context.Context, cmd CreateEventCommand) (result CreateEventResult, err error) {
2020-09-29 15:25:21 +00:00
const idLength = 10
2020-04-01 06:25:01 +00:00
const adminCodeLength = 10
2020-03-24 14:59:27 +00:00
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
2020-09-29 15:25:21 +00:00
id, err := s.genString(idLength)
2020-03-24 14:59:27 +00:00
if err != nil {
return
}
2020-04-01 06:25:01 +00:00
adminCode, err := s.genString(adminCodeLength)
2020-03-24 14:59:27 +00:00
if err != nil {
return
}
2021-03-04 04:22:09 +00:00
adminCodeHash, err := hash(adminCode)
if err != nil {
return
}
2020-03-24 14:59:27 +00:00
const query = `
2021-03-04 04:22:09 +00:00
INSERT INTO event(id, admin_code_hash, name, description, earliest_date, latest_date)
2020-04-01 04:40:06 +00:00
VALUES (?, ?, ?, ?, ?, ?);`
2020-03-24 14:59:27 +00:00
err = sqlitex.Exec(conn, query, nil,
2020-09-29 15:25:21 +00:00
id,
2021-03-04 04:22:09 +00:00
adminCodeHash,
2020-03-24 14:59:27 +00:00
cmd.Name,
2020-04-01 04:36:41 +00:00
cmd.Description,
2020-04-21 14:25:15 +00:00
cmd.Earliest.Format(dbDateLayout),
cmd.Latest.Format(dbDateLayout),
2020-03-24 14:59:27 +00:00
)
if err != nil {
return
}
2020-03-31 14:47:40 +00:00
result.AdminCode = adminCode
2020-09-29 15:25:21 +00:00
result.EventID = id
2020-03-24 14:59:27 +00:00
return
}
2020-03-31 14:47:40 +00:00
2020-10-04 22:03:16 +00:00
type CheckEventAdminCodeQuery struct {
EventID string
AdminCode string
}
func (s *Store) AuthorizeEventAdmin(ctx context.Context, query CheckEventAdminCodeQuery) error {
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
2021-03-04 04:22:09 +00:00
adminCodeHash, err := hash(query.AdminCode)
if err != nil {
return err
}
2020-10-04 22:03:16 +00:00
const dbQuery = `
SELECT 1
FROM event
2021-03-04 04:22:09 +00:00
WHERE id = ? AND admin_code_hash = ?;`
2020-10-04 22:03:16 +00:00
var doesMatch bool
2021-03-04 04:22:09 +00:00
err = sqlitex.Exec(conn, dbQuery,
2020-10-04 22:03:16 +00:00
func(stmt *sqlite.Stmt) error {
doesMatch = true
return nil
2021-03-04 04:22:09 +00:00
}, query.EventID, adminCodeHash)
2020-10-04 22:03:16 +00:00
if err != nil {
return err
}
if !doesMatch {
return UnauthorizedError{
EventID: query.EventID,
AdminCode: query.AdminCode,
}
}
return nil
}
2020-04-16 13:51:24 +00:00
type GetEventMetadataQuery struct {
2020-09-29 15:25:21 +00:00
EventID string
2020-03-31 14:47:40 +00:00
}
2020-04-16 13:51:24 +00:00
type GetEventMetadataResult struct {
2020-04-21 14:25:15 +00:00
Name string
Description string
Earliest, Latest date.Date
2020-03-31 14:47:40 +00:00
}
2020-04-16 13:51:24 +00:00
func (s *Store) GetEventMetadata(ctx context.Context, query GetEventMetadataQuery) (GetEventMetadataResult, error) {
2020-03-31 14:47:40 +00:00
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
const dbQuery = `
2020-04-01 04:40:06 +00:00
SELECT name, description, earliest_date, latest_date
2020-03-31 14:47:40 +00:00
FROM event
2020-09-29 15:25:21 +00:00
WHERE id = ?;`
2020-04-16 13:51:24 +00:00
var result GetEventMetadataResult
2020-03-31 14:47:40 +00:00
var found bool
err := sqlitex.Exec(conn, dbQuery,
func(stmt *sqlite.Stmt) error {
found = true
2020-04-01 04:36:41 +00:00
result.Name = stmt.ColumnText(0)
result.Description = stmt.ColumnText(1)
earliestDateString := stmt.ColumnText(2)
latestDateString := stmt.ColumnText(3)
var err error
2020-04-21 14:25:15 +00:00
result.Earliest, err = date.Parse(dbDateLayout, earliestDateString)
2020-04-01 04:36:41 +00:00
if err != nil {
return err
}
2020-04-21 14:25:15 +00:00
result.Latest, err = date.Parse(dbDateLayout, latestDateString)
2020-04-01 04:36:41 +00:00
return err
2020-09-29 15:25:21 +00:00
}, query.EventID)
2020-03-31 14:47:40 +00:00
if err != nil {
2020-04-16 13:51:24 +00:00
return GetEventMetadataResult{}, err
2020-03-31 14:47:40 +00:00
}
if !found {
2020-09-28 03:40:55 +00:00
return GetEventMetadataResult{}, ErrNotFound
2020-03-31 14:47:40 +00:00
}
2020-04-01 04:36:41 +00:00
return result, nil
2020-03-31 14:47:40 +00:00
}
2020-04-16 13:51:24 +00:00
2020-09-27 21:44:04 +00:00
type GetEventResponseSummaryQuery struct {
2020-09-29 15:25:21 +00:00
EventID string
2020-04-16 13:51:24 +00:00
}
2020-09-27 21:44:04 +00:00
type GetEventResponseSummaryResult struct {
2020-10-04 20:54:41 +00:00
RespondentNames []string
PerHourCounts map[date.Date]map[int]int
2020-04-16 13:51:24 +00:00
}
2020-09-27 21:44:04 +00:00
func (s *Store) GetEventResponseSummary(ctx context.Context, query GetEventResponseSummaryQuery) (GetEventResponseSummaryResult, error) {
2020-04-16 13:51:24 +00:00
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
2020-09-27 21:44:04 +00:00
var found bool
const eventIDQuery = `
2020-09-29 15:25:21 +00:00
SELECT 1
2020-09-27 21:44:04 +00:00
FROM event
2020-09-29 15:25:21 +00:00
WHERE id = ?`
2020-09-27 21:44:04 +00:00
var err = sqlitex.Exec(conn, eventIDQuery,
func(stmt *sqlite.Stmt) error {
found = true
return nil
2020-09-29 15:25:21 +00:00
}, query.EventID)
2020-09-27 21:44:04 +00:00
if err != nil {
return GetEventResponseSummaryResult{}, err
}
if !found {
2020-09-28 03:40:55 +00:00
return GetEventResponseSummaryResult{}, ErrNotFound
2020-09-27 21:44:04 +00:00
}
var result GetEventResponseSummaryResult
2020-10-04 20:54:41 +00:00
const respondentNameQuery = `
SELECT guest_name
2020-04-16 13:51:24 +00:00
FROM response
2020-10-04 20:54:41 +00:00
WHERE event_id = ?
ORDER BY guest_name ASC;`
err = sqlitex.Exec(conn, respondentNameQuery,
2020-04-16 13:51:24 +00:00
func(stmt *sqlite.Stmt) error {
2020-10-04 20:54:41 +00:00
result.RespondentNames = append(result.RespondentNames, stmt.ColumnText(0))
2020-04-16 13:51:24 +00:00
return nil
2020-09-29 15:25:21 +00:00
}, query.EventID)
2020-09-27 21:44:04 +00:00
if err != nil {
return GetEventResponseSummaryResult{}, err
}
2020-10-04 20:24:04 +00:00
result.PerHourCounts = make(map[date.Date]map[int]int)
const perHourCountQuery = `
SELECT date, time, COUNT(*)
2020-10-04 22:21:57 +00:00
FROM response_time
2020-10-04 20:24:04 +00:00
WHERE event_id = ?
GROUP BY date, time;`
err = sqlitex.Exec(conn, perHourCountQuery,
func(stmt *sqlite.Stmt) error {
d, err := date.Parse(dbDateLayout, stmt.ColumnText(0))
if err != nil {
return err
}
if result.PerHourCounts[d] == nil {
result.PerHourCounts[d] = make(map[int]int)
}
result.PerHourCounts[d][stmt.ColumnInt(1)] = stmt.ColumnInt(2)
return nil
}, query.EventID)
if err != nil {
return GetEventResponseSummaryResult{}, err
}
2020-09-27 21:44:04 +00:00
return result, nil
2020-04-16 13:51:24 +00:00
}
2020-04-17 02:36:48 +00:00
type CreateEventResponseCommand struct {
2020-09-29 15:25:21 +00:00
EventID string
GuestName string
DateHours map[date.Date]map[int]struct{}
2020-04-17 02:36:48 +00:00
}
type CreateEventResponseResult struct {
2020-09-29 15:25:21 +00:00
ResponseID string
2020-04-17 02:36:48 +00:00
}
func (s *Store) CreateEventResponse(ctx context.Context, cmd CreateEventResponseCommand) (result CreateEventResponseResult, err error) {
2020-09-29 15:25:21 +00:00
const responseIDLength = 10
2020-04-17 02:36:48 +00:00
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
defer sqlitex.Save(conn)(&err)
2020-09-29 15:25:21 +00:00
responseID, err := s.genString(responseIDLength)
2020-04-17 02:36:48 +00:00
if err != nil {
2020-09-27 21:44:04 +00:00
return
2020-04-17 02:36:48 +00:00
}
2020-10-04 22:21:57 +00:00
const responseQuery = `
INSERT INTO response(event_id, id, guest_name)
VALUES (?, ?, ?);`
2020-09-29 15:25:21 +00:00
err = sqlitex.Exec(conn, responseQuery, nil, cmd.EventID, responseID, cmd.GuestName)
2020-04-17 02:36:48 +00:00
if err != nil {
2020-09-27 21:44:04 +00:00
return
}
2020-10-04 22:21:57 +00:00
const responseTimeQuery = `
INSERT INTO response_time(event_id, response_id, date, time)
VALUES (?, ?, ?, ?);`
2020-09-27 21:44:04 +00:00
for d, hs := range cmd.DateHours {
for h := range hs {
2020-10-04 22:21:57 +00:00
err = sqlitex.Exec(conn, responseTimeQuery, nil,
cmd.EventID, responseID, d.Format(dbDateLayout), h)
2020-09-27 21:44:04 +00:00
if err != nil {
return
}
}
2020-04-17 02:36:48 +00:00
}
return CreateEventResponseResult{
2020-09-29 15:25:21 +00:00
ResponseID: responseID,
2020-04-17 02:36:48 +00:00
}, nil
}
2020-09-27 21:44:04 +00:00
type GetEventResponseQuery struct {
2020-09-29 15:25:21 +00:00
EventID string
ResponseID string
2020-09-27 21:44:04 +00:00
}
type GetEventResponseResult struct {
GuestName string
DateHours map[date.Date]map[int]struct{}
}
func (s *Store) GetEventResponse(ctx context.Context, query GetEventResponseQuery) (GetEventResponseResult, error) {
conn := s.pool.Get(ctx)
defer s.pool.Put(conn)
var found bool
var result GetEventResponseResult
const responseQuery = `
2020-09-29 15:25:21 +00:00
SELECT guest_name
2020-09-27 21:44:04 +00:00
FROM response
2020-09-29 15:25:21 +00:00
WHERE id = ? AND event_id = ?;`
2020-09-27 21:44:04 +00:00
var err = sqlitex.Exec(conn, responseQuery,
func(stmt *sqlite.Stmt) error {
found = true
result.GuestName = stmt.ColumnText(0)
return nil
2020-09-29 15:25:21 +00:00
}, query.ResponseID, query.EventID)
2020-09-27 21:44:04 +00:00
if err != nil {
return GetEventResponseResult{}, err
}
if !found {
2020-09-28 03:40:55 +00:00
return GetEventResponseResult{}, ErrNotFound
2020-09-27 21:44:04 +00:00
}
result.DateHours = make(map[date.Date]map[int]struct{})
const responseTimeQuery = `
SELECT date, time
FROM response_time
2020-10-04 22:21:57 +00:00
WHERE event_id = ? AND response_id = ?`
2020-09-27 21:44:04 +00:00
err = sqlitex.Exec(conn, responseTimeQuery,
func(stmt *sqlite.Stmt) error {
d, err := date.Parse(dbDateLayout, stmt.ColumnText(0))
if err != nil {
return err
}
if result.DateHours[d] == nil {
result.DateHours[d] = make(map[int]struct{})
}
result.DateHours[d][stmt.ColumnInt(1)] = struct{}{}
return nil
2020-10-04 22:21:57 +00:00
}, query.EventID, query.ResponseID)
2020-09-27 21:44:04 +00:00
if err != nil {
return GetEventResponseResult{}, err
}
return result, nil
}