init
This commit is contained in:
13 files changed
+1700
No files matched your search
@@ -0,0 +1,219 @@
|
||||
// Package scores persists pilots, every completed run, and their personal bests.
|
||||
package scores
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"go.etcd.io/bbolt"
|
||||
|
||||
"thermal-snake/internal/game"
|
||||
)
|
||||
|
||||
var (
|
||||
pilotsKey = []byte("pilots")
|
||||
runsKey = []byte("runs")
|
||||
recordedKey = []byte("recorded")
|
||||
)
|
||||
|
||||
type Store struct{ db *bbolt.DB }
|
||||
|
||||
type Pilot struct {
|
||||
Callsign string
|
||||
Best *Run
|
||||
Total int
|
||||
}
|
||||
|
||||
type Run struct {
|
||||
ID string
|
||||
Score int
|
||||
Heat int
|
||||
Outcome game.Outcome
|
||||
Finished time.Time
|
||||
Order uint64
|
||||
}
|
||||
|
||||
type Standing struct {
|
||||
Rank int
|
||||
Pilot
|
||||
}
|
||||
|
||||
func Open(path string) (*Store, error) {
|
||||
db, err := bbolt.Open(path, 0600, &bbolt.Options{Timeout: time.Second})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = db.Update(func(tx *bbolt.Tx) error {
|
||||
for _, name := range [][]byte{pilotsKey, runsKey, recordedKey} {
|
||||
if _, err := tx.CreateBucketIfNotExists(name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
_ = db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// Register assigns a unique display name to a verified public key fingerprint.
|
||||
func (s *Store) Register(fingerprint string) (Pilot, error) {
|
||||
var pilot Pilot
|
||||
err := s.db.Update(func(tx *bbolt.Tx) error {
|
||||
pilots := tx.Bucket(pilotsKey)
|
||||
key := []byte(fingerprint)
|
||||
if raw := pilots.Get(key); raw != nil {
|
||||
return json.Unmarshal(raw, &pilot)
|
||||
}
|
||||
number, err := pilots.NextSequence()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pilot.Callsign = fmt.Sprintf("PILOT-%04d", number)
|
||||
return put(pilots, key, pilot)
|
||||
})
|
||||
return pilot, err
|
||||
}
|
||||
|
||||
func (s *Store) Profile(fingerprint string) (Pilot, error) {
|
||||
var pilot Pilot
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
var err error
|
||||
pilot, err = readPilot(tx.Bucket(pilotsKey), []byte(fingerprint))
|
||||
return err
|
||||
})
|
||||
return pilot, err
|
||||
}
|
||||
|
||||
// Record writes the run, its history entry, and any new best in one transaction.
|
||||
// Retrying the same ID is safe even when several sessions share a pilot.
|
||||
func (s *Store) Record(fingerprint string, run Run) (Pilot, bool, error) {
|
||||
var pilot Pilot
|
||||
var personalBest bool
|
||||
err := s.db.Update(func(tx *bbolt.Tx) error {
|
||||
pilots := tx.Bucket(pilotsKey)
|
||||
key := []byte(fingerprint)
|
||||
var err error
|
||||
pilot, err = readPilot(pilots, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
allRuns := tx.Bucket(runsKey)
|
||||
recorded := tx.Bucket(recordedKey)
|
||||
id := []byte(fingerprint + "/" + run.ID)
|
||||
if recorded.Get(id) != nil {
|
||||
personalBest = pilot.Best != nil && pilot.Best.ID == run.ID
|
||||
return nil
|
||||
}
|
||||
|
||||
run.Order, err = allRuns.NextSequence()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
history, err := allRuns.CreateBucketIfNotExists(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
order := binary.BigEndian.AppendUint64(nil, run.Order)
|
||||
if err := put(history, order, run); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := recorded.Put(id, order); err != nil {
|
||||
return err
|
||||
}
|
||||
pilot.Total++
|
||||
personalBest = pilot.Best == nil || run.Score > pilot.Best.Score
|
||||
if personalBest {
|
||||
pilot.Best = &run
|
||||
}
|
||||
return put(pilots, key, pilot)
|
||||
})
|
||||
return pilot, personalBest, err
|
||||
}
|
||||
|
||||
func (s *Store) Leaderboard() ([]Standing, error) {
|
||||
var standings []Standing
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
return tx.Bucket(pilotsKey).ForEach(func(_, raw []byte) error {
|
||||
var pilot Pilot
|
||||
if err := json.Unmarshal(raw, &pilot); err != nil {
|
||||
return err
|
||||
}
|
||||
if pilot.Best != nil {
|
||||
standings = append(standings, Standing{Pilot: pilot})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(standings, func(i, j int) bool {
|
||||
left, right := standings[i].Best, standings[j].Best
|
||||
if left.Score != right.Score {
|
||||
return left.Score > right.Score
|
||||
}
|
||||
return left.Order < right.Order
|
||||
})
|
||||
for i := range standings {
|
||||
standings[i].Rank = i + 1
|
||||
}
|
||||
return standings, nil
|
||||
}
|
||||
|
||||
func (s *Store) History(fingerprint string, offset, limit int) ([]Run, int, error) {
|
||||
var runs []Run
|
||||
var total int
|
||||
err := s.db.View(func(tx *bbolt.Tx) error {
|
||||
key := []byte(fingerprint)
|
||||
pilot, err := readPilot(tx.Bucket(pilotsKey), key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total = pilot.Total
|
||||
if offset >= total || limit <= 0 {
|
||||
return nil
|
||||
}
|
||||
history := tx.Bucket(runsKey).Bucket(key)
|
||||
cursor := history.Cursor()
|
||||
k, v := cursor.Last()
|
||||
for range offset {
|
||||
k, v = cursor.Prev()
|
||||
}
|
||||
for k != nil && len(runs) < limit {
|
||||
var run Run
|
||||
if err := json.Unmarshal(v, &run); err != nil {
|
||||
return err
|
||||
}
|
||||
runs = append(runs, run)
|
||||
k, v = cursor.Prev()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return runs, total, err
|
||||
}
|
||||
|
||||
func readPilot(bucket *bbolt.Bucket, key []byte) (Pilot, error) {
|
||||
var pilot Pilot
|
||||
raw := bucket.Get(key)
|
||||
if raw == nil {
|
||||
return pilot, fmt.Errorf("pilot is not registered")
|
||||
}
|
||||
err := json.Unmarshal(raw, &pilot)
|
||||
return pilot, err
|
||||
}
|
||||
|
||||
func put(bucket *bbolt.Bucket, key []byte, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bucket.Put(key, raw)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package scores
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"thermal-snake/internal/game"
|
||||
)
|
||||
|
||||
func TestRunHistoryAndRankingAcrossReopen(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "scores.db")
|
||||
store, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if store != nil {
|
||||
_ = store.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
alice, err := store.Register("key-A")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bob, err := store.Register("key-B")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if alice.Callsign == bob.Callsign {
|
||||
t.Fatal("distinct keys share a callsign")
|
||||
}
|
||||
|
||||
record := func(key, id string, score int, wantBest bool) {
|
||||
t.Helper()
|
||||
_, best, err := store.Record(key, Run{ID: id, Score: score, Outcome: game.Wall})
|
||||
if err != nil || best != wantBest {
|
||||
t.Fatalf("record %s got best=%v, err=%v", id, best, err)
|
||||
}
|
||||
}
|
||||
|
||||
record("key-B", "bob-first", 100, true)
|
||||
record("key-A", "alice-first", 100, true)
|
||||
record("key-A", "alice-low", 0, false)
|
||||
record("key-A", "alice-equal", 100, false)
|
||||
record("key-A", "alice-low", 0, false) // Retry with the same ID.
|
||||
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := store.Register("key-A")
|
||||
if err != nil || again.Callsign != alice.Callsign || again.Total != 3 || again.Best == nil || again.Best.ID != "alice-first" {
|
||||
t.Fatalf("reopened profile: %+v, %v", again, err)
|
||||
}
|
||||
|
||||
standings, err := store.Leaderboard()
|
||||
if err != nil || len(standings) != 2 {
|
||||
t.Fatalf("reopened standings: %+v, %v", standings, err)
|
||||
}
|
||||
if standings[0].Callsign != bob.Callsign || standings[0].Rank != 1 ||
|
||||
standings[1].Callsign != alice.Callsign || standings[1].Rank != 2 {
|
||||
t.Fatalf("equal scores ranked out of recording order: %+v", standings)
|
||||
}
|
||||
|
||||
history, total, err := store.History("key-A", 1, 1)
|
||||
if err != nil || total != 3 || len(history) != 1 || history[0].ID != "alice-low" || history[0].Score != 0 {
|
||||
t.Fatalf("reopened history: %+v, total %d, %v", history, total, err)
|
||||
}
|
||||
record("key-A", "alice-high", 200, true)
|
||||
standings, err = store.Leaderboard()
|
||||
if err != nil || len(standings) != 2 || standings[0].Callsign != alice.Callsign {
|
||||
t.Fatalf("new best should take first place: %+v, %v", standings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentSessionsShareAProfile(t *testing.T) {
|
||||
store, err := Open(filepath.Join(t.TempDir(), "scores.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
const sessions = 18
|
||||
var wg sync.WaitGroup
|
||||
for i := range sessions {
|
||||
wg.Go(func() {
|
||||
if _, err := store.Register("same-key"); err != nil {
|
||||
t.Errorf("register: %v", err)
|
||||
return
|
||||
}
|
||||
if _, _, err := store.Record("same-key", Run{ID: fmt.Sprint(i), Score: i * 100}); err != nil {
|
||||
t.Errorf("record: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
runs, total, err := store.History("same-key", 0, sessions)
|
||||
if err != nil || len(runs) != sessions || total != sessions {
|
||||
t.Fatalf("history has %d of %d runs: %v", len(runs), total, err)
|
||||
}
|
||||
pilot, err := store.Profile("same-key")
|
||||
if err != nil || pilot.Best == nil || pilot.Best.Score != (sessions-1)*100 {
|
||||
t.Fatalf("unexpected personal best: %+v, %v", pilot, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user