-
Notifications
You must be signed in to change notification settings - Fork 10
/
controller.go
463 lines (411 loc) · 13.8 KB
/
controller.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
package controllers
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
"github.com/textileio/go-tableland/buildinfo"
"github.com/textileio/go-tableland/internal/formatter"
"github.com/textileio/go-tableland/internal/gateway"
"github.com/textileio/go-tableland/internal/router/controllers/apiv1"
"github.com/textileio/go-tableland/internal/router/middlewares"
"github.com/textileio/go-tableland/internal/tableland"
"github.com/textileio/go-tableland/pkg/errors"
"github.com/textileio/go-tableland/pkg/tables"
"github.com/textileio/go-tableland/pkg/telemetry"
)
// Controller defines the HTTP handlers for interacting with user tables.
type Controller struct {
gateway gateway.Gateway
}
// NewController creates a new Controller.
func NewController(gateway gateway.Gateway) *Controller {
return &Controller{
gateway: gateway,
}
}
// MetadataConfig defines columns should be mapped to erc721 metadata
// when using format=erc721 query param.
type MetadataConfig struct {
Image string `query:"image"`
ImageTransparent string `query:"image_transparent"`
ImageData string `query:"image_data"`
ExternalURL string `query:"external_url"`
Description string `query:"description"`
Name string `query:"name"`
Attributes []AttributeConfig `query:"attributes"`
BackgroundColor string `query:"background_color"`
AnimationURL string `query:"animation_url"`
YoutubeURL string `query:"youtube_url"`
}
// AttributeConfig provides formatting for a column used to drive an Attribute
// when using format=erc721 query param.
type AttributeConfig struct {
Column string `query:"column"`
DisplayType string `query:"display_type"`
TraitType string `query:"trait_type"`
}
// Metadata represents erc721 metadata.
// Ref: https://docs.opensea.io/docs/metadata-standards
type Metadata struct {
Image interface{} `json:"image,omitempty"`
ImageTransparent interface{} `json:"image_transparent,omitempty"`
ImageData interface{} `json:"image_data,omitempty"`
ExternalURL interface{} `json:"external_url,omitempty"`
Description interface{} `json:"description,omitempty"`
Name interface{} `json:"name,omitempty"`
Attributes []Attribute `json:"attributes,omitempty"`
BackgroundColor interface{} `json:"background_color,omitempty"`
AnimationURL interface{} `json:"animation_url,omitempty"`
YoutubeURL interface{} `json:"youtube_url,omitempty"`
}
// Attribute is a single entry in the "attributes" field of Metadata.
type Attribute struct {
DisplayType string `json:"display_type,omitempty"`
TraitType string `json:"trait_type"`
Value interface{} `json:"value"`
}
// Version returns git information of the running binary.
func (c *Controller) Version(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("Content-type", "application/json")
summary := buildinfo.GetSummary()
rw.WriteHeader(http.StatusOK)
_ = json.NewEncoder(rw).Encode(apiv1.VersionInfo{
Version: int32(summary.Version),
GitCommit: summary.GitCommit,
GitBranch: summary.GitBranch,
GitState: summary.GitState,
GitSummary: summary.GitSummary,
BuildDate: summary.BuildDate,
BinaryVersion: summary.BinaryVersion,
})
}
// GetReceiptByTransactionHash handles request asking for a transaction receipt.
func (c *Controller) GetReceiptByTransactionHash(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
paramTxnHash := mux.Vars(r)["transactionHash"]
if _, err := common.ParseHexOrString(paramTxnHash); err != nil {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusBadRequest)
log.Ctx(ctx).Error().Err(err).Msg("invalid transaction hash")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: "Invalid transaction hash"})
return
}
txnHash := common.HexToHash(paramTxnHash)
receipt, exists, err := c.gateway.GetReceiptByTransactionHash(
ctx, ctx.Value(middlewares.ContextKeyChainID).(tableland.ChainID), txnHash,
)
if err != nil {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusBadRequest)
log.Ctx(ctx).Error().Err(err).Msg("get receipt by transaction hash")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: "Get receipt by transaction hash failed"})
return
}
if !exists {
rw.WriteHeader(http.StatusNotFound)
return
}
receiptResponse := apiv1.TransactionReceipt{
TransactionHash: paramTxnHash,
BlockNumber: receipt.BlockNumber,
ChainId: int32(receipt.ChainID),
}
if receipt.TableID != nil { // nolint
receiptResponse.TableId = receipt.TableID.String() // nolint
}
if receipt.Error != nil {
receiptResponse.Error_ = *receipt.Error
receiptResponse.ErrorEventIdx = int32(*receipt.ErrorEventIdx)
}
ids := make([]string, len(receipt.TableIDs))
for i, tblID := range receipt.TableIDs {
ids[i] = tblID.String()
}
receiptResponse.TableIds = ids
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
_ = json.NewEncoder(rw).Encode(receiptResponse)
}
// GetTable handles the GET /tables/{chainID}/{tableId} call.
func (c *Controller) GetTable(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
vars := mux.Vars(r)
id, err := tables.NewTableID(vars["tableId"])
if err != nil {
rw.Header().Set("Content-type", "application/json")
rw.WriteHeader(http.StatusBadRequest)
log.Ctx(ctx).
Error().
Err(err).
Msg("invalid id format")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: "Invalid id format"})
return
}
metadata, err := c.gateway.GetTableMetadata(ctx, ctx.Value(middlewares.ContextKeyChainID).(tableland.ChainID), id)
if err == gateway.ErrTableNotFound {
rw.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
rw.Header().Set("Content-type", "application/json")
rw.WriteHeader(http.StatusInternalServerError)
log.Ctx(ctx).
Error().
Err(err).
Str("id", id.String()).
Msg("failed to fetch metadata")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: "Failed to fetch metadata"})
return
}
metadataV1 := apiv1.Table{
Name: metadata.Name,
ExternalUrl: metadata.ExternalURL,
AnimationUrl: metadata.AnimationURL,
Image: metadata.Image,
Attributes: make([]apiv1.TableAttributes, len(metadata.Attributes)),
Schema: &apiv1.Schema{
Columns: make([]apiv1.Column, len(metadata.Schema.Columns)),
TableConstraints: make([]string, len(metadata.Schema.TableConstraints)),
},
}
for i, attr := range metadata.Attributes {
metadataV1.Attributes[i] = apiv1.TableAttributes{
DisplayType: attr.DisplayType,
TraitType: attr.TraitType,
Value: attr.Value,
}
}
for i, schemaColumn := range metadata.Schema.Columns {
metadataV1.Schema.Columns[i] = apiv1.Column{
Name: schemaColumn.Name,
Type_: schemaColumn.Type,
Constraints: make([]string, len(schemaColumn.Constraints)),
}
copy(metadataV1.Schema.Columns[i].Constraints, schemaColumn.Constraints)
}
copy(metadataV1.Schema.TableConstraints, metadata.Schema.TableConstraints)
rw.Header().Set("Content-type", "application/json")
rw.WriteHeader(http.StatusOK)
enc := json.NewEncoder(rw)
enc.SetEscapeHTML(false)
_ = enc.Encode(metadataV1)
}
// HealthHandler serves health check requests.
func HealthHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
// GetTableQuery handles the GET /query?statement=[statement] call.
// Use format=objects|table query param to control output format.
func (c *Controller) GetTableQuery(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
stm := r.URL.Query().Get("statement")
params := []string{}
if r.URL.Query().Has("params") {
params = r.URL.Query()["params"]
}
start := time.Now()
res, ok := c.runReadRequest(r.Context(), stm, params, rw)
if !ok {
return
}
took := time.Since(start)
opts, err := formatterOptions(r)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("Error parsing formatting params: %v", err)
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: msg})
log.Ctx(r.Context()).Error().Err(err).Msg(msg)
return
}
formatted, config, err := formatter.Format(res, opts...)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
msg := fmt.Sprintf("Error formatting data: %v", err)
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: msg})
log.Ctx(r.Context()).Error().Err(err).Msg(msg)
return
}
if len(formatted) == 0 {
rw.WriteHeader(http.StatusNotFound)
return
}
collectReadQueryMetric(r.Context(), stm, config, took)
rw.WriteHeader(http.StatusOK)
if config.Unwrap && len(res.Rows) > 1 {
rw.Header().Set("Content-Type", "application/jsonl+json")
}
_, _ = rw.Write(formatted)
}
// PostTableQuery handles the POST /query call.
func (c *Controller) PostTableQuery(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
// setting a default body because these options could be missing from JSON
body := &apiv1.Query{
Params: []any{},
Format: string(formatter.Objects),
Extract: false,
Unwrap: false,
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
rw.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("Error parsing the body request: %v", err)
log.Ctx(r.Context()).Error().Err(err).Msg(msg)
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: msg})
return
}
_ = r.Body.Close()
params := make([]string, len(body.Params))
for i, p := range body.Params {
switch v := p.(type) {
case float64:
params[i] = fmt.Sprint(v)
case string:
params[i] = fmt.Sprintf("\"%s\"", v)
case nil:
params[i] = "null"
case bool:
params[i] = "false"
if v {
params[i] = "true"
}
default:
rw.WriteHeader(http.StatusBadRequest)
msg := fmt.Sprintf("invalid type (%T) of parameter", v)
log.Ctx(r.Context()).Error().Msg(msg)
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: msg})
return
}
}
start := time.Now()
res, ok := c.runReadRequest(r.Context(), body.Statement, params, rw)
if !ok {
return
}
took := time.Since(start)
var opts []formatter.FormatOption
output, ok := formatter.OutputFromString(body.Format)
if !ok {
log.Ctx(r.Context()).Error().Msg("bad output query parameter")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: "bad output query parameter"})
}
opts = append(opts, formatter.WithOutput(output))
opts = append(opts, formatter.WithExtract(body.Extract))
opts = append(opts, formatter.WithUnwrap(body.Unwrap))
formatted, config, err := formatter.Format(res, opts...)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
msg := fmt.Sprintf("Error formatting data: %v", err)
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: msg})
log.Ctx(r.Context()).Error().Err(err).Msg(msg)
return
}
if len(formatted) == 0 {
rw.WriteHeader(http.StatusNotFound)
return
}
collectReadQueryMetric(r.Context(), body.Statement, config, took)
rw.WriteHeader(http.StatusOK)
if config.Unwrap && len(res.Rows) > 1 {
rw.Header().Set("Content-Type", "application/jsonl+json")
}
_, _ = rw.Write(formatted)
}
func (c *Controller) runReadRequest(
ctx context.Context,
stm string,
params []string,
rw http.ResponseWriter,
) (*gateway.TableData, bool) {
res, err := c.gateway.RunReadQuery(ctx, stm, params)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
log.Ctx(ctx).
Error().
Str("sql_request", stm).
Err(err).
Msg("executing read query")
_ = json.NewEncoder(rw).Encode(errors.ServiceError{Message: err.Error()})
return nil, false
}
return res, true
}
func formatterOptions(r *http.Request) ([]formatter.FormatOption, error) {
var opts []formatter.FormatOption
params, err := getFormatterParams(r)
if err != nil {
return nil, err
}
if params.output != nil {
opts = append(opts, formatter.WithOutput(*params.output))
}
if params.extract != nil {
opts = append(opts, formatter.WithExtract(*params.extract))
}
if params.unwrap != nil {
opts = append(opts, formatter.WithUnwrap(*params.unwrap))
}
return opts, nil
}
type formatterParams struct {
output *formatter.Output
extract *bool
unwrap *bool
}
func getFormatterParams(r *http.Request) (formatterParams, error) {
c := formatterParams{}
output := r.URL.Query().Get("format")
extract := r.URL.Query().Get("extract")
unwrap := r.URL.Query().Get("unwrap")
if output != "" {
output, ok := formatter.OutputFromString(output)
if !ok {
return formatterParams{}, fmt.Errorf("bad output query parameter")
}
c.output = &output
}
if extract != "" {
extract, err := strconv.ParseBool(extract)
if err != nil {
return formatterParams{}, err
}
c.extract = &extract
}
if unwrap != "" {
unwrap, err := strconv.ParseBool(unwrap)
if err != nil {
return formatterParams{}, err
}
c.unwrap = &unwrap
}
return c, nil
}
// collectReadQueryMetric collects read query metric.
func collectReadQueryMetric(ctx context.Context, statement string, config formatter.FormatConfig, took time.Duration) {
value := ctx.Value(middlewares.ContextIPAddress)
ipAddress, ok := value.(string)
if ok && ipAddress != "" {
formatOptions := telemetry.ReadQueryFormatOptions{
Extract: config.Extract,
Unwrap: config.Unwrap,
Output: string(config.Output),
}
metric := telemetry.ReadQueryMetric{
Version: telemetry.ReadQueryMetricV1,
IPAddress: ipAddress,
SQLStatement: statement,
FormatOptions: formatOptions,
TookMilli: took.Milliseconds(),
}
if err := telemetry.Collect(ctx, metric); err != nil {
log.Warn().Err(err).Msg("failed to collect metric")
}
} else {
log.Warn().Str("sql_statement", statement).Msg("ip address not detected. metric not sent")
}
}