summaryrefslogtreecommitdiff
path: root/src/hub/src/spreadspace.org/sfive/s5store.go
blob: 9d3d57e3542a29ccecec7b2aa20cb3585805d8b8 (plain) (blame)
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
package sfive

import (
	"database/sql"
	"log"
	"os"
	"time"

	_ "github.com/mattn/go-sqlite3"

	"github.com/coopernurse/gorp"
)

// compared to JSON DTOs, DB types are flattened, and use key-relations instead of collections
// this is very much not normalized at all, because I'm too lazy to type

const (
	TagsTn              = "Tags"
	SourceTagsTn        = "StreamToTagMap"
	SourcesTn           = "Sources"
	ClientDataUpdatesTn = "ClientDataUpdates"
	DataUpdatesTn       = "DataUpdates"
)

// stored in TagsTn
type tagDb struct {
	Id   int
	Name string
}

func tagsFromStatisticsData(value StatisticsData) []tagDb {
	tags := make([]tagDb, len(value.SourceId.Tags))
	for i := range value.SourceId.Tags {
		tags[i] = tagDb{Id: -1, Name: value.SourceId.Tags[i]}
	}
	return tags
}

// stored in SourceTagsTn
// Stream m:n Tag
type sourceTagsDb struct {
	TagId    int // foreign key to TagsTn
	SourceId int // foreign key to SourcesTn
}

// stored in SourcesTn
type sourceDb struct {
	Id int
	StreamId
	SourceId
}

func sourceFromStatisticsData(value StatisticsData) sourceDb {
	return sourceDb{
		-1,
		StreamId{
			ContentId: value.SourceId.StreamId.ContentId,
			Format:    value.SourceId.StreamId.Format,
			Quality:   value.SourceId.StreamId.Quality,
		},
		SourceId{
			Hostname: value.SourceId.Hostname},
	}
}

// stored in ClientDataUpdatesTn
// ClientData n:1 DataUpdate
type clientDataDb struct {
	Id            int
	DataUpdatesId int // foreign key to DataUpdatesTn
	ClientData
}

func clientsFromStatisticsData(value StatisticsData) []clientDataDb {
	res := make([]clientDataDb, len(value.Data.Clients))
	for i := range value.Data.Clients {
		res[i] = clientDataDb{-1, -1, value.Data.Clients[i]}
	}
	return res
}

// stored in DataUpdatesTn
// in DB, StatisticsData/DataUpdate is flattened compared to JSON DTOs
type dataUpdateDb struct {
	Id            int
	SourceId      int // foreign key to SourcesTn
	StartTime     time.Time
	Duration      time.Duration
	ClientCount   uint
	BytesReceived uint
	BytesSent     uint
}

func dataUpdateFromStatisticsData(value StatisticsData) dataUpdateDb {
	return dataUpdateDb{
		-1,
		-1,
		value.StartTime,
		value.Duration,
		value.Data.ClientCount,
		value.Data.BytesReceived,
		value.Data.BytesSent}
}

func updateFromStatisticsData(value StatisticsData) (dataUpdateDb, []clientDataDb, sourceDb, []tagDb) {
	du := dataUpdateFromStatisticsData(value)
	cd := clientsFromStatisticsData(value)
	src := sourceFromStatisticsData(value)
	tags := tagsFromStatisticsData(value)

	return du, cd, src, tags
}

func initDb() *gorp.DbMap {
	// connect to db using standard Go database/sql API
	db, err := sql.Open("sqlite3", "/home/gimpf/test.sqlite")
	checkErr(err, "sql.Open failed")

	dbmap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}

	dbmap.AddTableWithName(tagDb{}, TagsTn).SetKeys(true, "Id").ColMap("Name").SetUnique(true)
	dbmap.AddTableWithName(sourceTagsDb{}, SourceTagsTn).SetKeys(false, "TagId", "SourceId")
	dbmap.AddTableWithName(sourceDb{}, SourcesTn).SetKeys(true, "Id")
	dbmap.AddTableWithName(clientDataDb{}, ClientDataUpdatesTn).SetKeys(true, "Id")
	dbmap.AddTableWithName(dataUpdateDb{}, DataUpdatesTn).SetKeys(true, "Id")

	// TODO use some real migration, yadda yadda
	err = dbmap.CreateTablesIfNotExists()
	checkErr(err, "Create tables failed")

	return dbmap
}

