-
Notifications
You must be signed in to change notification settings - Fork 4
/
event-handler.go
266 lines (225 loc) · 7.26 KB
/
event-handler.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
package statistics
import (
"context"
"embed"
"cloud.google.com/go/bigquery"
"github.com/ansel1/merry/v2"
"github.com/bcc-code/bcc-media-platform/backend/sqlc"
"github.com/bcc-code/bcc-media-platform/backend/utils"
"github.com/bcc-code/mediabank-bridge/log"
"github.com/google/uuid"
"github.com/samber/lo"
"go.opentelemetry.io/otel"
)
var bqTables = []string{
"shows",
"seasons",
"episodes",
}
// Embed the migrations into the binary
//
//go:embed bq-schema/*.json
var bqMigrationsJson embed.FS
type BigQueryConfig struct {
ProjectID string
DatasetID string
}
type Handler struct {
bigQueryClient *bigquery.Client
bigQueryDataset *bigquery.Dataset
queries *sqlc.Queries
}
func NewHandler(ctx context.Context, bqConfig BigQueryConfig, q *sqlc.Queries) *Handler {
ctx, span := otel.Tracer("statistics").Start(ctx, "NewDirectusHandler")
defer span.End()
bqClient, err := bigquery.NewClient(ctx, bqConfig.ProjectID)
if err != nil || bqConfig.ProjectID == "" || bqConfig.DatasetID == "" {
log.L.Warn().
Err(err).
Str("ProjectID", bqConfig.ProjectID).
Str("DatasetID", bqConfig.DatasetID).
Msg("Failed to set up BQ client. Data will not be exported to BQ")
return nil
}
bqDataset := bqClient.Dataset(bqConfig.DatasetID)
for _, tableName := range bqTables {
err := bqTableExistsOrCreate(ctx, bqDataset, tableName)
if err != nil {
log.L.Error().
Err(err).
Str("ProjectID", bqConfig.ProjectID).
Str("DatasetID", bqConfig.DatasetID).
Str("TableName", tableName).
Msg("Failed to load or create table in BQ")
}
}
return &Handler{
bigQueryClient: bqClient,
bigQueryDataset: bqDataset,
queries: q,
}
}
func (h *Handler) HandleDirectusEvent(ctx context.Context, collection string, id string) error {
log.L.Debug().Str("collection", collection).Str("id", id).Msg("Processing directus updates")
intID := utils.AsInt(id)
switch collection {
case "shows":
return h.handleShow(ctx, intID)
case "seasons":
return h.handleSeason(ctx, intID)
case "episodes":
return h.handleEpisode(ctx, intID)
case "timedmetadata":
return h.handleTimedMetadata(ctx, id)
case "mediaitems":
return h.handleMediaitem(ctx, id)
case "shorts":
return h.handleShort(ctx, id)
case "calendarentries":
return h.handleCalendarEntry(ctx, id)
default:
log.L.Debug().Str("collection", collection).Msg("Cllection not suported. Skipping")
}
return nil
}
func (h *Handler) insert(ctx context.Context, obj interface{}, tableName string) error {
table := h.bigQueryDataset.Table(tableName)
inserter := table.Inserter()
inserter.IgnoreUnknownValues = false
inserter.SkipInvalidRows = false
return merry.Wrap(inserter.Put(ctx, obj))
}
func (h *Handler) handleShow(ctx context.Context, id int) error {
log.L.Debug().Int("show_id", id).Msg("updating show in BQ")
shows, err := h.queries.GetShows(ctx, []int{id})
if err != nil {
return merry.Wrap(err)
}
if len(shows) == 0 {
// Show was deleted. Not supported yet. Log warning and return nil
log.L.Warn().Int("show id", id).Msg("Attempting to sync a deleted show. Not implemented")
return nil
}
bqShows, err := h.resolveShows(ctx, shows)
if err != nil {
return merry.Wrap(err)
}
return h.insert(ctx, bqShows, "shows")
}
func (h *Handler) handleSeason(ctx context.Context, id int) error {
log.L.Debug().Int("season_id", id).Msg("updating season in BQ")
seasons, err := h.queries.GetSeasons(ctx, []int{id})
if err != nil {
return merry.Wrap(err)
}
if len(seasons) == 0 {
// Season was deleted. Not supported yet. Log warning and return nil
log.L.Warn().Int("season id", id).Msg("Attempting to sync a deleted season. Not implemented")
return nil
}
bqSeasons, err := h.resolveSeasons(ctx, seasons)
if err != nil {
return merry.Wrap(err)
}
return h.insert(ctx, bqSeasons, "seasons")
}
func (h *Handler) handleEpisode(ctx context.Context, id int) error {
log.L.Debug().Int("episodeId", id).Msg("updating episode in BQ")
episodes, err := h.queries.GetEpisodes(ctx, []int{id})
if err != nil {
return merry.Wrap(err)
}
if len(episodes) == 0 {
// Show was deleted. Not supported yet. Log warning and return nil
log.L.Warn().Int("episode id", id).Msg("Attempting to sync a deleted episode. Not implemented")
return nil
}
bqEpisodes, err := h.resolveEpisodes(ctx, episodes)
if err != nil {
return merry.Wrap(err)
}
return h.insert(ctx, bqEpisodes, "episodes")
}
func (h *Handler) handleTimedMetadata(ctx context.Context, id string) error {
log.L.Debug().Str("timedMetadata", id).Msg("updating timedMetadata in BQ")
tmUuid := utils.AsUuid(id)
timedMetadatas, err := h.queries.GetTimedMetadata(ctx, []uuid.UUID{tmUuid})
if err != nil {
return merry.Wrap(err)
}
if len(timedMetadatas) == 0 {
// Was deleted. Not supported yet. Log warning and return nil
log.L.Warn().Str("timed metadata id", id).Msg("Attempting to sync a deleted timed metadata. Not implemented")
return nil
}
bqTimedMetadatas := lo.Map(timedMetadatas, TimedMetadataFromCommon)
return h.insert(ctx, bqTimedMetadatas, "timedmetadata")
}
// handleMediaitem updated the related shorts in BQ
//
// This is intentinall as most of the data about the short is stored in the mediaitem
func (h *Handler) handleMediaitem(ctx context.Context, id string) error {
log.L.Debug().Str("mediaitem", id).Msg("updating mediaitem in BQ")
miUuid := utils.AsUuid(id)
shorts, err := h.queries.GetShortsByMediaItemIDs(ctx, miUuid)
if err != nil {
return merry.Wrap(err)
}
bqShorts, err := h.resolveShorts(ctx, shorts)
if err != nil {
return merry.Wrap(err)
}
err = h.insert(ctx, bqShorts, "shorts")
if err != nil {
return merry.Wrap(err)
}
episodeIDs, err := h.queries.GetEpisodeIDsByMediaItemID(ctx, miUuid)
if err != nil {
return merry.Wrap(err)
}
episodes, err := h.queries.GetEpisodes(ctx, episodeIDs)
if err != nil {
return merry.Wrap(err)
}
bqEpisodes, err := h.resolveEpisodes(ctx, episodes)
if err != nil {
return merry.Wrap(err)
}
return h.insert(ctx, bqEpisodes, "episodes")
}
func (h *Handler) handleShort(ctx context.Context, id string) error {
log.L.Debug().Str("shorts", id).Msg("updating shorts in BQ")
shortUuid := utils.AsUuid(id)
shorts, err := h.queries.GetShorts(ctx, []uuid.UUID{shortUuid})
if err != nil {
return merry.Wrap(err)
}
bqShorts, err := h.resolveShorts(ctx, shorts)
if err != nil {
return merry.Wrap(err)
}
return h.insert(ctx, bqShorts, "shorts")
}
func (h *Handler) handleCalendarEntry(ctx context.Context, id string) error {
log.L.Debug().Str("calendarEntry", id).Msg("updating calendarEntry in BQ")
event, err := h.queries.GetCalendarEntriesByID(ctx, []int{utils.AsInt(id)})
if err != nil {
return merry.Wrap(err)
}
bqEvents := lo.Map(event, CalendarEntryFromCommon)
return h.insert(ctx, bqEvents, "calendar_entries")
}
func (h *Handler) HandleAnswerExportToBQ(ctx context.Context) error {
lastExported, err := getLatestExportedAnswerDate(ctx, h.bigQueryClient, h.bigQueryDataset)
if err != nil {
return err
}
log.L.Debug().Time("last exported answer", lastExported).Msg("Starting export of answers to BQ")
res, err := h.queries.GetAnswersSince(ctx, lastExported)
if err != nil {
return err
}
bqAnswers := lo.Map(res, answerRowToBQRow)
log.L.Debug().Int("new answer count", len(bqAnswers)).Msg("Fetched answers to export")
return h.insert(ctx, bqAnswers, "answers")
}