Skip to content

Commit 1449c13

Browse files
authored
[TT-1722] Update WASP docs (#1340)
1 parent 989c0a5 commit 1449c13

21 files changed

+259
-84
lines changed

wasp/alert.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ type AlertChecker struct {
2323
grafanaClient *grafana.Client
2424
}
2525

26+
// NewAlertChecker creates a new AlertChecker using Grafana configurations from environment variables.
27+
// It retrieves GRAFANA_URL and GRAFANA_TOKEN, ensuring they are set.
28+
// Use this function to set up alert checking in tests.
2629
func NewAlertChecker(t *testing.T) *AlertChecker {
2730
url := os.Getenv("GRAFANA_URL")
2831
if url == "" {
@@ -43,7 +46,8 @@ func NewAlertChecker(t *testing.T) *AlertChecker {
4346
}
4447
}
4548

46-
// AnyAlerts check if any alerts with dashboardUUID have been raised
49+
// AnyAlerts retrieves alert groups from Grafana and checks for alerts matching the specified dashboard UUID and requirement label value.
50+
// It returns the matching alert groups, enabling users to identify and respond to specific alert conditions.
4751
func (m *AlertChecker) AnyAlerts(dashboardUUID, requirementLabelValue string) ([]grafana.AlertGroupsResponse, error) {
4852
raised := false
4953
defer func() {
@@ -75,7 +79,9 @@ func (m *AlertChecker) AnyAlerts(dashboardUUID, requirementLabelValue string) ([
7579
return alertGroups, nil
7680
}
7781

78-
// CheckDashobardAlerts checks for alerts in the given dashboardUUIDs between from and to times
82+
// CheckDashboardAlerts retrieves alert annotations from a Grafana dashboard within the specified time range.
83+
// It returns the sorted alerts and an error if any alert is in the alerting state.
84+
// Use it to verify the status of dashboard alerts after a run.
7985
func CheckDashboardAlerts(grafanaClient *grafana.Client, from, to time.Time, dashboardUID string) ([]grafana.Annotation, error) {
8086
annotationType := "alert"
8187
alerts, _, err := grafanaClient.GetAnnotations(grafana.AnnotationsQueryParams{

wasp/buffer.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@ type SliceBuffer[T any] struct {
77
Data []T
88
}
99

10-
// NewSliceBuffer creates new limited capacity slice
10+
// NewSliceBuffer creates a new SliceBuffer with the specified capacity.
11+
// It provides an efficient way to store and manage a fixed number of elements,
12+
// enabling optimized access and manipulation in concurrent and decentralized applications.
1113
func NewSliceBuffer[T any](cap int) *SliceBuffer[T] {
1214
return &SliceBuffer[T]{Capacity: cap, Data: make([]T, 0)}
1315
}
1416

15-
// Append appends T if len <= cap, overrides old data otherwise
17+
// Append adds an element to the SliceBuffer. When the buffer reaches its capacity, it overwrites the oldest item.
18+
// This function is useful for maintaining a fixed-size, circular collection of elements.
1619
func (m *SliceBuffer[T]) Append(s T) {
1720
if m.Idx >= m.Capacity {
1821
m.Idx = 0

wasp/cmd.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,16 @@ import (
99
"github.com/rs/zerolog/log"
1010
)
1111

12-
// ExecCmd executes os command, logging both streams
12+
// ExecCmd executes the provided command string and logs its output.
13+
// It returns an error if the command fails to run or exits with a non-zero status.
1314
func ExecCmd(command string) error {
1415
return ExecCmdWithStreamFunc(command, func(m string) {
1516
log.Info().Str("Text", m).Msg("Command output")
1617
})
1718
}
1819

19-
// readStdPipe continuously read a pipe from the command
20+
// readStdPipe reads lines from the provided pipe and sends each line to streamFunc.
21+
// It is used to handle streaming output from command execution, such as stdout and stderr.
2022
func readStdPipe(pipe io.ReadCloser, streamFunc func(string)) {
2123
scanner := bufio.NewScanner(pipe)
2224
scanner.Split(bufio.ScanLines)
@@ -28,7 +30,8 @@ func readStdPipe(pipe io.ReadCloser, streamFunc func(string)) {
2830
}
2931
}
3032

31-
// ExecCmdWithStreamFunc executes command with stream function
33+
// ExecCmdWithStreamFunc runs the specified command and streams its output and error lines
34+
// to the provided outputFunction. It enables real-time handling of command execution output.
3235
func ExecCmdWithStreamFunc(command string, outputFunction func(string)) error {
3336
c := strings.Split(command, " ")
3437
cmd := exec.Command(c[0], c[1:]...)

wasp/dashboard/cmd/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"github.com/smartcontractkit/chainlink-testing-framework/wasp/dashboard"
55
)
66

7+
// main creates and deploys a default dashboard using environment variables for configuration.
8+
// It sets up the dashboard without extensions or non-functional requirements, enabling straightforward deployment.
79
func main() {
810
// just default dashboard, no NFRs, no dashboard extensions
911
// see examples/alerts.go for an example extension

wasp/dashboard/dashboard.go

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ type Dashboard struct {
5656
builder dashboard.Builder
5757
}
5858

59-
// NewDashboard creates new dashboard
59+
// NewDashboard initializes a Dashboard with provided alerts and options, using environment variables for configuration. It prepares the dashboard for deployment and returns the instance or an error if setup fails.
6060
func NewDashboard(reqs []WaspAlert, opts []dashboard.Option) (*Dashboard, error) {
6161
name := os.Getenv("DASHBOARD_NAME")
6262
if name == "" {
@@ -93,7 +93,8 @@ func NewDashboard(reqs []WaspAlert, opts []dashboard.Option) (*Dashboard, error)
9393
return dash, nil
9494
}
9595

96-
// Deploy deploys this dashboard to some Grafana folder
96+
// Deploy uploads the Dashboard to Grafana, creating the folder if necessary.
97+
// It returns the deployed grabana.Dashboard and any encountered error.
9798
func (m *Dashboard) Deploy() (*grabana.Dashboard, error) {
9899
ctx := context.Background()
99100
client := grabana.NewClient(&http.Client{}, m.GrafanaURL, grabana.WithAPIToken(m.GrafanaToken))
@@ -105,7 +106,8 @@ func (m *Dashboard) Deploy() (*grabana.Dashboard, error) {
105106
return client.UpsertDashboard(ctx, fo, m.builder)
106107
}
107108

108-
// defaultStatWidget creates default Stat widget
109+
// defaultStatWidget creates a standard dashboard stat widget using the specified name, datasource, Prometheus target, and legend.
110+
// It is used to display consistent metrics within dashboard rows.
109111
func defaultStatWidget(name, datasourceName, target, legend string) row.Option {
110112
return row.WithStat(
111113
name,
@@ -120,7 +122,8 @@ func defaultStatWidget(name, datasourceName, target, legend string) row.Option {
120122
)
121123
}
122124

123-
// defaultLastValueAlertWidget creates default last value alert
125+
// defaultLastValueAlertWidget generates a timeseries.Option for alerting using a WaspAlert.
126+
// It returns the custom alert if provided, otherwise configures a default last-value alert for consistent monitoring in dashboards.
124127
func defaultLastValueAlertWidget(a WaspAlert) timeseries.Option {
125128
if a.CustomAlert != nil {
126129
return a.CustomAlert
@@ -143,7 +146,9 @@ func defaultLastValueAlertWidget(a WaspAlert) timeseries.Option {
143146
)
144147
}
145148

146-
// defaultLabelValuesVar creates a dashboard variable with All/Multiple options
149+
// defaultLabelValuesVar generates a dashboard variable for the specified name and datasource.
150+
// It enables multiple selections, includes an "All" option, and sorts label values in ascending numerical order.
151+
// Use it to create consistent query variables for dashboard filtering.
147152
func defaultLabelValuesVar(name, datasourceName string) dashboard.Option {
148153
return dashboard.VariableAsQuery(
149154
name,
@@ -155,7 +160,8 @@ func defaultLabelValuesVar(name, datasourceName string) dashboard.Option {
155160
)
156161
}
157162

158-
// timeSeriesWithAlerts creates timeseries graphs per alert + definition of alert
163+
// timeSeriesWithAlerts creates dashboard options for each WaspAlert, configuring time series panels with alert settings.
164+
// Use it to add alert-specific rows to a dashboard based on provided alert definitions.
159165
func timeSeriesWithAlerts(datasourceName string, alertDefs []WaspAlert) []dashboard.Option {
160166
dashboardOpts := make([]dashboard.Option, 0)
161167
for _, a := range alertDefs {
@@ -189,6 +195,9 @@ func timeSeriesWithAlerts(datasourceName string, alertDefs []WaspAlert) []dashbo
189195
return dashboardOpts
190196
}
191197

198+
// AddVariables generates standard dashboard options for common label variables using the provided datasourceName.
199+
// It includes variables like go_test_name, gen_name, branch, commit, and call_group.
200+
// Use this to easily incorporate these variables into your dashboard configuration.
192201
func AddVariables(datasourceName string) []dashboard.Option {
193202
opts := []dashboard.Option{
194203
defaultLabelValuesVar("go_test_name", datasourceName),
@@ -200,7 +209,8 @@ func AddVariables(datasourceName string) []dashboard.Option {
200209
return opts
201210
}
202211

203-
// dashboard is internal appendable representation of all Dashboard widgets
212+
// dashboard generates dashboard configuration options based on the specified datasource and alert requirements.
213+
// It is used to set up panels and settings when building a new dashboard.
204214
func (m *Dashboard) dashboard(datasourceName string, requirements []WaspAlert) []dashboard.Option {
205215
panelQuery := map[string]string{
206216
"branch": `=~"${branch:pipe}"`,
@@ -221,7 +231,8 @@ func (m *Dashboard) dashboard(datasourceName string, requirements []WaspAlert) [
221231
return defaultOpts
222232
}
223233

224-
// Build creates dashboard instance
234+
// Build initializes the Dashboard with the specified name, data source, and alert requirements.
235+
// It prepares the dashboard builder for further configuration and usage.
225236
func (m *Dashboard) Build(dashboardName, datasourceName string, requirements []WaspAlert) error {
226237
b, err := dashboard.New(
227238
dashboardName,
@@ -234,12 +245,14 @@ func (m *Dashboard) Build(dashboardName, datasourceName string, requirements []W
234245
return nil
235246
}
236247

237-
// JSON render dashboard as JSON
248+
// JSON serializes the Dashboard into indented JSON format.
249+
// It provides a human-readable representation, useful for exporting or inspecting the dashboard.
238250
func (m *Dashboard) JSON() ([]byte, error) {
239251
return m.builder.MarshalIndentJSON()
240252
}
241253

242-
// InlineLokiAlertParams is specific params for predefined alerts for wasp dashboard
254+
// InlineLokiAlertParams generates a Loki query string based on the alert type, test name, and generator name.
255+
// It is used to configure specific alert conditions for monitoring test metrics in dashboards.
243256
func InlineLokiAlertParams(queryType, testName, genName string) string {
244257
switch queryType {
245258
case AlertTypeQuantile99:
@@ -262,6 +275,8 @@ max_over_time({go_test_name="%s", test_data_type=~"stats", gen_name="%s"}
262275
}
263276
}
264277

278+
// WASPLoadStatsRow creates a "WASP Load Stats" dashboard row with widgets displaying real-time and total load metrics.
279+
// It utilizes the provided data source and query parameters to configure the relevant statistics for monitoring.
265280
func WASPLoadStatsRow(dataSource string, query map[string]string) dashboard.Option {
266281
queryString := ""
267282
for key, value := range query {
@@ -384,6 +399,9 @@ func WASPLoadStatsRow(dataSource string, query map[string]string) dashboard.Opti
384399
)
385400
}
386401

402+
// WASPDebugDataRow returns a dashboard.Option containing a row with WASP debug metrics and logs.
403+
// It uses the provided data source and query parameters.
404+
// Use this function to include detailed debug information in your dashboard.
387405
func WASPDebugDataRow(dataSource string, query map[string]string, collapse bool) dashboard.Option {
388406
queryString := ""
389407
for key, value := range query {

wasp/dashboard/panels.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import (
77
"github.com/K-Phoen/grabana/timeseries/axis"
88
)
99

10+
// RPSPanel creates a time series panel displaying responses per second
11+
// grouped by generator and call group. It is used to monitor
12+
// response rates in the dashboard.
1013
func RPSPanel(dataSource string, query map[string]string) row.Option {
1114
queryString := ""
1215
for key, value := range query {
@@ -35,6 +38,8 @@ func RPSPanel(dataSource string, query map[string]string) row.Option {
3538
)
3639
}
3740

41+
// RPSVUPerScheduleSegmentsPanel creates a dashboard panel displaying Requests Per Second and Virtual Users segmented by schedule.
42+
// It is used to monitor performance metrics over time for different test configurations.
3843
func RPSVUPerScheduleSegmentsPanel(dataSource string, query map[string]string) row.Option {
3944
queryString := ""
4045
for key, value := range query {

wasp/gun_http_mock.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ type MockHTTPGun struct {
1414
Data []string
1515
}
1616

17-
// NewHTTPMockGun create an HTTP mock gun
17+
// NewHTTPMockGun initializes a MockHTTPGun with the given configuration.
18+
// It sets up the HTTP client and data storage, enabling simulated HTTP interactions for testing.
1819
func NewHTTPMockGun(cfg *MockHTTPGunConfig) *MockHTTPGun {
1920
return &MockHTTPGun{
2021
client: resty.New(),
@@ -23,7 +24,8 @@ func NewHTTPMockGun(cfg *MockHTTPGunConfig) *MockHTTPGun {
2324
}
2425
}
2526

26-
// Call implements example gun call, assertions on response bodies should be done here
27+
// Call sends an HTTP GET request to the configured target URL and returns the response data.
28+
// It is used to simulate HTTP calls for testing or load generation purposes.
2729
func (m *MockHTTPGun) Call(l *Generator) *Response {
2830
var result map[string]interface{}
2931
r, err := m.client.R().

wasp/gun_sleep_mock.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,18 @@ type MockGun struct {
2323
Data []string
2424
}
2525

26-
// NewMockGun create a mock gun
26+
// NewMockGun creates a new MockGun instance using the provided configuration.
27+
// It is used to simulate gun behavior for testing or development purposes.
2728
func NewMockGun(cfg *MockGunConfig) *MockGun {
2829
return &MockGun{
2930
cfg: cfg,
3031
Data: make([]string, 0),
3132
}
3233
}
3334

34-
// Call implements example gun call, assertions on response bodies should be done here
35+
// Call simulates a request to the Generator.
36+
// Depending on MockGun's configuration, it may succeed, fail, or timeout,
37+
// allowing testing of various response scenarios.
3538
func (m *MockGun) Call(l *Generator) *Response {
3639
if m.cfg.InternalStop {
3740
l.Stop()
@@ -54,6 +57,8 @@ func (m *MockGun) Call(l *Generator) *Response {
5457
return &Response{Data: "successCallData"}
5558
}
5659

60+
// convertResponsesData extracts successful and failed response data from the Generator.
61+
// It returns a slice of successful response strings, OK responses, and failed responses.
5762
func convertResponsesData(g *Generator) ([]string, []*Response, []*Response) {
5863
g.responsesData.okDataMu.Lock()
5964
defer g.responsesData.okDataMu.Unlock()

wasp/http_server_mock.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,24 @@ type HTTPMockServer struct {
1818
Sleep time.Duration
1919
}
2020

21+
// Run starts the HTTPMockServer in a separate goroutine.
22+
// It enables the server to handle incoming HTTP requests concurrently.
2123
func (s *HTTPMockServer) Run() {
2224
go func() {
2325
//nolint
2426
_ = s.srv.Run()
2527
}()
2628
}
2729

30+
// URL returns the base URL of the HTTPMockServer.
31+
// Use it to configure clients to send requests to the mock server during testing.
2832
func (s *HTTPMockServer) URL() string {
2933
return "http://localhost:8080/1"
3034
}
3135

36+
// NewHTTPMockServer initializes an HTTP mock server with configurable latencies and response codes.
37+
// If cfg is nil, default settings are applied.
38+
// Use it to simulate HTTP endpoints for testing purposes.
3239
func NewHTTPMockServer(cfg *HTTPMockServerConfig) *HTTPMockServer {
3340
if cfg == nil {
3441
cfg = &HTTPMockServerConfig{

wasp/k8s.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ type K8sClient struct {
2323
RESTConfig *rest.Config
2424
}
2525

26-
// GetLocalK8sDeps get local k8s context config
26+
// GetLocalK8sDeps retrieves the local Kubernetes Clientset and REST configuration.
27+
// It is used to initialize a Kubernetes client for interacting with the cluster.
2728
func GetLocalK8sDeps() (*kubernetes.Clientset, *rest.Config, error) {
2829
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
2930
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
@@ -38,7 +39,8 @@ func GetLocalK8sDeps() (*kubernetes.Clientset, *rest.Config, error) {
3839
return k8sClient, k8sConfig, nil
3940
}
4041

41-
// NewK8sClient creates a new k8s client with a REST config
42+
// NewK8sClient initializes and returns a new K8sClient for interacting with the local Kubernetes cluster.
43+
// It is used to perform operations such as synchronizing groups and managing cluster profiles.
4244
func NewK8sClient() *K8sClient {
4345
cs, cfg, err := GetLocalK8sDeps()
4446
if err != nil {
@@ -50,18 +52,27 @@ func NewK8sClient() *K8sClient {
5052
}
5153
}
5254

55+
// jobPods returns a list of pods in the specified namespace matching the sync label.
56+
// It is used to track and manage job-related pods within Kubernetes environments.
5357
func (m *K8sClient) jobPods(ctx context.Context, nsName, syncLabel string) (*v1.PodList, error) {
5458
return m.ClientSet.CoreV1().Pods(nsName).List(ctx, metaV1.ListOptions{LabelSelector: syncSelector(syncLabel)})
5559
}
5660

61+
// jobs retrieves the list of Kubernetes jobs within the specified namespace
62+
// that match the provided synchronization label.
63+
// It returns a JobList and an error if the operation fails.
5764
func (m *K8sClient) jobs(ctx context.Context, nsName, syncLabel string) (*batchV1.JobList, error) {
5865
return m.ClientSet.BatchV1().Jobs(nsName).List(ctx, metaV1.ListOptions{LabelSelector: syncSelector(syncLabel)})
5966
}
6067

68+
// syncSelector formats a sync label into a label selector string.
69+
// It is used to filter Kubernetes jobs and pods based on the specified synchronization label.
6170
func syncSelector(s string) string {
6271
return fmt.Sprintf("sync=%s", s)
6372
}
6473

74+
// removeJobs deletes all jobs in the given JobList within the specified namespace.
75+
// It is used to clean up job resources after they have completed or failed.
6576
func (m *K8sClient) removeJobs(ctx context.Context, nsName string, jobs *batchV1.JobList) error {
6677
log.Info().Msg("Removing jobs")
6778
for _, j := range jobs.Items {
@@ -75,6 +86,8 @@ func (m *K8sClient) removeJobs(ctx context.Context, nsName string, jobs *batchV1
7586
return nil
7687
}
7788

89+
// waitSyncGroup waits until the specified namespace has jobNum pods with the given syncLabel running.
90+
// It ensures that all required pods are synchronized and operational before proceeding.
7891
func (m *K8sClient) waitSyncGroup(ctx context.Context, nsName string, syncLabel string, jobNum int) error {
7992
outer:
8093
for {
@@ -97,7 +110,8 @@ outer:
97110
}
98111
}
99112

100-
// TrackJobs tracks both jobs and their pods until they succeed or fail
113+
// TrackJobs monitors Kubernetes jobs in the specified namespace and label selector until the desired number succeed or a failure occurs.
114+
// It optionally removes jobs upon completion based on the keepJobs flag.
101115
func (m *K8sClient) TrackJobs(ctx context.Context, nsName, syncLabel string, jobNum int, keepJobs bool) error {
102116
log.Debug().Str("LabelSelector", syncSelector(syncLabel)).Msg("Searching for jobs/pods")
103117
for {

0 commit comments

Comments
 (0)