Skip to content

Commit f18c901

Browse files
committed
try docs generated by the new tool
1 parent 0e411f1 commit f18c901

19 files changed

+488
-77
lines changed

wasp/alert.go

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

26+
// NewAlertChecker initializes a new AlertChecker instance by retrieving the Grafana URL and API token from the environment variables.
27+
// It panics if either the GRAFANA_URL or GRAFANA_TOKEN environment variable is not set, ensuring that the necessary configuration is available.
28+
// The function creates a Grafana client using the provided URL and API token, and sets up the AlertChecker with a default requirement label key and a logger.
29+
// It returns a pointer to the newly created AlertChecker instance, which can be used for checking alerts in Grafana.
2630
func NewAlertChecker(t *testing.T) *AlertChecker {
2731
url := os.Getenv("GRAFANA_URL")
2832
if url == "" {
@@ -43,7 +47,12 @@ func NewAlertChecker(t *testing.T) *AlertChecker {
4347
}
4448
}
4549

46-
// AnyAlerts check if any alerts with dashboardUUID have been raised
50+
// AnyAlerts checks for alerts associated with a specific dashboard and requirement label.
51+
// It retrieves alert groups from the Grafana Alert Manager and scans through the alerts to determine
52+
// if any alert matches the provided dashboard UUID and requirement label value.
53+
// If an alert is found, it logs the alert details and marks that an alert has been raised.
54+
// The function returns the list of alert groups and any error encountered during the retrieval process.
55+
// If the test context is active and an alert was raised, it will mark the test as failed.
4756
func (m *AlertChecker) AnyAlerts(dashboardUUID, requirementLabelValue string) ([]grafana.AlertGroupsResponse, error) {
4857
raised := false
4958
defer func() {
@@ -75,7 +84,11 @@ func (m *AlertChecker) AnyAlerts(dashboardUUID, requirementLabelValue string) ([
7584
return alertGroups, nil
7685
}
7786

78-
// CheckDashobardAlerts checks for alerts in the given dashboardUUIDs between from and to times
87+
// CheckDashboardAlerts retrieves annotations of type "alert" from a specified Grafana dashboard within a given time range.
88+
// It returns a slice of annotations and an error if any occurred during the retrieval process.
89+
// If the retrieval is successful, the function sorts the annotations by time from oldest to newest and checks if any alerts are in an "alerting" state.
90+
// If at least one alert is found to be firing, it returns the annotations along with an error indicating that an alert was firing.
91+
// If no alerts are firing, it returns the annotations with a nil error.
7992
func CheckDashboardAlerts(grafanaClient *grafana.Client, from, to time.Time, dashboardUID string) ([]grafana.Annotation, error) {
8093
annotationType := "alert"
8194
alerts, _, err := grafanaClient.GetAnnotations(grafana.AnnotationsQueryParams{

wasp/buffer.go

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

10-
// NewSliceBuffer creates new limited capacity slice
10+
// NewSliceBuffer initializes a new SliceBuffer with the specified capacity.
11+
// It returns a pointer to the newly created SliceBuffer, which contains an empty slice of the specified type.
12+
// This function is useful for creating a buffer that can hold elements of a generic type T, allowing for dynamic data storage.
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 a new element to the SliceBuffer. If the buffer has reached its capacity,
18+
// it will overwrite the oldest element. The function maintains the current index for
19+
// the next insertion, wrapping around when the end of the buffer is reached.
20+
// This allows for efficient storage of a fixed-size collection of elements.
1621
func (m *SliceBuffer[T]) Append(s T) {
1722
if m.Idx >= m.Capacity {
1823
m.Idx = 0

wasp/cluster.go

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ type ClusterConfig struct {
6868
tmpHelmFilePath string
6969
}
7070

71+
// Defaults initializes default values for the Helm configuration and related paths in the ClusterConfig.
72+
// It sets the namespace, sync identifier, deployment timeout, resource requests and limits,
73+
// and ensures that default chart, Dockerfile, Docker ignore file, and build script are created
74+
// if their respective paths are not provided.
75+
// If any errors occur during file writing or path resolution, it returns the error encountered.
76+
// This function is typically called during the creation of a new ClusterProfile to ensure
77+
// that the configuration is complete and valid before proceeding with further operations.
7178
func (m *ClusterConfig) Defaults(a int) error {
7279
// TODO: will it be more clear if we move Helm values to a struct
7380
// TODO: or should it be like that for extensibility of a chart without reflection?
@@ -132,6 +139,10 @@ func (m *ClusterConfig) Defaults(a int) error {
132139
return nil
133140
}
134141

142+
// Validate checks the ClusterConfig for required fields.
143+
// It ensures that the Namespace is not empty and that the "jobs" key in HelmValues is set.
144+
// If any of these validations fail, it returns an error detailing the missing fields.
145+
// If all validations pass, it returns nil, indicating that the configuration is valid.
135146
func (m *ClusterConfig) Validate() (err error) {
136147
if m.Namespace == "" {
137148
err = errors.Join(err, ErrNoNamespace)
@@ -142,7 +153,10 @@ func (m *ClusterConfig) Validate() (err error) {
142153
return
143154
}
144155

145-
// parseECRImageURI parses the ECR image URI and returns its components
156+
// parseECRImageURI parses an Amazon ECR image URI into its constituent parts: registry, repository, and tag.
157+
// It expects the URI to be in the format ${registry}/${repo}:${tag}.
158+
// If the format is invalid, it returns an error indicating the expected format.
159+
// On success, it returns the extracted registry, repository, and tag as strings, along with a nil error.
146160
func parseECRImageURI(uri string) (registry, repo, tag string, err error) {
147161
re := regexp.MustCompile(`^([^/]+)/([^:]+):(.+)$`)
148162
matches := re.FindStringSubmatch(uri)
@@ -160,7 +174,11 @@ type ClusterProfile struct {
160174
Cancel context.CancelFunc
161175
}
162176

163-
// NewClusterProfile creates new cluster profile
177+
// NewClusterProfile creates a new ClusterProfile instance based on the provided ClusterConfig.
178+
// It validates the configuration and sets default values before initializing the ClusterProfile.
179+
// If the configuration includes an update for the image, it builds and pushes the image as part of the initialization process.
180+
// The function returns a pointer to the newly created ClusterProfile and an error if any issues occur during the process.
181+
// If the configuration is invalid or if there are errors in parsing the timeout duration, an appropriate error is returned.
164182
func NewClusterProfile(cfg *ClusterConfig) (*ClusterProfile, error) {
165183
if err := cfg.Validate(); err != nil {
166184
return nil, err
@@ -186,6 +204,12 @@ func NewClusterProfile(cfg *ClusterConfig) (*ClusterProfile, error) {
186204
return cp, nil
187205
}
188206

207+
// buildAndPushImage builds a Docker image using the specified configuration and pushes it to a container registry.
208+
// It constructs the command to execute based on the provided build script, Dockerfile, and context path,
209+
// along with the image tag, registry, and repository details parsed from the image URI.
210+
// If any errors occur during the parsing of the image URI or the execution of the build command,
211+
// the function returns the corresponding error.
212+
// On successful execution, it returns nil.
189213
func (m *ClusterProfile) buildAndPushImage() error {
190214
registry, repo, tag, err := parseECRImageURI(m.cfg.HelmValues["image"])
191215
if err != nil {
@@ -204,6 +228,11 @@ func (m *ClusterProfile) buildAndPushImage() error {
204228
return ExecCmd(cmd)
205229
}
206230

231+
// deployHelm installs a Helm chart using the specified test name and configuration settings.
232+
// It constructs a command to execute the Helm install operation, incorporating any Helm values
233+
// provided in the configuration. The function also ensures that the temporary Helm file is
234+
// removed after execution. If the command execution fails, it returns an error indicating
235+
// the failure of the deployment process.
207236
func (m *ClusterProfile) deployHelm(testName string) error {
208237
//nolint
209238
defer os.Remove(m.cfg.tmpHelmFilePath)
@@ -218,7 +247,12 @@ func (m *ClusterProfile) deployHelm(testName string) error {
218247
return ExecCmd(cmd.String())
219248
}
220249

221-
// Run starts a new test
250+
// Run executes the deployment of a Helm chart and tracks the associated jobs.
251+
// It generates a unique test name, ensuring it starts with a letter, and then
252+
// calls the deployHelm method to initiate the deployment. If the deployment
253+
// is successful, it retrieves the number of jobs from the configuration and
254+
// invokes the TrackJobs method to monitor the job status.
255+
// The function returns an error if any step in the process fails.
222256
func (m *ClusterProfile) Run() error {
223257
testName := uuid.NewString()[0:8]
224258
tn := []rune(testName)

wasp/cmd.go

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

12-
// ExecCmd executes os command, logging both streams
12+
// ExecCmd executes a command in the shell and logs its output.
13+
// It takes a command string as input and returns an error if the command fails to execute or if there are issues with the output streams.
14+
// The command's standard output and standard error are processed by a logging function that captures and logs the output in real-time.
15+
// If the command completes successfully, ExecCmd returns nil; otherwise, it returns an error detailing the failure.
1316
func ExecCmd(command string) error {
1417
return ExecCmdWithStreamFunc(command, func(m string) {
1518
log.Info().Str("Text", m).Msg("Command output")
1619
})
1720
}
1821

19-
// readStdPipe continuously read a pipe from the command
22+
// readStdPipe reads lines from the provided io.ReadCloser pipe and passes each line to the specified streamFunc.
23+
// If streamFunc is nil, the lines will be ignored. The function continues reading until the pipe is closed or an error occurs.
24+
// It is typically used to handle output from command execution in a streaming manner.
2025
func readStdPipe(pipe io.ReadCloser, streamFunc func(string)) {
2126
scanner := bufio.NewScanner(pipe)
2227
scanner.Split(bufio.ScanLines)
@@ -28,7 +33,11 @@ func readStdPipe(pipe io.ReadCloser, streamFunc func(string)) {
2833
}
2934
}
3035

31-
// ExecCmdWithStreamFunc executes command with stream function
36+
// ExecCmdWithStreamFunc executes a command specified by the command string and streams its output
37+
// to the provided outputFunction. The outputFunction is called with each line of output from both
38+
// standard output and standard error streams. The function returns an error if there is an issue
39+
// starting the command, creating pipes, or waiting for the command to complete.
40+
// If the command executes successfully, it will return nil.
3241
func ExecCmdWithStreamFunc(command string, outputFunction func(string)) error {
3342
c := strings.Split(command, " ")
3443
cmd := exec.Command(c[0], c[1:]...)

wasp/gun_http_mock.go

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

17-
// NewHTTPMockGun create an HTTP mock gun
17+
// NewHTTPMockGun initializes a new instance of MockHTTPGun using the provided configuration.
18+
// It sets up an HTTP client and prepares an empty slice to store data.
19+
// The returned MockHTTPGun can be used for testing purposes, simulating HTTP interactions without making real network calls.
1820
func NewHTTPMockGun(cfg *MockHTTPGunConfig) *MockHTTPGun {
1921
return &MockHTTPGun{
2022
client: resty.New(),
@@ -23,7 +25,11 @@ func NewHTTPMockGun(cfg *MockHTTPGunConfig) *MockHTTPGun {
2325
}
2426
}
2527

26-
// Call implements example gun call, assertions on response bodies should be done here
28+
// Call executes an HTTP GET request to the target URL configured in the MockHTTPGun.
29+
// It returns a Response containing the result of the request. If the request encounters
30+
// an error or does not return a status of "200 OK", the Response will include the error
31+
// message. If the request is successful, the Response will contain the data retrieved
32+
// from the target URL.
2733
func (m *MockHTTPGun) Call(l *Generator) *Response {
2834
var result map[string]interface{}
2935
r, err := m.client.R().

wasp/gun_sleep_mock.go

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

26-
// NewMockGun create a mock gun
26+
// NewMockGun creates and returns a new instance of MockGun initialized with the provided configuration.
27+
// It sets up the internal data structure to hold string data, starting with an empty slice.
28+
// The returned MockGun can be used to simulate gun-related operations in a testing environment.
2729
func NewMockGun(cfg *MockGunConfig) *MockGun {
2830
return &MockGun{
2931
cfg: cfg,
3032
Data: make([]string, 0),
3133
}
3234
}
3335

34-
// Call implements example gun call, assertions on response bodies should be done here
36+
// Call executes a request using the provided Generator and returns a Response.
37+
// It may simulate a failure or a timeout based on the configuration settings of the MockGun.
38+
// If the InternalStop configuration is enabled, it will stop the Generator before proceeding.
39+
// The function will also respect the CallSleep duration specified in the configuration.
40+
// The returned Response contains data indicating success or failure, along with an error message if applicable.
41+
// If a timeout occurs, the Response will reflect that with a Timeout flag set to true.
3542
func (m *MockGun) Call(l *Generator) *Response {
3643
if m.cfg.InternalStop {
3744
l.Stop()
@@ -54,6 +61,11 @@ func (m *MockGun) Call(l *Generator) *Response {
5461
return &Response{Data: "successCallData"}
5562
}
5663

64+
// convertResponsesData processes the generator's response data and returns three values:
65+
// a slice of strings containing the successfully processed data,
66+
// a slice of pointers to Response objects representing successful responses,
67+
// and a slice of pointers to Response objects representing failed responses.
68+
// The function ensures thread safety by locking the necessary mutexes during data access.
5769
func convertResponsesData(g *Generator) ([]string, []*Response, []*Response) {
5870
g.responsesData.okDataMu.Lock()
5971
defer g.responsesData.okDataMu.Unlock()

wasp/http_server_mock.go

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

21+
// Run starts the HTTP mock server in a separate goroutine.
22+
// It invokes the server's Run method, allowing it to handle incoming requests
23+
// asynchronously. This function does not return any value and is intended
24+
// to be called to initiate the server's operation.
2125
func (s *HTTPMockServer) Run() {
2226
go func() {
2327
//nolint
2428
_ = s.srv.Run()
2529
}()
2630
}
2731

32+
// URL returns the base URL of the HTTP mock server as a string.
33+
// This URL can be used to send requests to the mock server for testing purposes.
34+
// The returned URL is fixed and points to "http://localhost:8080/1".
2835
func (s *HTTPMockServer) URL() string {
2936
return "http://localhost:8080/1"
3037
}
3138

39+
// NewHTTPMockServer creates a new instance of HTTPMockServer with the provided configuration.
40+
// If the configuration is nil, it initializes the server with default settings, including
41+
// predefined latencies and HTTP response codes for two mock API endpoints.
42+
// The returned HTTPMockServer can be used to simulate API responses for testing purposes.
3243
func NewHTTPMockServer(cfg *HTTPMockServerConfig) *HTTPMockServer {
3344
if cfg == nil {
3445
cfg = &HTTPMockServerConfig{

wasp/k8s.go

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

26-
// GetLocalK8sDeps get local k8s context config
26+
// GetLocalK8sDeps retrieves a Kubernetes client set and its associated REST configuration
27+
// for interacting with a local Kubernetes cluster.
28+
// It returns a pointer to the kubernetes.Clientset, a pointer to the rest.Config,
29+
// and an error if any issues occur during the retrieval process.
30+
// If successful, the client set can be used to perform operations on the Kubernetes API.
2731
func GetLocalK8sDeps() (*kubernetes.Clientset, *rest.Config, error) {
2832
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
2933
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
@@ -38,7 +42,10 @@ func GetLocalK8sDeps() (*kubernetes.Clientset, *rest.Config, error) {
3842
return k8sClient, k8sConfig, nil
3943
}
4044

41-
// NewK8sClient creates a new k8s client with a REST config
45+
// NewK8sClient initializes a new K8sClient instance by retrieving the necessary Kubernetes dependencies
46+
// from the local environment. It returns a pointer to the K8sClient, which contains the ClientSet and
47+
// RESTConfig required for interacting with the Kubernetes API. If there is an error while fetching
48+
// the dependencies, the function logs the error and terminates the program.
4249
func NewK8sClient() *K8sClient {
4350
cs, cfg, err := GetLocalK8sDeps()
4451
if err != nil {
@@ -50,18 +57,33 @@ func NewK8sClient() *K8sClient {
5057
}
5158
}
5259

60+
// jobPods retrieves a list of pods in the specified namespace that match the given synchronization label.
61+
// It returns a pointer to a v1.PodList containing the matching pods and an error if the operation fails.
62+
// If no pods are found, the returned PodList will be empty, and the error will be nil.
5363
func (m *K8sClient) jobPods(ctx context.Context, nsName, syncLabel string) (*v1.PodList, error) {
5464
return m.ClientSet.CoreV1().Pods(nsName).List(ctx, metaV1.ListOptions{LabelSelector: syncSelector(syncLabel)})
5565
}
5666

67+
// jobs retrieves a list of Kubernetes jobs in the specified namespace that match the given label selector.
68+
// It takes a context for cancellation and a namespace name along with a synchronization label as parameters.
69+
// The function returns a pointer to a batchV1.JobList containing the jobs that match the criteria,
70+
// or an error if the retrieval fails.
5771
func (m *K8sClient) jobs(ctx context.Context, nsName, syncLabel string) (*batchV1.JobList, error) {
5872
return m.ClientSet.BatchV1().Jobs(nsName).List(ctx, metaV1.ListOptions{LabelSelector: syncSelector(syncLabel)})
5973
}
6074

75+
// syncSelector formats a string to create a label selector for synchronization purposes.
76+
// It returns a string in the format "sync=<input>", where <input> is the provided string argument.
77+
// This formatted string can be used in Kubernetes API calls to filter resources based on the specified synchronization label.
6178
func syncSelector(s string) string {
6279
return fmt.Sprintf("sync=%s", s)
6380
}
6481

82+
// removeJobs deletes the specified jobs in the given namespace.
83+
// It takes a context for cancellation and a namespace name along with a list of jobs to be removed.
84+
// The function logs the removal process and ensures that each job is deleted with a foreground deletion policy.
85+
// If any error occurs during the deletion of a job, it returns the error.
86+
// If all jobs are successfully deleted, it returns nil.
6587
func (m *K8sClient) removeJobs(ctx context.Context, nsName string, jobs *batchV1.JobList) error {
6688
log.Info().Msg("Removing jobs")
6789
for _, j := range jobs.Items {
@@ -75,6 +97,10 @@ func (m *K8sClient) removeJobs(ctx context.Context, nsName string, jobs *batchV1
7597
return nil
7698
}
7799

100+
// waitSyncGroup blocks until the specified number of pods with the given sync label are in the Running state.
101+
// It periodically checks the status of the pods in the specified namespace and logs the progress.
102+
// If an error occurs while retrieving the pods, it returns the error.
103+
// The function will return nil once all pods are confirmed to be running, or it will continue to wait if the conditions are not met.
78104
func (m *K8sClient) waitSyncGroup(ctx context.Context, nsName string, syncLabel string, jobNum int) error {
79105
outer:
80106
for {
@@ -97,7 +123,11 @@ outer:
97123
}
98124
}
99125

100-
// TrackJobs tracks both jobs and their pods until they succeed or fail
126+
// TrackJobs monitors the status of Kubernetes jobs and their associated pods in a specified namespace.
127+
// It continuously checks for the specified number of job pods and logs their statuses.
128+
// If any job fails, it returns an error and can optionally remove the jobs based on the keepJobs parameter.
129+
// The function will exit gracefully if the provided context is done, returning nil.
130+
// If all jobs succeed, it will either remove the jobs or return nil based on the keepJobs flag.
101131
func (m *K8sClient) TrackJobs(ctx context.Context, nsName, syncLabel string, jobNum int, keepJobs bool) error {
102132
log.Debug().Str("LabelSelector", syncSelector(syncLabel)).Msg("Searching for jobs/pods")
103133
for {

0 commit comments

Comments
 (0)