/
data_models.go
406 lines (355 loc) · 10 KB
/
data_models.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package data_models
import (
"database/sql"
"fmt"
"sort"
"sync"
"time"
"github.com/lib/pq"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/volatiletech/null/v8"
"github.com/Bnei-Baruch/feed-api/consts"
"github.com/Bnei-Baruch/feed-api/mdb"
"github.com/Bnei-Baruch/feed-api/utils"
"github.com/Bnei-Baruch/sqlboiler/queries"
)
const (
LANGUAGES_CONTENT_UNITS_SQL = `
select
f.language,
array_agg(distinct cu.uid)
from
content_units as cu,
files as f
where
f.content_unit_id = cu.id and
f.mime_type in ('video/mp4', 'audio/mpeg')
group by
f.language;`
TAGS_CONTENT_UNITS_SQL = `
select
t.uid,
array_agg(distinct cu.uid)
from
content_units as cu,
tags as t,
content_units_tags as cut
where
cut.content_unit_id = cu.id and
t.id = cut.tag_id
group by
t.uid;`
SOURCES_CONTENT_UNITS_SQL = `
select
s.uid,
array_agg(distinct cu.uid)
from
content_units as cu,
sources as s,
content_units_sources as cus
where
cus.content_unit_id = cu.id and
s.id = cus.source_id
group by
s.uid;`
PERSONS_CONTENT_UNITS_SQL = `
select
p.uid,
array_agg(distinct cu.uid)
from
content_units as cu,
content_units_persons as cup,
persons as p
where
p.id = cup.person_id and
cup.content_unit_id = cu.id
group by
p.uid;`
RAV_PERSON_UID = "abcdefgh"
COLLECTIONS_CONTENT_UNITS_SQL = `
select
c.uid,
array_agg(distinct cu.uid)
from
content_units as cu,
collections_content_units as ccu,
collections as c
where
c.id = ccu.collection_id and
ccu.content_unit_id = cu.id
group by
c.uid;`
CONTENT_UNITS_COLLECTIONS_SQL = `
select
cu.uid,
array_agg(distinct c.uid)
from
content_units as cu,
collections_content_units as ccu,
collections as c
where
c.id = ccu.collection_id and
ccu.content_unit_id = cu.id
group by
cu.uid;`
CONTENT_UNITS_INFO_SQL = `
select
cu.type_id,
cu.uid as uid,
coalesce(cu.properties->>'film_date', cu.properties->>'start_date', cu.created_at::text)::date as date,
cu.created_at as created_at,
cu.secure = 0 AND cu.published IS TRUE as secure_and_published,
cu.type_id = %d and (cu.properties->>'part')::int = 0 and (cu.properties->>'duration')::int < 1200,
(cu.properties->>'duration')::int
from
content_units as cu;`
COLLECTIONS_INFO_SQL = `
select
c.type_id,
c.uid as uid,
coalesce(c.properties->>'start_date', c.created_at::text)::date as date,
c.created_at as created_at,
c.properties->>'source'
from
collections as c;`
CONTENT_UNITS_WATCH_DURATION_SQL = `
select
a.data->>'unit_uid' as event_unit_uid,
case when
cast(b.data->>'current_time' as float) > cast(a.data->>'current_time' as float) then
cast(b.data->>'current_time' as float) - cast(a.data->>'current_time' as float)
else 0 end as current_duration_seconds
from entries a
left join entries b on (a.client_event_id=b.client_flow_id and b.client_event_type='player-stop')
where
cast(a.created_at as date) >= '2021-04-01'
and a.client_event_type='player-play'
order by a.created_at;`
)
type ContentUnitInfo struct {
TypeId int64
Uid string
Date time.Time
CreatedAt time.Time
SecureAndPublished bool
IsLessonPrep bool
Duration time.Duration
}
func ScanContentUnitInfo(rows *sql.Rows, datas map[string]interface{}) error {
cu := ContentUnitInfo{}
var isLessonPrep null.Bool
var duration null.Int64
if err := rows.Scan(&cu.TypeId, &cu.Uid, &cu.Date, &cu.CreatedAt, &cu.SecureAndPublished, &isLessonPrep, &duration); err != nil {
return err
} else {
cu.IsLessonPrep = isLessonPrep.Valid && isLessonPrep.Bool
cu.Duration = time.Duration(duration.Int64) * time.Second
datas[cu.Uid] = &cu
return nil
}
}
type CollectionInfo struct {
TypeId int64
Uid string
Date time.Time
CreatedAt time.Time
SourceUid string
}
func ScanCollectionInfo(rows *sql.Rows, datas map[string]interface{}) error {
c := CollectionInfo{}
var sourceUid null.String
if err := rows.Scan(&c.TypeId, &c.Uid, &c.Date, &c.CreatedAt, &sourceUid); err != nil {
return err
} else {
c.SourceUid = sourceUid.String
datas[c.Uid] = &c
return nil
}
}
type RefreshModel interface {
Name() string
Refresh() error
Interval() time.Duration
}
type DataModels struct {
ticker *time.Ticker
nextRefresh map[string]time.Time
LanguagesContentUnitsFilter *MDBFilterModel
TagsContentUnitsFilter *MDBFilterModel
SourcesContentUnitsFilter *MDBFilterModel
PersonsContentUnitsFilter *MDBFilterModel
CollectionsContentUnitsFilter *MDBFilterModel
ContentUnitsCollectionsFilter *MDBFilterModel
ContentUnitsInfo *MDBDataModel
//ContentUnitsPopularity *MDBDataModel
CollectionsInfo *MDBDataModel
models []RefreshModel
}
func MakeDataModels(db *sql.DB) *DataModels {
lcuf := MakeMDBFilterModel(db, "LanguagesContentUnitsFilter", time.Duration(time.Minute*10), LANGUAGES_CONTENT_UNITS_SQL)
tcuf := MakeMDBFilterModel(db, "TagsContentUnitsFilter", time.Duration(time.Minute*10), TAGS_CONTENT_UNITS_SQL)
scuf := MakeMDBFilterModel(db, "SourcesContentUnitsFilter", time.Duration(time.Minute*10), SOURCES_CONTENT_UNITS_SQL)
pcuf := MakeMDBFilterModel(db, "PersonsContentUnitsFilter", time.Duration(time.Minute*10), PERSONS_CONTENT_UNITS_SQL)
ccuf := MakeMDBFilterModel(db, "CollectionsContentUnitsFilter", time.Duration(time.Minute*10), COLLECTIONS_CONTENT_UNITS_SQL)
cucf := MakeMDBFilterModel(db, "ContentUnitsCollectionsFilter", time.Duration(time.Minute*10), CONTENT_UNITS_COLLECTIONS_SQL)
cui := MakeMDBDataModel(db, "ContentUnitsInfo", time.Duration(time.Minute*10), fmt.Sprintf(CONTENT_UNITS_INFO_SQL, mdb.CONTENT_TYPE_REGISTRY.ByName[consts.CT_LESSON_PART].ID), ScanContentUnitInfo)
ci := MakeMDBDataModel(db, "CollectionsInfo", time.Duration(time.Minute*10), COLLECTIONS_INFO_SQL, ScanCollectionInfo)
models := []RefreshModel{lcuf, tcuf, scuf, pcuf, ccuf, cucf, cui, ci}
dataModels := &DataModels{
ticker: time.NewTicker(time.Second),
nextRefresh: make(map[string]time.Time),
LanguagesContentUnitsFilter: lcuf,
TagsContentUnitsFilter: tcuf,
SourcesContentUnitsFilter: scuf,
PersonsContentUnitsFilter: pcuf,
CollectionsContentUnitsFilter: ccuf,
ContentUnitsCollectionsFilter: cucf,
ContentUnitsInfo: cui,
CollectionsInfo: ci,
models: models,
}
go func() {
refresh := func() {
if err := dataModels.Refresh(); err != nil {
log.Errorf("Error Refresh: %s", err.Error())
}
}
refresh()
for range dataModels.ticker.C {
refresh()
}
}()
return dataModels
}
func (dataModels *DataModels) Refresh() error {
refreshModel := func(model RefreshModel) error {
start := time.Now()
err := model.Refresh()
end := time.Now()
log.Infof("Refreshed %s in %s", model.Name(), end.Sub(start))
if err != nil {
return errors.Wrap(err, model.Name())
}
return err
}
for _, dataModel := range dataModels.models {
if when, ok := dataModels.nextRefresh[dataModel.Name()]; !ok || when.Before(time.Now()) {
if err := refreshModel(dataModel); err != nil {
return err
}
dataModels.nextRefresh[dataModel.Name()] = time.Now().Add(dataModel.Interval())
}
}
return nil
}
// --- Data Models --- //
// --- MDB Filter Model --- //
type MDBFilterModel struct {
db *sql.DB
name string
interval time.Duration
sql string
Values map[string][]string
valuesMutex sync.RWMutex
}
func MakeMDBFilterModel(db *sql.DB, name string, interval time.Duration, sql string) *MDBFilterModel {
return &MDBFilterModel{db, name, interval, sql, make(map[string][]string), sync.RWMutex{}}
}
func (model *MDBFilterModel) Name() string {
return model.name
}
func (model *MDBFilterModel) Interval() time.Duration {
return model.interval
}
func (model *MDBFilterModel) Refresh() error {
rows, err := queries.Raw(model.db, model.sql).Query()
if err != nil {
return err
}
defer rows.Close()
tmp := make(map[string][]string)
for rows.Next() {
var key null.String
uids := []string(nil)
if err := rows.Scan(&key, pq.Array(&uids)); err != nil {
return err
}
sort.Strings(uids)
// We ignore key.Valid as we want to use in non valid state the default empty string.
tmp[key.String] = uids
}
model.valuesMutex.Lock()
defer model.valuesMutex.Unlock()
for k, v := range tmp {
model.Values[k] = v
}
return nil
}
func (model *MDBFilterModel) FilterValues(keys []string) []string {
model.valuesMutex.RLock()
defer model.valuesMutex.RUnlock()
ret := []string(nil)
for _, key := range keys {
if ret == nil {
ret = model.Values[key]
} else {
ret = utils.UnionSorted(ret, model.Values[key])
}
}
return ret
}
// -- MDB Data Model -- //
type ScanRows func(rows *sql.Rows, datas map[string]interface{}) error
type MDBDataModel struct {
db *sql.DB
name string
interval time.Duration
sql string
scanRows ScanRows
Datas map[string]interface{}
datasMutex sync.RWMutex
}
func MakeMDBDataModel(db *sql.DB, name string, interval time.Duration, sql string, scanRows ScanRows) *MDBDataModel {
return &MDBDataModel{db, name, interval, sql, scanRows, make(map[string]interface{}), sync.RWMutex{}}
}
func (model *MDBDataModel) Name() string {
return model.name
}
func (model *MDBDataModel) Interval() time.Duration {
return model.interval
}
func (model *MDBDataModel) Refresh() error {
rows, err := queries.Raw(model.db, model.sql).Query()
if err != nil {
return err
}
defer rows.Close()
tmp := make(map[string]interface{})
for rows.Next() {
if err := model.scanRows(rows, tmp); err != nil {
return err
}
}
model.datasMutex.Lock()
defer model.datasMutex.Unlock()
for k, d := range tmp {
model.Datas[k] = d
}
return nil
}
func (model *MDBDataModel) Data(key string) interface{} {
model.datasMutex.RLock()
defer model.datasMutex.RUnlock()
return model.Datas[key]
}
func (model *MDBDataModel) Keys() []string {
model.datasMutex.RLock()
defer model.datasMutex.RUnlock()
keys := []string(nil)
for k := range model.Datas {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}