Skip to content

Commit bc8b29e

Browse files
committed
merge packages for common clients
1 parent 36f1885 commit bc8b29e

File tree

7 files changed

+60
-62
lines changed

7 files changed

+60
-62
lines changed

.github/workflows/test.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,18 @@ jobs:
1313
fail-fast: false
1414
matrix:
1515
test:
16-
- path: framework
17-
vm: ubuntu-latest
18-
regex: TestStorageMutations
1916
- path: framework
2017
vm: ubuntu-latest
2118
regex: TestSmoke
22-
- path: framework/prometheus
19+
- path: framework
2320
vm: ubuntu-latest
2421
regex: TestPrometheus
25-
- path: framework/loki
22+
- path: framework
2623
vm: ubuntu-latest
2724
regex: TestLoki
25+
- path: framework
26+
vm: ubuntu-latest
27+
regex: TestStorageMutations
2828
- path: wasp
2929
vm: ubuntu22.04-16cores-64GB # ghv-ignore!
3030
regex: TestSmoke
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ import (
77
"github.com/go-resty/resty/v2"
88
)
99

10-
type Client struct {
10+
type GrafanaClient struct {
1111
resty *resty.Client
1212
}
1313

1414
// NewGrafanaClient initializes a new Grafana client with the specified URL and API key.
15-
func NewGrafanaClient(url, bearerToken string) *Client {
16-
return &Client{
15+
func NewGrafanaClient(url, bearerToken string) *GrafanaClient {
16+
return &GrafanaClient{
1717
resty: resty.New().
1818
SetBaseURL(url).
1919
SetHeader("Authorization", "Bearer "+bearerToken),
@@ -49,7 +49,7 @@ func A(ns, text string, dashboardUIDs []string, from, to *time.Time) Annotation
4949
}
5050

5151
// Annotate adds annotation to all the dashboards, works for both single point annotation with just StartTime and for ranges with StartTime/EndTime
52-
func (c *Client) Annotate(annotation Annotation) ([]PostAnnotationResponse, []*resty.Response, error) {
52+
func (c *GrafanaClient) Annotate(annotation Annotation) ([]PostAnnotationResponse, []*resty.Response, error) {
5353
var results []PostAnnotationResponse
5454
var responses []*resty.Response
5555

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package loki
1+
package framework
22

33
import (
44
"context"
@@ -8,8 +8,6 @@ import (
88
"time"
99

1010
"github.com/go-resty/resty/v2"
11-
12-
"github.com/smartcontractkit/chainlink-testing-framework/framework"
1311
)
1412

1513
// APIError is a custom error type for handling non-200 responses from the Loki API
@@ -45,8 +43,8 @@ type LogEntry struct {
4543
Log string
4644
}
4745

48-
// Client represents a client to interact with Loki for querying logs
49-
type Client struct {
46+
// LokiClient represents a client to interact with Loki for querying logs
47+
type LokiClient struct {
5048
BaseURL string
5149
TenantID string
5250
BasicAuth BasicAuth
@@ -62,9 +60,9 @@ type QueryParams struct {
6260
Limit int
6361
}
6462

65-
// NewQueryClient creates a new Loki client with the given parameters, initializes a logger, and configures Resty with debug mode
66-
func NewQueryClient(baseURL, tenantID string, auth BasicAuth, queryParams QueryParams) *Client {
67-
framework.L.Info().
63+
// NewLokiQueryClient creates a new Loki client with the given parameters, initializes a logger, and configures Resty with debug mode
64+
func NewLokiQueryClient(baseURL, tenantID string, auth BasicAuth, queryParams QueryParams) *LokiClient {
65+
L.Info().
6866
Str("BaseURL", baseURL).
6967
Str("TenantID", tenantID).
7068
Msg("Initializing Loki Client")
@@ -75,7 +73,7 @@ func NewQueryClient(baseURL, tenantID string, auth BasicAuth, queryParams QueryP
7573
restyClient := resty.New().
7674
SetDebug(isDebug)
7775

78-
return &Client{
76+
return &LokiClient{
7977
BaseURL: baseURL,
8078
TenantID: tenantID,
8179
BasicAuth: auth,
@@ -85,9 +83,9 @@ func NewQueryClient(baseURL, tenantID string, auth BasicAuth, queryParams QueryP
8583
}
8684

8785
// QueryRange queries Loki logs based on the query parameters and returns the raw log entries
88-
func (lc *Client) QueryRange(ctx context.Context) ([]LogEntry, error) {
86+
func (lc *LokiClient) QueryRange(ctx context.Context) ([]LogEntry, error) {
8987
// Log request details
90-
framework.L.Info().
88+
L.Info().
9189
Str("Query", lc.QueryParams.Query).
9290
Str("StartTime", lc.QueryParams.StartTime.Format(time.RFC3339Nano)).
9391
Str("EndTime", lc.QueryParams.EndTime.Format(time.RFC3339Nano)).
@@ -117,7 +115,7 @@ func (lc *Client) QueryRange(ctx context.Context) ([]LogEntry, error) {
117115
duration := time.Since(start)
118116

119117
if err != nil {
120-
framework.L.Error().Err(err).Dur("duration", duration).Msg("Error querying Loki")
118+
L.Error().Err(err).Dur("duration", duration).Msg("Error querying Loki")
121119
return nil, err
122120
}
123121

@@ -127,7 +125,7 @@ func (lc *Client) QueryRange(ctx context.Context) ([]LogEntry, error) {
127125
if len(bodySnippet) > 200 {
128126
bodySnippet = bodySnippet[:200] + "..."
129127
}
130-
framework.L.Error().
128+
L.Error().
131129
Int("StatusCode", resp.StatusCode()).
132130
Dur("duration", duration).
133131
Str("ResponseBody", bodySnippet).
@@ -139,40 +137,40 @@ func (lc *Client) QueryRange(ctx context.Context) ([]LogEntry, error) {
139137
}
140138

141139
// Log successful response
142-
framework.L.Info().
140+
L.Info().
143141
Int("StatusCode", resp.StatusCode()).
144142
Dur("duration", duration).
145143
Msg("Successfully queried Loki API")
146144

147145
// Parse the response into the Response struct
148146
var lokiResp Response
149147
if err := json.Unmarshal(resp.Body(), &lokiResp); err != nil {
150-
framework.L.Error().Err(err).Msg("Error decoding response from Loki")
148+
L.Error().Err(err).Msg("Error decoding response from Loki")
151149
return nil, err
152150
}
153151

154152
// Extract log entries from the response
155153
logEntries := lc.extractRawLogEntries(lokiResp)
156154

157155
// Log the number of entries retrieved
158-
framework.L.Info().Int("LogEntries", len(logEntries)).Msg("Successfully retrieved logs from Loki")
156+
L.Info().Int("LogEntries", len(logEntries)).Msg("Successfully retrieved logs from Loki")
159157

160158
return logEntries, nil
161159
}
162160

163161
// extractRawLogEntries processes the Response and returns raw log entries
164-
func (lc *Client) extractRawLogEntries(lokiResp Response) []LogEntry {
162+
func (lc *LokiClient) extractRawLogEntries(lokiResp Response) []LogEntry {
165163
var logEntries []LogEntry
166164

167165
for _, result := range lokiResp.Data.Result {
168166
for _, entry := range result.Values {
169167
if len(entry) != 2 {
170-
framework.L.Error().Interface("Log entry", entry).Msgf("Error parsing log entry. Expected 2 elements, got %d", len(entry))
168+
L.Error().Interface("Log entry", entry).Msgf("Error parsing log entry. Expected 2 elements, got %d", len(entry))
171169
continue
172170
}
173171
var timestamp string
174172
if entry[0] == nil {
175-
framework.L.Error().Msg("Error parsing timestamp. Entry at index 0, that should be a timestamp, is nil")
173+
L.Error().Msg("Error parsing timestamp. Entry at index 0, that should be a timestamp, is nil")
176174
continue
177175
}
178176
if timestampString, ok := entry[0].(string); ok {
@@ -182,7 +180,7 @@ func (lc *Client) extractRawLogEntries(lokiResp Response) []LogEntry {
182180
} else if timestampFloat, ok := entry[0].(float64); ok {
183181
timestamp = fmt.Sprintf("%f", timestampFloat)
184182
} else {
185-
framework.L.Error().Msgf("Error parsing timestamp. Expected string, int, or float64, got %T", entry[0])
183+
L.Error().Msgf("Error parsing timestamp. Expected string, int, or float64, got %T", entry[0])
186184
continue
187185
}
188186
logLine := entry[1].(string)
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package loki
1+
package framework
22

33
import (
44
"context"
@@ -43,7 +43,7 @@ func TestLokiClient_SuccessfulQuery(t *testing.T) {
4343
EndTime: time.Now(),
4444
Limit: 100,
4545
}
46-
lokiClient := NewQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
46+
lokiClient := NewLokiQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
4747
logEntries, err := lokiClient.QueryRange(context.Background())
4848
assert.NoError(t, err)
4949
assert.Len(t, logEntries, 2)
@@ -69,7 +69,7 @@ func TestLokiClient_AuthenticationFailure(t *testing.T) {
6969
EndTime: time.Now(),
7070
Limit: 100,
7171
}
72-
lokiClient := NewQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
72+
lokiClient := NewLokiQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
7373
logEntries, err := lokiClient.QueryRange(context.Background())
7474
assert.Nil(t, logEntries)
7575
assert.Error(t, err)
@@ -99,7 +99,7 @@ func TestLokiClient_InternalServerError(t *testing.T) {
9999
EndTime: time.Now(),
100100
Limit: 100,
101101
}
102-
lokiClient := NewQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
102+
lokiClient := NewLokiQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
103103
logEntries, err := lokiClient.QueryRange(context.Background())
104104
assert.Nil(t, logEntries)
105105
assert.Error(t, err)
@@ -143,7 +143,7 @@ func TestLokiClient_DebugMode(t *testing.T) {
143143
EndTime: time.Now(),
144144
Limit: 100,
145145
}
146-
lokiClient := NewQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
146+
lokiClient := NewLokiQueryClient(mockServer.URL, "test-tenant", auth, queryParams)
147147
logEntries, err := lokiClient.QueryRange(context.Background())
148148
assert.NoError(t, err)
149149
assert.Len(t, logEntries, 2)
Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package prometheus
1+
package framework
22

33
import (
44
"encoding/json"
@@ -10,23 +10,23 @@ import (
1010
"github.com/go-resty/resty/v2"
1111
)
1212

13-
// QueryClient is a client for querying Prometheus metrics
14-
type QueryClient struct {
13+
// PrometheusQueryClient is a client for querying Prometheus metrics
14+
type PrometheusQueryClient struct {
1515
client *resty.Client
1616
baseURL string
1717
}
1818

19-
// NewQueryClient creates a new QueryClient
20-
func NewQueryClient(baseURL string) *QueryClient {
19+
// NewPrometheusQueryClient creates a new PrometheusQueryClient
20+
func NewPrometheusQueryClient(baseURL string) *PrometheusQueryClient {
2121
isDebug := os.Getenv("RESTY_DEBUG") == "true"
22-
return &QueryClient{
22+
return &PrometheusQueryClient{
2323
client: resty.New().SetDebug(isDebug),
2424
baseURL: strings.TrimSuffix(baseURL, "/"),
2525
}
2626
}
2727

28-
// QueryResponse represents the response from Prometheus API
29-
type QueryResponse struct {
28+
// PrometheusQueryResponse represents the response from Prometheus API
29+
type PrometheusQueryResponse struct {
3030
Status string `json:"status"`
3131
Data struct {
3232
ResultType string `json:"resultType"`
@@ -58,7 +58,7 @@ type QueryRangeParams struct {
5858
}
5959

6060
// Query executes an instant query against the Prometheus API
61-
func (p *QueryClient) Query(query string, timestamp time.Time) (*QueryResponse, error) {
61+
func (p *PrometheusQueryClient) Query(query string, timestamp time.Time) (*PrometheusQueryResponse, error) {
6262
url := fmt.Sprintf("%s/api/v1/query", p.baseURL)
6363
resp, err := p.client.R().
6464
SetQueryParams(map[string]string{
@@ -72,7 +72,7 @@ func (p *QueryClient) Query(query string, timestamp time.Time) (*QueryResponse,
7272
if resp.StatusCode() != 200 {
7373
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode())
7474
}
75-
var result QueryResponse
75+
var result PrometheusQueryResponse
7676
if err := json.Unmarshal(resp.Body(), &result); err != nil {
7777
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
7878
}
@@ -83,7 +83,7 @@ func (p *QueryClient) Query(query string, timestamp time.Time) (*QueryResponse,
8383
}
8484

8585
// QueryRange executes a range query against the Prometheus API
86-
func (p *QueryClient) QueryRange(params QueryRangeParams) (*QueryRangeResponse, error) {
86+
func (p *PrometheusQueryClient) QueryRange(params QueryRangeParams) (*QueryRangeResponse, error) {
8787
url := fmt.Sprintf("%s/api/v1/query_range", p.baseURL)
8888
resp, err := p.client.R().
8989
SetQueryParams(map[string]string{
@@ -109,9 +109,9 @@ func (p *QueryClient) QueryRange(params QueryRangeParams) (*QueryRangeResponse,
109109
return &result, nil
110110
}
111111

112-
// ToLabelsMap converts QueryResponse.Data.Result into a map where keys are
112+
// ToLabelsMap converts PrometheusQueryResponse.Data.Result into a map where keys are
113113
// metric labels in "k:v" format and values are slices of all values with that label
114-
func ToLabelsMap(response *QueryResponse) map[string][]interface{} {
114+
func ToLabelsMap(response *PrometheusQueryResponse) map[string][]interface{} {
115115
resultMap := make(map[string][]interface{})
116116
for _, res := range response.Data.Result {
117117
for k, v := range res.Metric {

0 commit comments

Comments
 (0)