-
Notifications
You must be signed in to change notification settings - Fork 11
/
stats.go
474 lines (429 loc) 路 16.7 KB
/
stats.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/hex"
"errors"
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/labstack/echo/v4"
)
type StatsHandler struct {
repo storage.IStats
nsRepo storage.INamespace
price storage.IPrice
state storage.IState
}
func NewStatsHandler(repo storage.IStats, nsRepo storage.INamespace, price storage.IPrice, state storage.IState) StatsHandler {
return StatsHandler{
repo: repo,
nsRepo: nsRepo,
price: price,
state: state,
}
}
type summaryRequest struct {
Table string `example:"block" param:"table" swaggertype:"string" validate:"required,oneof=block block_stats tx event message validator"`
Function string `example:"count" param:"function" swaggertype:"string" validate:"required,oneof=avg sum min max count"`
Column string `example:"fee" query:"column" swaggertype:"string" validate:"omitempty"`
From uint64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To uint64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Summary godoc
//
// @Summary Get value by table and function
// @Description.markdown summary
// @Tags stats
// @ID stats-summary
// @Param table path string true "Table name" Enums(block, block_stats, tx, event, message, validator)
// @Param function path string true "Function name" Enums(min, max, avg, sum, count)
// @Param column query string false "Column name which will be used for computation. Optional for count."
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {object} string
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/summary/{table}/{function} [get]
func (sh StatsHandler) Summary(c echo.Context) error {
req, err := bindAndValidate[summaryRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
summary string
countRequest = storage.CountRequest{
Table: req.Table,
From: req.From,
To: req.To,
}
)
if req.Function == "count" {
summary, err = sh.repo.Count(c.Request().Context(), countRequest)
} else {
summary, err = sh.repo.Summary(c.Request().Context(), storage.SummaryRequest{
CountRequest: countRequest,
Function: req.Function,
Column: req.Column,
})
}
if err != nil {
if errors.Is(err, storage.ErrValidation) {
return badRequestError(c, err)
}
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, summary)
}
type histogramRequest struct {
Table string `example:"block" param:"table" swaggertype:"string" validate:"required,oneof=block block_stats tx event message"`
Function string `example:"count" param:"function" swaggertype:"string" validate:"required,oneof=avg sum min max count"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
Column string `example:"fee" query:"column" swaggertype:"string" validate:"omitempty"`
From uint64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To uint64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Histogram godoc
//
// @Summary Get histogram
// @Description.markdown histogram
// @Tags stats
// @ID stats-histogram
// @Param table path string true "Table name" Enums(block, block_stats, tx, event, message)
// @Param function path string true "Function name" Enums(min, max, avg, sum, count)
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param column query string false "Column name which will be used for computation. Optional for count"
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.HistogramItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/histogram/{table}/{function}/{timeframe} [get]
func (sh StatsHandler) Histogram(c echo.Context) error {
req, err := bindAndValidate[histogramRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
histogram []storage.HistogramItem
countRequest = storage.CountRequest{
Table: req.Table,
From: req.From,
To: req.To,
}
)
if req.Function == "count" {
histogram, err = sh.repo.HistogramCount(c.Request().Context(), storage.HistogramCountRequest{
CountRequest: countRequest,
Timeframe: storage.Timeframe(req.Timeframe),
})
} else {
histogram, err = sh.repo.Histogram(c.Request().Context(), storage.HistogramRequest{
SummaryRequest: storage.SummaryRequest{
CountRequest: countRequest,
Function: req.Function,
Column: req.Column,
},
Timeframe: storage.Timeframe(req.Timeframe),
})
}
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.HistogramItem, len(histogram))
for i := range histogram {
response[i] = responses.NewHistogramItem(histogram[i])
}
return returnArray(c, response)
}
// TPS godoc
//
// @Summary Get tps
// @Description Returns transaction per seconds statistics
// @Tags stats
// @ID stats-tps
// @Produce json
// @Success 200 {object} responses.TPS
// @Failure 500 {object} Error
// @Router /v1/stats/tps [get]
func (sh StatsHandler) TPS(c echo.Context) error {
tps, err := sh.repo.TPS(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewTPS(tps))
}
// TxCountHourly24h godoc
//
// @Summary Get tx count histogram for last 24 hours by hour
// @Description Get tx count histogram for last 24 hours by hour
// @Tags stats
// @ID stats-tx-count-24h
// @Produce json
// @Success 200 {array} responses.TxCountHistogramItem
// @Failure 500 {object} Error
// @Router /v1/stats/tx_count_24h [get]
func (sh StatsHandler) TxCountHourly24h(c echo.Context) error {
histogram, err := sh.repo.TxCountForLast24h(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.TxCountHistogramItem, len(histogram))
for i := range histogram {
response[i] = responses.NewTxCountHistogramItem(histogram[i])
}
return returnArray(c, response)
}
type namespaceUsageRequest struct {
Top *int `example:"100" query:"top" validate:"omitempty,min=1,max=100"`
}
// NamespaceUsage godoc
//
// @Summary Get namespaces with sorting by size.
// @Description Get namespaces with sorting by size. Returns top 100 namespaces. Namespaces which is not included to top 100 grouped into 'others' item
// @Tags stats
// @ID stats-namespace-usage
// @Param top query integer false "Count of entities" mininum(1) maximum(100)
// @Produce json
// @Success 200 {array} responses.NamespaceUsage
// @Failure 500 {object} Error
// @Router /v1/stats/namespace/usage [get]
func (sh StatsHandler) NamespaceUsage(c echo.Context) error {
req, err := bindAndValidate[namespaceUsageRequest](c)
if err != nil {
return badRequestError(c, err)
}
if req.Top == nil {
top := 10
req.Top = &top
}
namespaces, err := sh.nsRepo.ListWithSort(c.Request().Context(), "size", sdk.SortOrderDesc, *req.Top, 0)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
var top100Size int64
response := make([]responses.NamespaceUsage, len(namespaces)+1)
for i := range namespaces {
response[i] = responses.NewNamespaceUsage(namespaces[i])
top100Size += response[i].Size
}
state, err := sh.state.List(c.Request().Context(), 1, 0, sdk.SortOrderAsc)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
if len(state) == 0 {
return returnArray(c, response)
}
response[len(namespaces)] = responses.NamespaceUsage{
Name: "others",
Size: state[0].TotalBlobsSize - top100Size,
Version: nil,
}
return returnArray(c, response)
}
type seriesRequest struct {
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=blobs_size blobs_count tps bps fee supply_change block_time tx_count events_count gas_price gas_efficiency gas_used gas_limit bytes_in_block rewards commissions"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Series godoc
//
// @Summary Get histogram with precomputed stats
// @Description Get histogram with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-series
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param name path string true "Series name" Enums(blobs_size, blobs_count, tps, bps, fee, supply_change, block_time, tx_count, events_count, gas_price, gas_efficiency, gas_used, gas_limit, bytes_in_block, rewards, commissions)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/series/{name}/{timeframe} [get]
func (sh StatsHandler) Series(c echo.Context) error {
req, err := bindAndValidate[seriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := sh.repo.Series(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type namespaceSeriesRequest struct {
Id string `example:"0011223344" param:"id" swaggertype:"string" validate:"required,hexadecimal,len=56"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
SeriesName string `example:"size" param:"name" swaggertype:"string" validate:"required,oneof=pfb_count size"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// NamespaceSeries godoc
//
// @Summary Get histogram for namespace with precomputed stats
// @Description Get histogram for namespace with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-ns-series
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param name path string true "Series name" Enums(pfb_count, size)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/namespace/series/{id}/{name}/{timeframe} [get]
func (sh StatsHandler) NamespaceSeries(c echo.Context) error {
req, err := bindAndValidate[namespaceSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
namespace, err := sh.nsRepo.ByNamespaceId(c.Request().Context(), namespaceId)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
if len(namespace) == 0 {
return c.JSON(http.StatusOK, []any{})
}
histogram, err := sh.repo.NamespaceSeries(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
namespace[0].Id,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type priceSeriesRequest struct {
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=1m 1h 1d"`
From uint64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To uint64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// PriceSeries godoc
//
// @Summary Get histogram with TIA price
// @Description Get histogram with TIA price
// @Tags stats
// @ID stats-price-series
// @Param timeframe path string true "Timeframe" Enums(1m, 1h, 1d)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.Price
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/price/series/{timeframe} [get]
func (sh StatsHandler) PriceSeries(c echo.Context) error {
req, err := bindAndValidate[priceSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
from time.Time
to time.Time
)
if req.From > 0 {
from = time.Unix(int64(req.From), 0).UTC()
}
if req.To > 0 {
to = time.Unix(int64(req.To), 0).UTC()
}
histogram, err := sh.price.Get(c.Request().Context(), req.Timeframe, from, to, 100)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.Price, len(histogram))
for i := range histogram {
response[i] = responses.NewPrice(histogram[i])
}
return returnArray(c, response)
}
// PriceCurrent godoc
//
// @Summary Get current TIA price
// @Description Get current TIA price
// @Tags stats
// @ID stats-price-current
// @Produce json
// @Success 200 {object} responses.Price
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/price/current [get]
func (sh StatsHandler) PriceCurrent(c echo.Context) error {
price, err := sh.price.Last(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewPrice(price))
}
type stakingSeriesRequest struct {
Id uint64 `example:"123" param:"id" swaggertype:"integer" validate:"required,min=1"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day month"`
SeriesName string `example:"size" param:"name" swaggertype:"string" validate:"required,oneof=rewards commissions flow"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// StakingSeries godoc
//
// @Summary Get histogram for staking with precomputed stats
// @Description Get histogram for staking with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-staking-series
// @Param id path string true "Validator id" minlength(56) maxlength(56)
// @Param timeframe path string true "Timeframe" Enums(hour, day, month)
// @Param name path string true "Series name" Enums(rewards, commissions, flow)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/staking/series/{id}/{name}/{timeframe} [get]
func (sh StatsHandler) StakingSeries(c echo.Context) error {
req, err := bindAndValidate[stakingSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := sh.repo.StakingSeries(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
req.Id,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}