-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbigquery.go
377 lines (311 loc) · 11.8 KB
/
bigquery.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
package usage
import (
"context"
"fmt"
"strconv"
"time"
"cloud.google.com/go/bigquery"
"github.com/Masterminds/squirrel"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
type QueryFilter struct {
CreatorID string
UserID string
}
type QuerySpec struct {
TimeStep string
From, To *time.Time
Filter QueryFilter
}
type FromToQuerySpec struct {
From, To *time.Time
}
var allowedTimeSteps = map[string]bool{
"hour": true,
"day": true,
}
type UsageSummaryRow struct {
UserID string `bigquery:"user_id"`
CreatorID string `bigquery:"creator_id"`
DeliveryUsageMins float64 `bigquery:"delivery_usage_mins"`
TotalUsageMins float64 `bigquery:"transcode_total_usage_mins"`
StorageUsageMins float64 `bigquery:"storage_usage_mins"`
}
type ActiveUsersSummaryRow struct {
UserID string `bigquery:"user_id" json:"userId"`
Email string `bigquery:"email" json:"email"`
From time.Time `bigquery:"interval_start_date" json:"from"`
To time.Time `bigquery:"interval_end_date" json:"to"`
DeliveryUsageMins float64 `bigquery:"delivery_usage_mins" json:"deliveryUsageMins"`
TotalUsageMins float64 `bigquery:"transcode_total_usage_mins" json:"totalUsageMins"`
StorageUsageMins float64 `bigquery:"storage_usage_mins" json:"storageUsageMins"`
}
type TotalUsageSummaryRow struct {
DateTs time.Time `bigquery:"date_ts" json:"dateTs"`
DateS int64 `bigquery:"date_s" json:"dateS"`
WeekTs time.Time `bigquery:"week_ts" json:"weekTs"`
WeekS int64 `bigquery:"week_s" json:"weekS"`
VolumeEth float64 `bigquery:"volume_eth" json:"volumeEth"`
VolumeUsd float64 `bigquery:"volume_usd" json:"volumeUsd"`
FeeDerivedMinutes float64 `bigquery:"fee_derived_minutes" json:"feeDerivedMinutes"`
ParticipationRate float64 `bigquery:"participation_rate" json:"participationRate"`
Inflation float64 `bigquery:"inflation" json:"inflation"`
ActiveTranscoderCount int64 `bigquery:"active_transcoder_count" json:"activeTranscoderCount"`
DelegatorsCount int64 `bigquery:"delegators_count" json:"delegatorsCount"`
AveragePricePerPixel float64 `bigquery:"average_price_per_pixel" json:"averagePricePerPixel"`
AveragePixelPerMinute float64 `bigquery:"average_pixel_per_minute" json:"averagePixelPerMinute"`
}
type BigQuery interface {
QueryUsageSummary(ctx context.Context, userID string, creatorID string, spec QuerySpec) (*UsageSummaryRow, error)
QueryUsageSummaryWithTimestep(ctx context.Context, userID string, creatorID string, spec QuerySpec) (*[]UsageSummaryRow, error)
QueryTotalUsageSummary(ctx context.Context, spec FromToQuerySpec) (*[]TotalUsageSummaryRow, error)
QueryActiveUsersUsageSummary(ctx context.Context, spec FromToQuerySpec) (*[]ActiveUsersSummaryRow, error)
}
type BigQueryOptions struct {
BigQueryCredentialsJSON string
HourlyUsageTable string
DailyUsageTable string
UsersTable string
MaxBytesBilledPerBigQuery int64
}
const maxBigQueryResultRows = 10000
func NewBigQuery(opts BigQueryOptions) (BigQuery, error) {
bigquery, err := bigquery.NewClient(context.Background(),
bigquery.DetectProjectID,
option.WithCredentialsJSON([]byte(opts.BigQueryCredentialsJSON)))
if err != nil {
return nil, fmt.Errorf("error creating bigquery client: %w", err)
}
return &bigqueryHandler{opts, bigquery}, nil
}
func parseInputTimestamp(str string) (*time.Time, error) {
if str == "" {
return nil, nil
}
t, rfcErr := time.Parse(time.RFC3339Nano, str)
if rfcErr == nil {
return &t, nil
}
ts, unixErr := strconv.ParseInt(str, 10, 64)
if unixErr != nil {
return nil, fmt.Errorf("bad time %q. must be in RFC3339 or Unix Timestamp (millisecond) formats. rfcErr: %s; unixErr: %s", str, rfcErr, unixErr)
}
t = time.UnixMilli(ts)
return &t, nil
}
// interface from *bigquery.Client to allow mocking
type bigqueryClient interface {
Query(q string) *bigquery.Query
}
type bigqueryHandler struct {
opts BigQueryOptions
client bigqueryClient
}
// usage summary query
func (bq *bigqueryHandler) QueryUsageSummary(ctx context.Context, userID string, creatorID string, spec QuerySpec) (*UsageSummaryRow, error) {
sql, args, err := buildUsageSummaryQuery(bq.opts.HourlyUsageTable, userID, creatorID, spec)
if err != nil {
return nil, fmt.Errorf("error building usage summary query: %w", err)
}
bqRows, err := doBigQuery[UsageSummaryRow](bq, ctx, sql, args)
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
} else if len(bqRows) > 1 {
return nil, fmt.Errorf("internal error, query returned %d rows", len(bqRows))
}
if len(bqRows) == 0 {
return &UsageSummaryRow{
UserID: userID,
CreatorID: creatorID,
DeliveryUsageMins: 0,
TotalUsageMins: 0,
StorageUsageMins: 0,
}, nil
}
return &bqRows[0], nil
}
func (bq *bigqueryHandler) QueryUsageSummaryWithTimestep(ctx context.Context, userID string, creatorID string, spec QuerySpec) (*[]UsageSummaryRow, error) {
sql, args, err := buildUsageSummaryQuery(bq.opts.HourlyUsageTable, userID, creatorID, spec)
if err != nil {
return nil, fmt.Errorf("error building usage summary query: %w", err)
}
bqRows, err := doBigQuery[UsageSummaryRow](bq, ctx, sql, args)
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
}
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
} else if len(bqRows) > maxBigQueryResultRows {
return nil, fmt.Errorf("query must return less than %d datapoints. consider decreasing your timeframe or increasing the time step", maxBigQueryResultRows)
}
if len(bqRows) == 0 {
return nil, nil
}
return &bqRows, nil
}
func (bq *bigqueryHandler) QueryTotalUsageSummary(ctx context.Context, spec FromToQuerySpec) (*[]TotalUsageSummaryRow, error) {
sql, args, err := buildTotalUsageSummaryQuery(bq.opts.DailyUsageTable, spec)
if err != nil {
return nil, fmt.Errorf("error building usage summary query: %w", err)
}
bqRows, err := doBigQuery[TotalUsageSummaryRow](bq, ctx, sql, args)
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
}
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
} else if len(bqRows) > maxBigQueryResultRows {
return nil, fmt.Errorf("query must return less than %d datapoints. consider decreasing your timeframe or increasing the time step", maxBigQueryResultRows)
}
if len(bqRows) == 0 {
return nil, nil
}
return &bqRows, nil
}
func (bq *bigqueryHandler) QueryActiveUsersUsageSummary(ctx context.Context, spec FromToQuerySpec) (*[]ActiveUsersSummaryRow, error) {
sql, args, err := buildActiveUsersUsageSummaryQuery(bq.opts.HourlyUsageTable, bq.opts.UsersTable, spec)
if err != nil {
return nil, fmt.Errorf("error building active users summary query: %w", err)
}
bqRows, err := doBigQuery[ActiveUsersSummaryRow](bq, ctx, sql, args)
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
}
if err != nil {
return nil, fmt.Errorf("bigquery error: %w", err)
} else if len(bqRows) > maxBigQueryResultRows {
return nil, fmt.Errorf("query must return less than %d datapoints. consider decreasing your timeframe or increasing the time step", maxBigQueryResultRows)
}
if len(bqRows) == 0 {
return nil, nil
}
return &bqRows, nil
}
func buildUsageSummaryQuery(table string, userID string, creatorID string, spec QuerySpec) (string, []interface{}, error) {
if userID == "" {
return "", nil, fmt.Errorf("userID cannot be empty")
}
query := squirrel.Select(
"cast(sum(transcode_total_usage_mins) as FLOAT64) as transcode_total_usage_mins",
"cast(sum(delivery_usage_mins) as FLOAT64) as delivery_usage_mins",
"cast((sum(storage_usage_mins) / count(distinct usage_hour_ts)) as FLOAT64) as storage_usage_mins").
From(table).
Limit(maxBigQueryResultRows + 1)
if creatorId := spec.Filter.CreatorID; creatorId != "" {
query = query.Where("creator_id_type = ?", "unverified")
query = query.Where("creator_id = ?", creatorID)
}
if from := spec.From; from != nil {
query = query.Where("usage_hour_ts >= timestamp_millis(?)", from.UnixMilli())
}
if to := spec.To; to != nil {
query = query.Where("usage_hour_ts < timestamp_millis(?)", to.UnixMilli())
}
if timeStep := spec.TimeStep; timeStep != "" {
if !allowedTimeSteps[timeStep] {
return "", nil, fmt.Errorf("invalid time step: %s", timeStep)
}
query = query.
Columns(fmt.Sprintf("timestamp_trunc(usage_hour_ts, %s) as time_interval", timeStep)).
GroupBy("time_interval").
OrderBy("time_interval")
}
query = withUserIdFilter(query, userID)
sql, args, err := query.ToSql()
if err != nil {
return "", nil, err
}
return sql, args, nil
}
func buildTotalUsageSummaryQuery(table string, spec FromToQuerySpec) (string, []interface{}, error) {
query := squirrel.Select(
"date_ts,date_s,week_ts,week_s,volume_eth,volume_usd, fee_derived_minutes,participation_rate,inflation,active_transcoder_count,delegators_count,average_price_per_pixel,average_pixel_per_minute").
From(table).
Limit(maxBigQueryResultRows + 1).
OrderBy("date_ts DESC")
if from := spec.From; from != nil {
query = query.Where("date_ts >= timestamp_millis(?)", from.UnixMilli())
}
if to := spec.To; to != nil {
query = query.Where("date_ts < timestamp_millis(?)", to.UnixMilli())
}
sql, args, err := query.ToSql()
if err != nil {
return "", nil, err
}
return sql, args, nil
}
func buildActiveUsersUsageSummaryQuery(billingTable, usersTable string, spec FromToQuerySpec) (string, []interface{}, error) {
// Create the base select statement using the provided billingTable and usersTable
query := squirrel.
Select(
"b.user_id",
"u.email",
"min(usage_hour_ts) as interval_start_date",
"max(usage_hour_ts) as interval_end_date",
"cast(sum(transcode_total_usage_mins) as FLOAT64) as transcode_total_usage_mins",
"cast(sum(delivery_usage_mins) as FLOAT64) as delivery_usage_mins",
"cast((sum(storage_usage_mins) / count(distinct usage_hour_ts)) as FLOAT64) as storage_usage_mins",
).
From(fmt.Sprintf("`%s` as b", billingTable)).
Join(fmt.Sprintf("%s as u on b.user_id = u.user_id", usersTable)).
Where("not internal").
GroupBy("b.user_id", "u.email").
Having("transcode_total_usage_mins > 0 or delivery_usage_mins > 0 or storage_usage_mins > 0")
// Apply additional conditions based on the spec provided
if from := spec.From; from != nil {
query = query.Where("usage_hour_ts >= timestamp_millis(?)", from.UnixMilli())
}
if to := spec.To; to != nil {
query = query.Where("usage_hour_ts < timestamp_millis(?)", to.UnixMilli())
}
// Convert to SQL
sql, args, err := query.ToSql()
if err != nil {
return "", nil, err
}
return sql, args, nil
}
// query helpers
func withUserIdFilter(query squirrel.SelectBuilder, userID string) squirrel.SelectBuilder {
if userID == "" {
query = query.Column("user_id").GroupBy("user_id")
} else {
query = query.Columns("user_id").
Where("user_id = ?", userID).
GroupBy("user_id")
}
return query
}
func doBigQuery[RowT any](bq *bigqueryHandler, ctx context.Context, sql string, args []interface{}) ([]RowT, error) {
query := bq.client.Query(sql)
query.Parameters = toBigQueryParameters(args)
query.MaxBytesBilled = bq.opts.MaxBytesBilledPerBigQuery
it, err := query.Read(ctx)
if err != nil {
return nil, fmt.Errorf("error running query: %w", err)
}
return toTypedValues[RowT](it)
}
func toBigQueryParameters(args []interface{}) []bigquery.QueryParameter {
params := make([]bigquery.QueryParameter, len(args))
for i, arg := range args {
params[i] = bigquery.QueryParameter{Value: arg}
}
return params
}
func toTypedValues[RowT any](it *bigquery.RowIterator) ([]RowT, error) {
var values []RowT
for {
var row RowT
err := it.Next(&row)
if err == iterator.Done {
break
} else if err != nil {
return nil, fmt.Errorf("error reading query result: %w", err)
}
values = append(values, row)
}
return values, nil
}