summaryrefslogtreecommitdiff
path: root/stats/enrich.go
blob: 40e91eca30efa1d1f0cdd2dd5a7eefd45d1e534c (plain)
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
package stats

import (
	"sts2stats/model"
	"sts2stats/spool"
	"sts2stats/storage"
	"sync"
	"time"
)

type LoadFunc = func() error

// Enricher reads data from the RunSave and fills dictionaries and data structures
type Enricher interface {
	Enrich(run model.Run, stat RunStat) ([]any, error)
}

type EnrichFunc func(run model.Run, stat RunStat) ([]any, error)

type EnrichFuncWrapper struct {
	f EnrichFunc
}

func EnrichWrap(f EnrichFunc) Enricher {
	return EnrichFuncWrapper{f: f}
}

func (e EnrichFuncWrapper) Enrich(run model.Run, stat RunStat) ([]any, error) {
	return e.f(run, stat)
}

var Enrichers = map[string]Enricher{
	"act":            EnrichWrap(EnrichActs),
	"version":        EnrichWrap(EnrichGameVersion),
	"ancient choice": EnrichWrap(EnrichAncients),
	"card choice":    EnrichWrap(EnrichCardChoice),
}

func Enrich(run model.Run) error {
	startTime := time.Now()
	id := run.RunId[:4]
	wg := sync.WaitGroup{}
	st := NewRunStat(run)
	for k, e := range Enrichers {
		wg.Go(func() {
			spool.Debug("[%v] Starting %v enrichment\n", id, k)
			res, err := e.Enrich(run, st)
			if err != nil {
				spool.Panic("%v\n", err)
			}

			if len(res) == 0 {
				spool.Debug("[%v] Finished %v enrichment\n", id, k)
				return
			}

			spool.Debug("[%v] Collected %v entities (%v)\n", id, k, len(res))
			err = storage.SaveNow(res...)
			if err != nil {
				spool.Panic("during %v: %v\n", k, err)
			}
			spool.Debug("[%v] Saved %v entities (%v)\n", id, k, len(res))
		})
	}
	wg.Wait()

	endTime := time.Now()
	spool.Info("[%v] digested run\n", id)
	spool.Debug("[%v] took %.2fs", endTime.Sub(startTime).Seconds())
	return nil
}