func checkErr(err error, msg string) {
	if err != nil {
		log.Fatalln(msg, err)
	}
}

type StatsFilter struct {
	start     *time.Time
	end       *time.Time
	hostname  *string
	contentId *string
	format    *string
	quality   *string
	tagsAny   []string
}

type Closer interface {
	Close()
}

type StatsContainer interface {
	Append(update StatisticsData) error
	CountUpdateEntries() (int64, error)
	GetTags() ([]string, error)
	ClientCount(filter *StatsFilter) uint
	AverageBps(filter *StatsFilter) (uint, error)
	Locations(filter *StatsFilter) map[string]int
}

type sqliteStore struct {
	db *gorp.DbMap
}

func (s sqliteStore) Append(update StatisticsData) (err error) {
	du, cd, src, tags := updateFromStatisticsData(update)

	s.db.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
	tx, err := s.db.Begin()
	if err != nil {
		//fmt.Printf("tx\n")
		return
	}

	for i := range tags {
		err = s.db.Insert(&tags[i])
		if err != nil {
			//fmt.Printf("tags\n")
			return
		}
	}

	err = s.db.Insert(&src)
	if err != nil {
		//fmt.Printf("src\n")
		return
	}

	st := make([]sourceTagsDb, len(tags))
	for i := range tags {
		st[i].TagId = tags[i].Id
		st[i].SourceId = src.Id
	}
	for i := range st {
		err = s.db.Insert(&st[i])
		if err != nil {
			//fmt.Printf("st\n")
			return
		}
	}

	du.SourceId = src.Id
	err = s.db.Insert(&du)
	if err != nil {
		//fmt.Printf("du\n")
		return
	}

	for i := range cd {
		cd[i].DataUpdatesId = du.Id
		err = s.db.Insert(&cd)
		if err != nil {
			return
		}

	}
	return tx.Commit()
}

func (s sqliteStore) CountUpdateEntries() (count int64, err error) {
	count, err = s.db.SelectInt("select count(*) from " + DataUpdatesTn)
	return
}

func (s sqliteStore) GetTags() ([]string, error) {
	res, dbErr := s.db.Select("", "select Name from "+TagsTn)
	if dbErr == nil {
		sRes := ToString(res)
		return sRes, nil
	}
	return nil, dbErr
}

func ToString(value []interface{}) []string {
	res := make([]string, len(value))
	for i := range value {
		res[i] = value[i].(string)
	}
	return res
}

func (s sqliteStore) ClientCount(filter *StatsFilter) uint {
	count, _ := s.db.SelectInt(
		"select count(distict (Ip, UserAgent)) from " + ClientDataUpdatesTn)
	return uint(count)
}

type bpsQueryResult struct {
	BytesReceived uint
	BytesSent     uint
	StartTime     time.Time
	LastStartTime time.Time
	LastDuration  time.Duration
}

func (s sqliteStore) AverageBps(filter *StatsFilter) (uint, error) {
	res := bpsQueryResult{}
	err := s.db.SelectOne(res, "select (sum(BytesSent) as BytesSent, sum(BytesReceived) as BytesReceived, min(StartTime) as StartTime, max(StartTime) as LastStartTime) from "+DataUpdatesTn)
	if err == nil {
		bps := (res.BytesSent + res.BytesReceived) / uint(res.StartTime.Sub(res.LastStartTime).Seconds())
		return bps, nil
	}
	return 0, err
}

func (s sqliteStore) Locations(filter *StatsFilter) map[string]int {
	return nil
	// TODO
}

func NewStore() (store StatsContainer, err error) {
	db := initDb()
	if db == nil {
		return
	}
	res := sqliteStore{db}
	store = res
	return
}

func EatDataAndClose(sc StatsContainer) {
	s := sc.(sqliteStore)
	//	if s == nil {
	//		return
	//	}
	s.db.TruncateTables()
	s.Close()
}

func (s *sqliteStore) Close() {
	s.db.Db.Close()
}