Skip to content

Commit 4a23018

Browse files
Context package. Monitor
1 parent c1265a4 commit 4a23018

File tree

15 files changed

+475
-158
lines changed

15 files changed

+475
-158
lines changed

config/config.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ type Config struct {
1515
Database Database `yaml:"database" validate:"required"`
1616
DataSources map[string]DataSource `yaml:"datasources"`
1717
Contracts map[string]Contract `yaml:"contracts"`
18-
Hasura Hasura `yaml:"hasura"`
18+
Hasura Hasura `yaml:"hasura" validate:"omitempty"`
19+
Prometheus Prometheus `yaml:"prometheus" validate:"omitempty"`
1920
}
2021

2122
// Substitute -
@@ -56,6 +57,11 @@ type Hasura struct {
5657
Rest *bool `yaml:"rest"`
5758
}
5859

60+
// Prometheus -
61+
type Prometheus struct {
62+
URL string `yaml:"url" validate:"required"`
63+
}
64+
5965
// Load - load default config from `filename`
6066
func Load(filename string) (*Config, error) {
6167
if filename == "" {

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,13 @@ github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU=
112112
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
113113
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
114114
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
115+
github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE=
115116
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
116117
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
117118
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
118119
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
119120
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
121+
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
120122
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
121123
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
122124
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=

hasura/api.go

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package hasura
22

33
import (
44
"bytes"
5+
"context"
56
"net/http"
67
"net/url"
78
"path"
@@ -41,12 +42,12 @@ func (api *API) buildURL(endpoint string, args map[string]string) (string, error
4142
return u.String(), nil
4243
}
4344

44-
func (api *API) get(endpoint string, args map[string]string) (*http.Response, error) {
45+
func (api *API) get(ctx context.Context, endpoint string, args map[string]string) (*http.Response, error) {
4546
url, err := api.buildURL(endpoint, args)
4647
if err != nil {
4748
return nil, err
4849
}
49-
req, err := http.NewRequest(http.MethodGet, url, nil)
50+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
5051
if err != nil {
5152
return nil, err
5253
}
@@ -55,7 +56,7 @@ func (api *API) get(endpoint string, args map[string]string) (*http.Response, er
5556
}
5657

5758
//nolint
58-
func (api *API) post(endpoint string, args map[string]string, body interface{}, output interface{}) error {
59+
func (api *API) post(ctx context.Context, endpoint string, args map[string]string, body interface{}, output interface{}) error {
5960
url, err := api.buildURL(endpoint, args)
6061
if err != nil {
6162
return err
@@ -66,7 +67,7 @@ func (api *API) post(endpoint string, args map[string]string, body interface{},
6667
return err
6768
}
6869

69-
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(postBody))
70+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(postBody))
7071
if err != nil {
7172
return err
7273
}
@@ -97,8 +98,8 @@ func (api *API) post(endpoint string, args map[string]string, body interface{},
9798
}
9899

99100
// Health
100-
func (api *API) Health() error {
101-
resp, err := api.get("/healthz", nil)
101+
func (api *API) Health(ctx context.Context) error {
102+
resp, err := api.get(ctx, "/healthz", nil)
102103
if err != nil {
103104
return err
104105
}
@@ -111,24 +112,24 @@ func (api *API) Health() error {
111112
}
112113

113114
// ExportMetadata -
114-
func (api *API) ExportMetadata(data *Metadata) (ExportMetadataResponse, error) {
115+
func (api *API) ExportMetadata(ctx context.Context, data *Metadata) (ExportMetadataResponse, error) {
115116
req := request{
116117
Type: "export_metadata",
117118
Args: data,
118119
}
119120
var resp ExportMetadataResponse
120-
err := api.post("/v1/query", nil, req, &resp)
121+
err := api.post(ctx, "/v1/query", nil, req, &resp)
121122
return resp, err
122123
}
123124

124125
// ReplaceMetadata -
125-
func (api *API) ReplaceMetadata(data *Metadata) error {
126+
func (api *API) ReplaceMetadata(ctx context.Context, data *Metadata) error {
126127
req := request{
127128
Type: "replace_metadata",
128129
Args: data,
129130
}
130131
var resp replaceMetadataResponse
131-
if err := api.post("/v1/query", nil, req, &resp); err != nil {
132+
if err := api.post(ctx, "/v1/query", nil, req, &resp); err != nil {
132133
return err
133134
}
134135
if resp.Message == "success" {
@@ -138,19 +139,19 @@ func (api *API) ReplaceMetadata(data *Metadata) error {
138139
}
139140

140141
// TrackTable -
141-
func (api *API) TrackTable(schema, name string) error {
142+
func (api *API) TrackTable(ctx context.Context, schema, name string) error {
142143
req := request{
143144
Type: "track_table",
144145
Args: map[string]string{
145146
"schema": schema,
146147
"name": name,
147148
},
148149
}
149-
return api.post("/v1/query", nil, req, nil)
150+
return api.post(ctx, "/v1/query", nil, req, nil)
150151
}
151152

152153
// CreateSelectPermissions - A select permission is used to restrict access to only the specified columns and rows.
153-
func (api *API) CreateSelectPermissions(table, role string, perm Permission) error {
154+
func (api *API) CreateSelectPermissions(ctx context.Context, table, role string, perm Permission) error {
154155
req := request{
155156
Type: "create_select_permission",
156157
Args: map[string]interface{}{
@@ -159,23 +160,23 @@ func (api *API) CreateSelectPermissions(table, role string, perm Permission) err
159160
"permission": perm,
160161
},
161162
}
162-
return api.post("/v1/query", nil, req, nil)
163+
return api.post(ctx, "/v1/query", nil, req, nil)
163164
}
164165

165166
// DropSelectPermissions -
166-
func (api *API) DropSelectPermissions(table, role string) error {
167+
func (api *API) DropSelectPermissions(ctx context.Context, table, role string) error {
167168
req := request{
168169
Type: "drop_select_permission",
169170
Args: map[string]interface{}{
170171
"table": table,
171172
"role": role,
172173
},
173174
}
174-
return api.post("/v1/query", nil, req, nil)
175+
return api.post(ctx, "/v1/query", nil, req, nil)
175176
}
176177

177178
// CreateRestEndpoint -
178-
func (api *API) CreateRestEndpoint(name, url, queryName, collectionName string) error {
179+
func (api *API) CreateRestEndpoint(ctx context.Context, name, url, queryName, collectionName string) error {
179180
req := request{
180181
Type: "create_rest_endpoint",
181182
Args: map[string]interface{}{
@@ -190,5 +191,5 @@ func (api *API) CreateRestEndpoint(name, url, queryName, collectionName string)
190191
},
191192
},
192193
}
193-
return api.post("/v1/query", nil, req, nil)
194+
return api.post(ctx, "/v1/query", nil, req, nil)
194195
}

hasura/hasura.go

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package hasura
22

33
import (
4+
"context"
45
"fmt"
56
"io/ioutil"
67
"os"
@@ -19,23 +20,39 @@ const (
1920
allowedQueries = "allowed-queries"
2021
)
2122

23+
func checkHealth(ctx context.Context, api *API) {
24+
log.Info("Waiting hasura is up and running")
25+
if err := api.Health(ctx); err != nil {
26+
return
27+
}
28+
ticker := time.NewTicker(5 * time.Second)
29+
for {
30+
select {
31+
case <-ctx.Done():
32+
return
33+
case <-ticker.C:
34+
if err := api.Health(ctx); err != nil {
35+
log.Warn(err)
36+
continue
37+
}
38+
return
39+
}
40+
}
41+
}
42+
2243
// Create - creates hasura models
23-
func Create(hasura config.Hasura, cfg config.Database, views []string, models ...interface{}) error {
44+
func Create(ctx context.Context, hasura config.Hasura, cfg config.Database, views []string, models ...interface{}) error {
2445
api := New(hasura.URL, hasura.Secret)
2546

26-
log.Info("Waiting hasura is up and running")
27-
for err := api.Health(); err != nil; err = api.Health() {
28-
log.Warn(err)
29-
time.Sleep(time.Second * 5)
30-
}
47+
checkHealth(ctx, api)
3148

3249
metadata, err := Generate(hasura, cfg, models...)
3350
if err != nil {
3451
return err
3552
}
3653

3754
log.Info("Fetching existing metadata...")
38-
export, err := api.ExportMetadata(metadata)
55+
export, err := api.ExportMetadata(ctx, metadata)
3956
if err != nil {
4057
return err
4158
}
@@ -57,14 +74,14 @@ func Create(hasura config.Hasura, cfg config.Database, views []string, models ..
5774
}
5875

5976
log.Info("Replacing metadata...")
60-
if err := api.ReplaceMetadata(metadata); err != nil {
77+
if err := api.ReplaceMetadata(ctx, metadata); err != nil {
6178
return err
6279
}
6380

6481
if len(metadata.QueryCollections) > 0 && (hasura.Rest == nil || *hasura.Rest) {
6582
log.Info("Creating REST endpoints...")
6683
for _, query := range metadata.QueryCollections[0].Definition.Queries {
67-
if err := api.CreateRestEndpoint(query.Name, query.Name, query.Name, allowedQueries); err != nil {
84+
if err := api.CreateRestEndpoint(ctx, query.Name, query.Name, query.Name, allowedQueries); err != nil {
6885
if e, ok := err.(APIError); !ok || !e.AlreadyExists() {
6986
return err
7087
}
@@ -74,15 +91,15 @@ func Create(hasura config.Hasura, cfg config.Database, views []string, models ..
7491

7592
log.Info("Tracking views...")
7693
for i := range views {
77-
if err := api.TrackTable("public", views[i]); err != nil {
94+
if err := api.TrackTable(ctx, "public", views[i]); err != nil {
7895
if !strings.Contains(err.Error(), "view/table already tracked") {
7996
return err
8097
}
8198
}
82-
if err := api.DropSelectPermissions(views[i], "user"); err != nil {
99+
if err := api.DropSelectPermissions(ctx, views[i], "user"); err != nil {
83100
log.Warn(err)
84101
}
85-
if err := api.CreateSelectPermissions(views[i], "user", Permission{
102+
if err := api.CreateSelectPermissions(ctx, views[i], "user", Permission{
86103
Limit: hasura.RowsLimit,
87104
AllowAggs: hasura.EnableAggregations,
88105
Columns: Columns{"*"},

node/errors.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
11
package node
22

3-
import "github.com/pkg/errors"
4-
5-
// errors
6-
var (
7-
ErrInvalidResponse = errors.New("invalid response")
3+
import (
4+
"fmt"
85
)
6+
7+
// RequestError -
8+
type RequestError struct {
9+
Code int
10+
Body string
11+
Err error
12+
}
13+
14+
// Error -
15+
func (e RequestError) Error() string {
16+
if e.Err != nil {
17+
return fmt.Sprintf("%s | %s | status code: %d", e.Err.Error(), e.Body, e.Code)
18+
}
19+
return fmt.Sprintf("%s | status code: %d", e.Body, e.Code)
20+
}

0 commit comments

Comments
 (0)