From d9534370522527dca19ebbd008b81e181872faab Mon Sep 17 00:00:00 2001 From: Matheus Nogueira Date: Tue, 2 May 2023 13:34:57 -0300 Subject: [PATCH] feat: environments as resources (#2415) * remove old environment endpoints * implement environments as a resource * fix build after rebase * fix encoding * fix test * registering environent resource routes (#2435) * feature(frontend): enabling environments as resources (#2437) * remove old environment endpoints * implement environments as a resource * fix build after rebase * fix encoding * fix test * registering environent resource routes (#2435) * feature(frontend): enabling environments as resources * feature(frontend): fixing unit tests --------- Co-authored-by: Matheus Nogueira Co-authored-by: Sebastian Choren * add instrumentation to resource manager * Update map conversion logic * fix cli tests * fix rebase * fix span name * fix tests * remove broken middleware config * fix generated file * chore(docs): updating docs * feature(cli): enabling environments as resources (#2446) * remove old environment endpoints * feature(frontend): enabling environments as resources (#2437) * remove old environment endpoints * implement environments as a resource * fix build after rebase * fix encoding * fix test * registering environent resource routes (#2435) * feature(frontend): enabling environments as resources * feature(frontend): fixing unit tests --------- Co-authored-by: Matheus Nogueira Co-authored-by: Sebastian Choren * fixing unit tests * feature(cli): enabling environments as resources * fixing environments tracetest testing with tracetest * fixing environments tracetest testing with tracetest * fixing environments tracetest testing with tracetest * remove old environment endpoints * implement environments as a resource * fix build after rebase * fix encoding * registering environent resource routes (#2435) * feature(frontend): enabling environments as resources (#2437) * remove old environment endpoints * implement environments as a resource * fix build after rebase * fix encoding * fix test * registering environent resource routes (#2435) * feature(frontend): enabling environments as resources * feature(frontend): fixing unit tests --------- Co-authored-by: Matheus Nogueira Co-authored-by: Sebastian Choren * fix rebase * fixing unit tests * fixing environments tracetest testing with tracetest * fixing environments tracetest testing with tracetest * fix rebase * fix test run with env * fix bad rebase --------- Co-authored-by: Matheus Nogueira Co-authored-by: Sebastian Choren * fix instrumentation * fix span name * Apply suggestions from code review Co-authored-by: Daniel Baptista Dias * remove empty line --------- Co-authored-by: Sebastian Choren Co-authored-by: Oscar Reyes Co-authored-by: Daniel Dias Co-authored-by: Daniel Baptista Dias --- api/environments.yaml | 11 + api/openapi.yaml | 271 ++-- api/parameters.yaml | 8 + cli/actions/apply_environment_action.go | 73 -- cli/actions/config.go | 8 +- cli/actions/datastore.go | 8 +- cli/actions/demo.go | 6 +- cli/actions/environments.go | 114 ++ cli/actions/polling.go | 24 +- cli/actions/resource_actions.go | 25 +- cli/actions/run_test_action.go | 109 +- cli/cmd/config.go | 4 + cli/cmd/environment_apply.go | 40 - cli/cmd/environment_cmd.go | 21 - cli/cmd/environment_legacy_cmd.go | 45 + cli/cmd/test_run_cmd.go | 8 +- cli/file/definition.go | 4 +- cli/go.mod | 2 +- cli/openapi/api_api.go | 1161 ++++------------- cli/openapi/api_resource_api.go | 647 ++++++++- cli/openapi/model_environment_resource.go | 161 +++ .../model_list_environments_200_response.go | 160 +++ cli/utils/api.go | 66 +- cli/utils/common.go | 21 + docs/docs/cli/creating-environments.md | 2 +- server/app/app.go | 35 +- server/environment/main_test.go | 18 + server/environment/manager.go | 330 +++++ server/environment/manager_test.go | 114 ++ server/environment/model.go | 65 + server/environment/resource.go | 16 + server/go.mod | 2 +- server/http/controller.go | 71 - server/http/custom_routes.go | 17 - server/openapi/api.go | 22 +- server/openapi/api_api.go | 162 --- server/openapi/api_resource_api.go | 139 ++ server/openapi/api_resource_api_service.go | 91 +- server/openapi/model_environment_resource.go | 39 + .../model_list_environments_200_response.go | 38 + server/resourcemanager/provisioner.go | 4 +- server/resourcemanager/resource_manager.go | 131 +- .../testutil/operations_list.go | 2 +- .../environment/01_create_environment.yml | 16 +- .../environment/02_list_environment.yml | 5 +- .../environment/03_delete_environment.yml | 2 +- .../EnvironmentForm/EnvironmentForm.tsx | 3 + .../EnvironmentModal/EnvironmentModal.tsx | 5 +- .../FileViewerModal.provider.tsx | 13 +- web/src/models/Environment.model.ts | 17 +- web/src/models/TestRun.model.ts | 2 +- web/src/models/TransactionRun.model.ts | 2 +- .../Environment/Environment.provider.tsx | 6 +- .../Environment/hooks/useEnvironmentCrud.ts | 6 +- web/src/redux/apis/TraceTest.api.ts | 1 + .../apis/endpoints/Environment.endpoint.ts | 26 +- .../redux/apis/endpoints/Resource.endpoint.ts | 12 + web/src/services/Environment.service.ts | 16 + web/src/types/Generated.types.ts | 243 ++-- 59 files changed, 2823 insertions(+), 1847 deletions(-) delete mode 100644 cli/actions/apply_environment_action.go create mode 100644 cli/actions/environments.go delete mode 100644 cli/cmd/environment_apply.go delete mode 100644 cli/cmd/environment_cmd.go create mode 100644 cli/cmd/environment_legacy_cmd.go create mode 100644 cli/openapi/model_environment_resource.go create mode 100644 cli/openapi/model_list_environments_200_response.go create mode 100644 server/environment/main_test.go create mode 100644 server/environment/manager.go create mode 100644 server/environment/manager_test.go create mode 100644 server/environment/model.go create mode 100644 server/environment/resource.go create mode 100644 server/openapi/model_environment_resource.go create mode 100644 server/openapi/model_list_environments_200_response.go create mode 100644 web/src/services/Environment.service.ts diff --git a/api/environments.yaml b/api/environments.yaml index b640b2b6d9..ecddc734a8 100644 --- a/api/environments.yaml +++ b/api/environments.yaml @@ -2,6 +2,17 @@ openapi: 3.0.0 components: schemas: + EnvironmentResource: + type: object + description: "Represents an environment structured into the Resources format." + properties: + type: + type: string + description: "Represents the type of this resource. It should always be set as 'Environment'." + enum: + - Environment + spec: + $ref: "#/components/schemas/Environment" Environment: type: object properties: diff --git a/api/openapi.yaml b/api/openapi.yaml index ed99a40663..8693215515 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -643,136 +643,6 @@ paths: items: $ref: "./testEvents.yaml#/components/schemas/TestRunEvent" - # Environments - /environments: - get: - tags: - - api - summary: "Get Environments" - description: "Get Environments" - operationId: getEnvironments - parameters: - - $ref: "./parameters.yaml#/components/parameters/take" - - $ref: "./parameters.yaml#/components/parameters/skip" - - $ref: "./parameters.yaml#/components/parameters/query" - - $ref: "./parameters.yaml#/components/parameters/sortBy" - - $ref: "./parameters.yaml#/components/parameters/sortDirection" - responses: - 200: - description: successful operation - headers: - X-Total-Count: - schema: - type: integer - description: Total records count - content: - application/json: - schema: - type: array - items: - $ref: "./environments.yaml#/components/schemas/Environment" - 500: - description: "problem with getting environments" - post: - tags: - - api - summary: "Create new environment" - description: "Create new environment action" - operationId: createEnvironment - requestBody: - content: - application/json: - schema: - $ref: "./environments.yaml#/components/schemas/Environment" - responses: - 200: - description: successful operation - content: - application/json: - schema: - $ref: "./environments.yaml#/components/schemas/Environment" - 400: - description: "trying to create a environment with an already existing ID" - /environments/{environmentId}: - get: - tags: - - api - parameters: - - in: path - name: environmentId - schema: - type: string - required: true - summary: "get environment" - description: "get environment" - operationId: getEnvironment - responses: - 200: - description: successful operation - content: - application/json: - schema: - $ref: "./environments.yaml#/components/schemas/Environment" - 500: - description: "problem with getting a environment" - put: - tags: - - api - parameters: - - in: path - name: environmentId - schema: - type: string - required: true - summary: "update environment" - description: "update environment action" - operationId: updateEnvironment - requestBody: - content: - application/json: - schema: - $ref: "./environments.yaml#/components/schemas/Environment" - responses: - 204: - description: successful operation - 500: - description: "problem with updating environment" - delete: - tags: - - api - parameters: - - in: path - name: environmentId - schema: - type: string - required: true - summary: "delete a environment" - description: "delete a environment" - operationId: deleteEnvironment - responses: - "204": - description: OK - /environments/{environmentId}/definition.yaml: - get: - tags: - - api - parameters: - - in: path - name: environmentId - schema: - type: string - required: true - summary: Get the environment definition as an YAML file - description: Get the environment as an YAML file - operationId: getEnvironmentDefinitionFile - responses: - 200: - description: OK - content: - application/yaml: - schema: - type: string - # Expressions /expressions/resolve: post: @@ -1139,8 +1009,147 @@ paths: summary: "Delete a Data Store" description: "Delete a Data Store" operationId: deleteDataStore + responses: + "204": + description: OK + + # Environments + /environments: + get: + tags: + - resource-api + summary: "List environments" + description: "List environments available in Tracetest." + operationId: listEnvironments + parameters: + - $ref: "./parameters.yaml#/components/parameters/take" + - $ref: "./parameters.yaml#/components/parameters/skip" + - $ref: "./parameters.yaml#/components/parameters/switchableResourceSortBy" + - $ref: "./parameters.yaml#/components/parameters/sortDirection" + responses: + 200: + description: successful operation + content: + application/json: + schema: + type: object + properties: + count: + type: integer + items: + type: array + items: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + type: object + properties: + count: + type: integer + items: + type: array + items: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + 400: + description: "invalid query for environments, some data was sent in incorrect format." + 500: + description: "problem listing environments" + post: + tags: + - resource-api + summary: "Create an environment" + description: "Create an environment that can be used by tests and transactions" + operationId: createEnvironment + requestBody: + content: + application/json: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + responses: + 201: + description: successful operation + content: + application/json: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + 500: + description: "problem creating an environment" + + /environments/{environmentId}: + get: + tags: + - resource-api + parameters: + - $ref: "./parameters.yaml#/components/parameters/environmentId" + summary: "Get a specific environment" + description: "Get one environment by its id" + operationId: getEnvironment + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + 404: + description: "environment not found" + 500: + description: "problem getting an environment" + put: + tags: + - resource-api + parameters: + - $ref: "./parameters.yaml#/components/parameters/environmentId" + summary: "Update an environment" + description: "Update an environment used on Tracetest" + operationId: updateEnvironment + requestBody: + content: + application/json: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + text/yaml: + schema: + $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + 400: + description: "invalid environment, some data was sent in incorrect format." + 404: + description: "environment not found" + 500: + description: "problem updating an environment" + delete: + tags: + - resource-api + parameters: + - $ref: "./parameters.yaml#/components/parameters/environmentId" + summary: "Delete an environment" + description: "Delete an environment from Tracetest" + operationId: deleteEnvironment responses: 204: description: successful operation + 400: + description: "invalid environment, some data was sent in incorrect format." + 404: + description: "environment not found" 500: - description: "problem with data store deletion" + description: "problem deleting an environment" diff --git a/api/parameters.yaml b/api/parameters.yaml index de8e6bfeee..f4e5a67783 100644 --- a/api/parameters.yaml +++ b/api/parameters.yaml @@ -125,3 +125,11 @@ components: description: "ID of a datastore used on Tracetest to configure how to fetch traces in a test" schema: type: string + + environmentId: + in: path + name: environmentId + required: true + description: "ID of an environment used on Tracetest to inject values into tests and transactions" + schema: + type: string diff --git a/cli/actions/apply_environment_action.go b/cli/actions/apply_environment_action.go deleted file mode 100644 index de099555cf..0000000000 --- a/cli/actions/apply_environment_action.go +++ /dev/null @@ -1,73 +0,0 @@ -package actions - -import ( - "context" - "fmt" - - "github.com/kubeshop/tracetest/cli/file" - "github.com/kubeshop/tracetest/cli/openapi" - "go.uber.org/zap" -) - -type ApplyEnvironmentConfig struct { - File string -} - -type applyEnvironmentAction struct { - logger *zap.Logger - client *openapi.APIClient -} - -var _ Action[ApplyEnvironmentConfig] = &applyEnvironmentAction{} - -func NewApplyEnvironmentAction(logger *zap.Logger, client *openapi.APIClient) applyEnvironmentAction { - return applyEnvironmentAction{ - logger: logger, - client: client, - } -} - -func (a applyEnvironmentAction) Run(ctx context.Context, args ApplyEnvironmentConfig) error { - if args.File == "" { - return fmt.Errorf("you must specify a file to be applied") - } - - a.logger.Debug( - "applying environment", - zap.String("file", args.File), - ) - - fileContent, err := file.Read(args.File) - if err != nil { - return fmt.Errorf("could not read file: %w", err) - } - - if fileContent.Definition().Type != "Environment" { - return fmt.Errorf(`file must be of type "Environment"`) - } - - fileContentString := fileContent.Contents() - - req := a.client.ApiApi.ExecuteDefinition(ctx) - req = req.TextDefinition(openapi.TextDefinition{ - RunInformation: &openapi.RunInformation{}, - Content: &fileContentString, - }) - - response, _, err := req.Execute() - if err != nil { - return fmt.Errorf("could not apply environment: %w", err) - } - - if fileContent.HasID() || response.Id == nil { - return nil - } - - newFile, err := fileContent.SetID(*response.Id) - if err != nil { - return fmt.Errorf("could not set id into environment file: %w", err) - } - - _, err = newFile.Write() - return err -} diff --git a/cli/actions/config.go b/cli/actions/config.go index c45616eb9f..c859be19d3 100644 --- a/cli/actions/config.go +++ b/cli/actions/config.go @@ -31,16 +31,16 @@ func (configActions) Name() string { return "config" } -func (config configActions) Apply(ctx context.Context, fileContent file.File) error { +func (config configActions) Apply(ctx context.Context, fileContent file.File) (*file.File, error) { return config.resourceClient.Update(ctx, fileContent, currentConfigID) } -func (config configActions) Get(ctx context.Context, ID string) (string, error) { +func (config configActions) Get(ctx context.Context, ID string) (*file.File, error) { return config.resourceClient.Get(ctx, currentConfigID) } -func (config configActions) List(ctx context.Context, listArgs utils.ListArgs) (string, error) { - return "", ErrNotSupportedResourceAction +func (config configActions) List(ctx context.Context, listArgs utils.ListArgs) (*file.File, error) { + return nil, ErrNotSupportedResourceAction } func (config configActions) Delete(ctx context.Context, ID string) error { diff --git a/cli/actions/datastore.go b/cli/actions/datastore.go index cfd5fdab6e..5af6921772 100644 --- a/cli/actions/datastore.go +++ b/cli/actions/datastore.go @@ -32,18 +32,18 @@ func (d *dataStoreActions) Name() string { return "datastore" } -func (d *dataStoreActions) Apply(ctx context.Context, fileContent file.File) error { +func (d *dataStoreActions) Apply(ctx context.Context, fileContent file.File) (*file.File, error) { var dataStore openapi.DataStore mapstructure.Decode(fileContent.Definition().Spec, &dataStore) return d.resourceClient.Update(ctx, fileContent, currentConfigID) } -func (d *dataStoreActions) List(ctx context.Context, args utils.ListArgs) (string, error) { - return "", ErrNotSupportedResourceAction +func (d *dataStoreActions) List(ctx context.Context, args utils.ListArgs) (*file.File, error) { + return nil, ErrNotSupportedResourceAction } -func (d *dataStoreActions) Get(ctx context.Context, id string) (string, error) { +func (d *dataStoreActions) Get(ctx context.Context, id string) (*file.File, error) { return d.resourceClient.Get(ctx, currentConfigID) } diff --git a/cli/actions/demo.go b/cli/actions/demo.go index a70b83e789..172dfdbc86 100644 --- a/cli/actions/demo.go +++ b/cli/actions/demo.go @@ -32,7 +32,7 @@ func (demoActions) Name() string { return "demo" } -func (demo demoActions) Apply(ctx context.Context, fileContent file.File) error { +func (demo demoActions) Apply(ctx context.Context, fileContent file.File) (*file.File, error) { var demoResource openapi.Demo mapstructure.Decode(fileContent.Definition().Spec, &demoResource.Spec) @@ -43,7 +43,7 @@ func (demo demoActions) Apply(ctx context.Context, fileContent file.File) error return demo.resourceClient.Update(ctx, fileContent, *demoResource.Spec.Id) } -func (demo demoActions) List(ctx context.Context, listArgs utils.ListArgs) (string, error) { +func (demo demoActions) List(ctx context.Context, listArgs utils.ListArgs) (*file.File, error) { return demo.resourceClient.List(ctx, listArgs) } @@ -51,6 +51,6 @@ func (demo demoActions) Delete(ctx context.Context, ID string) error { return demo.resourceClient.Delete(ctx, ID) } -func (demo demoActions) Get(ctx context.Context, ID string) (string, error) { +func (demo demoActions) Get(ctx context.Context, ID string) (*file.File, error) { return demo.resourceClient.Get(ctx, ID) } diff --git a/cli/actions/environments.go b/cli/actions/environments.go new file mode 100644 index 0000000000..48568c6e94 --- /dev/null +++ b/cli/actions/environments.go @@ -0,0 +1,114 @@ +package actions + +import ( + "context" + "fmt" + "io/ioutil" + + "github.com/kubeshop/tracetest/cli/file" + "github.com/kubeshop/tracetest/cli/openapi" + "github.com/kubeshop/tracetest/cli/utils" + "github.com/kubeshop/tracetest/server/model/yaml" + "github.com/mitchellh/mapstructure" +) + +type environmentsActions struct { + resourceArgs +} + +var _ ResourceActions = &environmentsActions{} + +func NewEnvironmentsActions(options ...ResourceArgsOption) environmentsActions { + args := NewResourceArgs(options...) + + return environmentsActions{ + resourceArgs: args, + } +} + +func (environmentsActions) FileType() yaml.FileType { + return yaml.FileTypeEnvironment +} + +func (environmentsActions) Name() string { + return "environment" +} + +func (environment environmentsActions) Apply(ctx context.Context, fileContent file.File) (*file.File, error) { + envResource := openapi.EnvironmentResource{ + Spec: &openapi.Environment{}, + } + + mapstructure.Decode(fileContent.Definition().Spec, &envResource.Spec) + + if envResource.Spec.Id == nil || *envResource.Spec.Id == "" { + return environment.resourceClient.Create(ctx, fileContent) + } + + return environment.resourceClient.Update(ctx, fileContent, *envResource.Spec.Id) +} + +func (environment environmentsActions) List(ctx context.Context, listArgs utils.ListArgs) (*file.File, error) { + return environment.resourceClient.List(ctx, listArgs) +} + +func (environment environmentsActions) Delete(ctx context.Context, ID string) error { + return environment.resourceClient.Delete(ctx, ID) +} + +func (environment environmentsActions) Get(ctx context.Context, ID string) (*file.File, error) { + return environment.resourceClient.Get(ctx, ID) +} + +func (environment environmentsActions) ApplyResource(ctx context.Context, resource openapi.EnvironmentResource) (*file.File, error) { + content, err := resource.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("could not marshal environment: %w", err) + } + + file, err := file.NewFromRaw("env.yaml", content) + if err != nil { + return nil, fmt.Errorf("could not create environment file: %w", err) + } + + return environment.Apply(ctx, file) +} + +func (environment environmentsActions) FromFile(ctx context.Context, filePath string) (openapi.EnvironmentResource, error) { + if !utils.StringReferencesFile(filePath) { + return openapi.EnvironmentResource{}, fmt.Errorf(`env file "%s" does not exist`, filePath) + } + + fileContent, err := ioutil.ReadFile(filePath) + if err != nil { + return openapi.EnvironmentResource{}, fmt.Errorf(`cannot read env file "%s": %w`, filePath, err) + } + + model, err := yaml.Decode(fileContent) + if err != nil { + return openapi.EnvironmentResource{}, fmt.Errorf(`cannot parse env file "%s": %w`, filePath, err) + } + + envModel := model.Spec.(yaml.Environment) + + values := make([]openapi.EnvironmentValue, 0, len(envModel.Values)) + for _, value := range envModel.Values { + v := value + values = append(values, openapi.EnvironmentValue{ + Key: &v.Key, + Value: &v.Value, + }) + } + + environmentResource := openapi.EnvironmentResource{ + Type: (*string)(&model.Type), + Spec: &openapi.Environment{ + Id: &envModel.ID, + Name: &envModel.Name, + Description: &envModel.Description, + Values: values, + }, + } + + return environmentResource, nil +} diff --git a/cli/actions/polling.go b/cli/actions/polling.go index 637d4c4d35..de30f242e6 100644 --- a/cli/actions/polling.go +++ b/cli/actions/polling.go @@ -2,7 +2,6 @@ package actions import ( "context" - "fmt" "github.com/kubeshop/tracetest/cli/file" "github.com/kubeshop/tracetest/cli/openapi" @@ -33,36 +32,21 @@ func (pollingActions) Name() string { return "pollingprofile" } -func (polling pollingActions) Apply(ctx context.Context, fileContent file.File) error { +func (polling pollingActions) Apply(ctx context.Context, fileContent file.File) (*file.File, error) { var pollingProfile openapi.PollingProfile mapstructure.Decode(fileContent.Definition().Spec, &pollingProfile.Spec) return polling.resourceClient.Update(ctx, fileContent, currentConfigID) } -func (polling pollingActions) List(ctx context.Context, listArgs utils.ListArgs) (string, error) { - return "", ErrNotSupportedResourceAction -} - -func (polling pollingActions) Export(ctx context.Context, ID string, filePath string) error { - pollingProfile, err := polling.resourceClient.Get(ctx, currentConfigID) - if err != nil { - return err - } - - file, err := file.NewFromRaw(filePath, []byte(pollingProfile)) - if err != nil { - return fmt.Errorf("could not create file: %w", err) - } - - _, err = file.WriteRaw() - return err +func (polling pollingActions) List(ctx context.Context, listArgs utils.ListArgs) (*file.File, error) { + return nil, ErrNotSupportedResourceAction } func (polling pollingActions) Delete(ctx context.Context, ID string) error { return ErrNotSupportedResourceAction } -func (polling pollingActions) Get(ctx context.Context, ID string) (string, error) { +func (polling pollingActions) Get(ctx context.Context, ID string) (*file.File, error) { return polling.resourceClient.Get(ctx, currentConfigID) } diff --git a/cli/actions/resource_actions.go b/cli/actions/resource_actions.go index 58599b4984..8b7e6be631 100644 --- a/cli/actions/resource_actions.go +++ b/cli/actions/resource_actions.go @@ -14,9 +14,9 @@ type ResourceActions interface { Logger() *zap.Logger FileType() yaml.FileType Name() string - Apply(context.Context, file.File) error - List(context.Context, utils.ListArgs) (string, error) - Get(context.Context, string) (string, error) + Apply(context.Context, file.File) (*file.File, error) + List(context.Context, utils.ListArgs) (*file.File, error) + Get(context.Context, string) (*file.File, error) Delete(context.Context, string) error } @@ -53,7 +53,13 @@ func (r *resourceActions) Apply(ctx context.Context, args ApplyArgs) error { return fmt.Errorf(fmt.Sprintf(`file must be of type "%s"`, r.actions.FileType())) } - return r.actions.Apply(ctx, fileContent) + file, err := r.actions.Apply(ctx, fileContent) + if err != nil { + return err + } + + _, err = file.WriteRaw() + return err } func (r *resourceActions) List(ctx context.Context, args utils.ListArgs) error { @@ -62,7 +68,7 @@ func (r *resourceActions) List(ctx context.Context, args utils.ListArgs) error { return err } - fmt.Println(resources) + fmt.Println(resources.Contents()) return nil } @@ -72,21 +78,16 @@ func (r *resourceActions) Get(ctx context.Context, id string) error { return err } - fmt.Println(resource) + fmt.Println(resource.Contents()) return nil } func (r *resourceActions) Export(ctx context.Context, id string, filePath string) error { - resource, err := r.actions.Get(ctx, id) + file, err := r.actions.Get(ctx, id) if err != nil { return err } - file, err := file.NewFromRaw(filePath, []byte(resource)) - if err != nil { - return fmt.Errorf("could not create file: %w", err) - } - _, err = file.WriteRaw() return err } diff --git a/cli/actions/run_test_action.go b/cli/actions/run_test_action.go index 6c64331620..ebb3ccd527 100644 --- a/cli/actions/run_test_action.go +++ b/cli/actions/run_test_action.go @@ -13,7 +13,6 @@ import ( "time" cienvironment "github.com/cucumber/ci-environment/go" - "github.com/joho/godotenv" "github.com/kubeshop/tracetest/cli/config" "github.com/kubeshop/tracetest/cli/file" "github.com/kubeshop/tracetest/cli/formatters" @@ -32,9 +31,10 @@ type RunTestConfig struct { } type runTestAction struct { - config config.Config - logger *zap.Logger - client *openapi.APIClient + config config.Config + logger *zap.Logger + client *openapi.APIClient + environmentActions environmentsActions } var _ Action[RunTestConfig] = &runTestAction{} @@ -48,8 +48,8 @@ type runDefParams struct { EnvironmentVariables map[string]string } -func NewRunTestAction(config config.Config, logger *zap.Logger, client *openapi.APIClient) runTestAction { - return runTestAction{config, logger, client} +func NewRunTestAction(config config.Config, logger *zap.Logger, client *openapi.APIClient, environmentActions environmentsActions) runTestAction { + return runTestAction{config, logger, client, environmentActions} } func (a runTestAction) Run(ctx context.Context, args RunTestConfig) error { @@ -69,9 +69,20 @@ func (a runTestAction) Run(ctx context.Context, args RunTestConfig) error { zap.String("junit", args.JUnit), ) - envID, err := a.processEnv(ctx, args.EnvID) - if err != nil { - return fmt.Errorf("could not run definition: %w", err) + envID := args.EnvID + + if utils.StringReferencesFile(args.EnvID) { + envResource, err := a.environmentActions.FromFile(ctx, args.EnvID) + if err != nil { + return fmt.Errorf("could not run definition: %w", err) + } + + _, err = a.environmentActions.ApplyResource(ctx, envResource) + if err != nil { + return fmt.Errorf("could not run definition: %w", err) + } + + envID = *envResource.Spec.Id } params := runDefParams{ @@ -82,7 +93,7 @@ func (a runTestAction) Run(ctx context.Context, args RunTestConfig) error { Metadata: a.getMetadata(), } - err = a.runDefinition(ctx, params) + err := a.runDefinition(ctx, params) if err != nil { return fmt.Errorf("could not run definition: %w", err) } @@ -90,82 +101,6 @@ func (a runTestAction) Run(ctx context.Context, args RunTestConfig) error { return nil } -func stringReferencesFile(path string) bool { - // for the current working dir, check if the file exists - // by finding its absolute path and executing a stat command - - absolutePath, err := filepath.Abs(path) - if err != nil { - return false - } - - info, err := os.Stat(absolutePath) - if err != nil { - return false - } - - // if the string is empty the absolute path will the entire dir - // otherwise the user also could send a directory by mistake - return info != nil && !info.IsDir() -} - -func (a runTestAction) processEnv(ctx context.Context, envID string) (string, error) { - if !stringReferencesFile(envID) { //not a file, do nothing - return envID, nil - } - - envVars, err := godotenv.Read(envID) - if err != nil { - return "", fmt.Errorf(`cannot read env file "%s": %w`, envID, err) - } - - values := make([]openapi.EnvironmentValue, 0, len(envVars)) - for k, v := range envVars { - values = append(values, openapi.EnvironmentValue{ - Key: openapi.PtrString(k), - Value: openapi.PtrString(v), - }) - } - - name := filepath.Base(envID) - - req := openapi.Environment{ - Id: &name, - Name: &name, - Values: values, - } - - body, resp, err := a.client.ApiApi. - CreateEnvironment(ctx). - Environment(req). - Execute() - if err != nil { - if resp != nil && resp.StatusCode == http.StatusBadRequest { - return a.updateEnv(ctx, req) - } - - return "", fmt.Errorf("could not create environment: %w", err) - } - - return body.GetId(), nil -} - -func (a runTestAction) updateEnv(ctx context.Context, req openapi.Environment) (string, error) { - resp, err := a.client.ApiApi. - UpdateEnvironment(ctx, req.GetId()). - Environment(req). - Execute() - if err != nil { - return "", fmt.Errorf("could not update environment: %w", err) - } - - if resp.StatusCode != http.StatusNoContent { - return "", fmt.Errorf("error updating environment") - } - - return req.GetId(), nil -} - func (a runTestAction) testFileToID(ctx context.Context, originalPath, filePath string) (string, error) { path := filepath.Join(originalPath, filePath) f, err := file.Read(path) @@ -213,7 +148,7 @@ func (a runTestAction) runDefinitionFile(ctx context.Context, f file.File, param // to check it properly we need to convert it to an absolute path stepPath := filepath.Join(f.AbsDir(), step) - if !stringReferencesFile(stepPath) { + if !utils.StringReferencesFile(stepPath) { // not referencing a file, keep the value continue } diff --git a/cli/cmd/config.go b/cli/cmd/config.go index e83e470e38..0acdfe66c0 100644 --- a/cli/cmd/config.go +++ b/cli/cmd/config.go @@ -62,6 +62,10 @@ func setupCommand(options ...setupOption) func(cmd *cobra.Command, args []string dataStoreActions := actions.NewDataStoreActions(dataStoreOptions...) resourceRegistry.Register(dataStoreActions) + environmentOptions := append(baseOptions, actions.WithClient(utils.GetResourceAPIClient("environments", cliConfig))) + environmentActions := actions.NewEnvironmentsActions(environmentOptions...) + resourceRegistry.Register(environmentActions) + if config.shouldValidateConfig { validateConfig(cmd, args) } diff --git a/cli/cmd/environment_apply.go b/cli/cmd/environment_apply.go deleted file mode 100644 index b25f0d46d1..0000000000 --- a/cli/cmd/environment_apply.go +++ /dev/null @@ -1,40 +0,0 @@ -package cmd - -import ( - "context" - "fmt" - "os" - - "github.com/kubeshop/tracetest/cli/actions" - "github.com/kubeshop/tracetest/cli/analytics" - "github.com/kubeshop/tracetest/cli/utils" - "github.com/spf13/cobra" -) - -var environmentApplyFile string - -var environmentApplyCmd = &cobra.Command{ - Use: "apply", - Short: "Create or update an environment to Tracetest", - Long: "Create or update an environment to Tracetest", - PreRun: setupCommand(), - Run: func(cmd *cobra.Command, args []string) { - analytics.Track("Environment apply", "cmd", map[string]string{}) - client := utils.GetAPIClient(cliConfig) - action := actions.NewApplyEnvironmentAction(cliLogger, client) - - err := action.Run(context.Background(), actions.ApplyEnvironmentConfig{ - File: environmentApplyFile, - }) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - }, - PostRun: teardownCommand, -} - -func init() { - environmentApplyCmd.PersistentFlags().StringVarP(&environmentApplyFile, "file", "f", "", "file containing the environment configuration") - environmentCmd.AddCommand(environmentApplyCmd) -} diff --git a/cli/cmd/environment_cmd.go b/cli/cmd/environment_cmd.go deleted file mode 100644 index 4edb7bf3d5..0000000000 --- a/cli/cmd/environment_cmd.go +++ /dev/null @@ -1,21 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" -) - -var environmentCmd = &cobra.Command{ - GroupID: cmdGroupConfig.ID, - Use: "environment", - Short: "Manage your tracetest environments", - Long: "Manage your tracetest environments", - PreRun: setupCommand(), - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - PostRun: teardownCommand, -} - -func init() { - rootCmd.AddCommand(environmentCmd) -} diff --git a/cli/cmd/environment_legacy_cmd.go b/cli/cmd/environment_legacy_cmd.go new file mode 100644 index 0000000000..f51d2d9db1 --- /dev/null +++ b/cli/cmd/environment_legacy_cmd.go @@ -0,0 +1,45 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +var environmentApplyFile string + +var environmentCmd = &cobra.Command{ + GroupID: cmdGroupConfig.ID, + Use: "environment", + Short: "Manage your tracetest environments", + Long: "Manage your tracetest environments", + PreRun: setupCommand(), + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, + PostRun: teardownCommand, +} + +var environmentApplyCmd = &cobra.Command{ + Use: "apply", + Short: "Create or update an environment to Tracetest", + Long: "Create or update an environment to Tracetest", + PreRun: setupCommand(), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Warning! This is a deprecated command and it will be removed on Tracetest future versions!") + fmt.Println("Please use `tracetest apply environment --file [path]` command instead.") + fmt.Println("") + + // call new apply command + definitionFile = dataStoreApplyFile + applyCmd.Run(applyCmd, []string{"environment"}) + }, + PostRun: teardownCommand, +} + +func init() { + rootCmd.AddCommand(environmentCmd) + + environmentApplyCmd.PersistentFlags().StringVarP(&environmentApplyFile, "file", "f", "", "file containing the environment configuration") + environmentCmd.AddCommand(environmentApplyCmd) +} diff --git a/cli/cmd/test_run_cmd.go b/cli/cmd/test_run_cmd.go index 7b56dcf770..5677631ba8 100644 --- a/cli/cmd/test_run_cmd.go +++ b/cli/cmd/test_run_cmd.go @@ -23,13 +23,17 @@ var testRunCmd = &cobra.Command{ Short: "Run a test on your Tracetest server", Long: "Run a test on your Tracetest server", PreRun: setupCommand(), - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { analytics.Track("Test Run", "cmd", map[string]string{}) ctx := context.Background() client := utils.GetAPIClient(cliConfig) - runTestAction := actions.NewRunTestAction(cliConfig, cliLogger, client) + baseOptions := []actions.ResourceArgsOption{actions.WithLogger(cliLogger), actions.WithConfig(cliConfig)} + environmentOptions := append(baseOptions, actions.WithClient(utils.GetResourceAPIClient("environments", cliConfig))) + environmentActions := actions.NewEnvironmentsActions(environmentOptions...) + + runTestAction := actions.NewRunTestAction(cliConfig, cliLogger, client, environmentActions) actionArgs := actions.RunTestConfig{ DefinitionFile: runTestFileDefinition, EnvID: runTestEnvID, diff --git a/cli/file/definition.go b/cli/file/definition.go index 2117f8c1a9..66f7570124 100644 --- a/cli/file/definition.go +++ b/cli/file/definition.go @@ -165,8 +165,8 @@ func (f File) WriteRaw() (File, error) { return ReadRaw(f.path) } -func (f File) SaveChanges(changes string) (File, error) { +func (f File) SaveChanges(changes string) File { f.contents = []byte(changes) - return f.WriteRaw() + return f } diff --git a/cli/go.mod b/cli/go.mod index 577cfa2cab..882687239a 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -7,7 +7,6 @@ require ( github.com/compose-spec/compose-go v1.5.1 github.com/cucumber/ci-environment/go v0.0.0-20220915001957-711b1c82415f github.com/denisbrodbeck/machineid v1.0.1 - github.com/fluidtruck/deepcopy v1.0.0 github.com/joho/godotenv v1.3.0 github.com/kubeshop/tracetest/server v0.0.0-20230208220354-63c9594b2160 github.com/mitchellh/mapstructure v1.5.0 @@ -31,6 +30,7 @@ require ( github.com/distribution/distribution/v3 v3.0.0-20220907155224-78b9c98c5c31 // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect + github.com/fluidtruck/deepcopy v1.0.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.2.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect diff --git a/cli/openapi/api_api.go b/cli/openapi/api_api.go index 750301f2d4..cdec67fc07 100644 --- a/cli/openapi/api_api.go +++ b/cli/openapi/api_api.go @@ -22,114 +22,6 @@ import ( // ApiApiService ApiApi service type ApiApiService service -type ApiCreateEnvironmentRequest struct { - ctx context.Context - ApiService *ApiApiService - environment *Environment -} - -func (r ApiCreateEnvironmentRequest) Environment(environment Environment) ApiCreateEnvironmentRequest { - r.environment = &environment - return r -} - -func (r ApiCreateEnvironmentRequest) Execute() (*Environment, *http.Response, error) { - return r.ApiService.CreateEnvironmentExecute(r) -} - -/* -CreateEnvironment Create new environment - -Create new environment action - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateEnvironmentRequest -*/ -func (a *ApiApiService) CreateEnvironment(ctx context.Context) ApiCreateEnvironmentRequest { - return ApiCreateEnvironmentRequest{ - ApiService: a, - ctx: ctx, - } -} - -// Execute executes the request -// -// @return Environment -func (a *ApiApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentRequest) (*Environment, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPost - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *Environment - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.CreateEnvironment") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/environments" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.environment - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - type ApiCreateTestRequest struct { ctx context.Context ApiService *ApiApiService @@ -150,8 +42,8 @@ CreateTest Create new test Create new test action - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateTestRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateTestRequest */ func (a *ApiApiService) CreateTest(ctx context.Context) ApiCreateTestRequest { return ApiCreateTestRequest{ @@ -161,8 +53,7 @@ func (a *ApiApiService) CreateTest(ctx context.Context) ApiCreateTestRequest { } // Execute executes the request -// -// @return Test +// @return Test func (a *ApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -258,8 +149,8 @@ CreateTransaction Create new transaction Create new transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateTransactionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateTransactionRequest */ func (a *ApiApiService) CreateTransaction(ctx context.Context) ApiCreateTransactionRequest { return ApiCreateTransactionRequest{ @@ -269,8 +160,7 @@ func (a *ApiApiService) CreateTransaction(ctx context.Context) ApiCreateTransact } // Execute executes the request -// -// @return Transaction +// @return Transaction func (a *ApiApiService) CreateTransactionExecute(r ApiCreateTransactionRequest) (*Transaction, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -346,98 +236,6 @@ func (a *ApiApiService) CreateTransactionExecute(r ApiCreateTransactionRequest) return localVarReturnValue, localVarHTTPResponse, nil } -type ApiDeleteEnvironmentRequest struct { - ctx context.Context - ApiService *ApiApiService - environmentId string -} - -func (r ApiDeleteEnvironmentRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteEnvironmentExecute(r) -} - -/* -DeleteEnvironment delete a environment - -delete a environment - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId - @return ApiDeleteEnvironmentRequest -*/ -func (a *ApiApiService) DeleteEnvironment(ctx context.Context, environmentId string) ApiDeleteEnvironmentRequest { - return ApiDeleteEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, - } -} - -// Execute executes the request -func (a *ApiApiService) DeleteEnvironmentExecute(r ApiDeleteEnvironmentRequest) (*http.Response, error) { - var ( - localVarHTTPMethod = http.MethodDelete - localVarPostBody interface{} - formFiles []formFile - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.DeleteEnvironment") - if err != nil { - return nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarHTTPResponse, newErr - } - - return localVarHTTPResponse, nil -} - type ApiDeleteTestRequest struct { ctx context.Context ApiService *ApiApiService @@ -453,9 +251,9 @@ DeleteTest delete a test delete a test - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiDeleteTestRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiDeleteTestRequest */ func (a *ApiApiService) DeleteTest(ctx context.Context, testId string) ApiDeleteTestRequest { return ApiDeleteTestRequest{ @@ -546,10 +344,10 @@ DeleteTestRun delete a test run delete a test run - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiDeleteTestRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiDeleteTestRunRequest */ func (a *ApiApiService) DeleteTestRun(ctx context.Context, testId string, runId int32) ApiDeleteTestRunRequest { return ApiDeleteTestRunRequest{ @@ -641,9 +439,9 @@ DeleteTransaction delete a transaction delete a transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiDeleteTransactionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @return ApiDeleteTransactionRequest */ func (a *ApiApiService) DeleteTransaction(ctx context.Context, transactionId string) ApiDeleteTransactionRequest { return ApiDeleteTransactionRequest{ @@ -734,10 +532,10 @@ DeleteTransactionRun Delete a specific run from a particular transaction Delete a specific run from a particular transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @param runId id of the run - @return ApiDeleteTransactionRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @param runId id of the run + @return ApiDeleteTransactionRunRequest */ func (a *ApiApiService) DeleteTransactionRun(ctx context.Context, transactionId string, runId int32) ApiDeleteTransactionRunRequest { return ApiDeleteTransactionRunRequest{ @@ -803,396 +601,71 @@ func (a *ApiApiService) DeleteTransactionRunExecute(r ApiDeleteTransactionRunReq return localVarHTTPResponse, err } - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarHTTPResponse, newErr - } - - return localVarHTTPResponse, nil -} - -type ApiDryRunAssertionRequest struct { - ctx context.Context - ApiService *ApiApiService - testId string - runId int32 - testSpecs *TestSpecs -} - -func (r ApiDryRunAssertionRequest) TestSpecs(testSpecs TestSpecs) ApiDryRunAssertionRequest { - r.testSpecs = &testSpecs - return r -} - -func (r ApiDryRunAssertionRequest) Execute() (*AssertionResults, *http.Response, error) { - return r.ApiService.DryRunAssertionExecute(r) -} - -/* -DryRunAssertion run given assertions against the traces from the given run without persisting anything - -use this method to test a definition against an actual trace without creating a new version or persisting anything - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiDryRunAssertionRequest -*/ -func (a *ApiApiService) DryRunAssertion(ctx context.Context, testId string, runId int32) ApiDryRunAssertionRequest { - return ApiDryRunAssertionRequest{ - ApiService: a, - ctx: ctx, - testId: testId, - runId: runId, - } -} - -// Execute executes the request -// -// @return AssertionResults -func (a *ApiApiService) DryRunAssertionExecute(r ApiDryRunAssertionRequest) (*AssertionResults, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPut - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *AssertionResults - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.DryRunAssertion") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/tests/{testId}/run/{runId}/dry-run" - localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) - localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.testSpecs - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - -type ApiExecuteDefinitionRequest struct { - ctx context.Context - ApiService *ApiApiService - textDefinition *TextDefinition -} - -func (r ApiExecuteDefinitionRequest) TextDefinition(textDefinition TextDefinition) ApiExecuteDefinitionRequest { - r.textDefinition = &textDefinition - return r -} - -func (r ApiExecuteDefinitionRequest) Execute() (*ExecuteDefinitionResponse, *http.Response, error) { - return r.ApiService.ExecuteDefinitionExecute(r) -} - -/* -ExecuteDefinition Execute a definition - -Execute a definition - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiExecuteDefinitionRequest -*/ -func (a *ApiApiService) ExecuteDefinition(ctx context.Context) ApiExecuteDefinitionRequest { - return ApiExecuteDefinitionRequest{ - ApiService: a, - ctx: ctx, - } -} - -// Execute executes the request -// -// @return ExecuteDefinitionResponse -func (a *ApiApiService) ExecuteDefinitionExecute(r ApiExecuteDefinitionRequest) (*ExecuteDefinitionResponse, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPost - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *ExecuteDefinitionResponse - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExecuteDefinition") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/definition.yaml" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"text/json"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.textDefinition - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - -type ApiExportTestRunRequest struct { - ctx context.Context - ApiService *ApiApiService - testId string - runId int32 -} - -func (r ApiExportTestRunRequest) Execute() (*ExportedTestInformation, *http.Response, error) { - return r.ApiService.ExportTestRunExecute(r) -} - -/* -ExportTestRun export test and test run information - -export test and test run information for debugging - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiExportTestRunRequest -*/ -func (a *ApiApiService) ExportTestRun(ctx context.Context, testId string, runId int32) ApiExportTestRunRequest { - return ApiExportTestRunRequest{ - ApiService: a, - ctx: ctx, - testId: testId, - runId: runId, - } -} - -// Execute executes the request -// -// @return ExportedTestInformation -func (a *ApiApiService) ExportTestRunExecute(r ApiExportTestRunRequest) (*ExportedTestInformation, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodGet - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *ExportedTestInformation - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExportTestRun") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/tests/{testId}/run/{runId}/export" - localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) - localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { + if localVarHTTPResponse.StatusCode >= 300 { newErr := &GenericOpenAPIError{ body: localVarBody, - error: err.Error(), + error: localVarHTTPResponse.Status, } - return localVarReturnValue, localVarHTTPResponse, newErr + return localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHTTPResponse, nil + return localVarHTTPResponse, nil } -type ApiExpressionResolveRequest struct { - ctx context.Context - ApiService *ApiApiService - resolveRequestInfo *ResolveRequestInfo +type ApiDryRunAssertionRequest struct { + ctx context.Context + ApiService *ApiApiService + testId string + runId int32 + testSpecs *TestSpecs } -func (r ApiExpressionResolveRequest) ResolveRequestInfo(resolveRequestInfo ResolveRequestInfo) ApiExpressionResolveRequest { - r.resolveRequestInfo = &resolveRequestInfo +func (r ApiDryRunAssertionRequest) TestSpecs(testSpecs TestSpecs) ApiDryRunAssertionRequest { + r.testSpecs = &testSpecs return r } -func (r ApiExpressionResolveRequest) Execute() (*ResolveResponseInfo, *http.Response, error) { - return r.ApiService.ExpressionResolveExecute(r) +func (r ApiDryRunAssertionRequest) Execute() (*AssertionResults, *http.Response, error) { + return r.ApiService.DryRunAssertionExecute(r) } /* -ExpressionResolve resolves an expression and returns the result string +DryRunAssertion run given assertions against the traces from the given run without persisting anything -resolves an expression and returns the result string +use this method to test a definition against an actual trace without creating a new version or persisting anything - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiExpressionResolveRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiDryRunAssertionRequest */ -func (a *ApiApiService) ExpressionResolve(ctx context.Context) ApiExpressionResolveRequest { - return ApiExpressionResolveRequest{ +func (a *ApiApiService) DryRunAssertion(ctx context.Context, testId string, runId int32) ApiDryRunAssertionRequest { + return ApiDryRunAssertionRequest{ ApiService: a, ctx: ctx, + testId: testId, + runId: runId, } } // Execute executes the request -// -// @return ResolveResponseInfo -func (a *ApiApiService) ExpressionResolveExecute(r ApiExpressionResolveRequest) (*ResolveResponseInfo, *http.Response, error) { +// @return AssertionResults +func (a *ApiApiService) DryRunAssertionExecute(r ApiDryRunAssertionRequest) (*AssertionResults, *http.Response, error) { var ( - localVarHTTPMethod = http.MethodPost + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} formFiles []formFile - localVarReturnValue *ResolveResponseInfo + localVarReturnValue *AssertionResults ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExpressionResolve") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.DryRunAssertion") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/expressions/resolve" + localVarPath := localBasePath + "/tests/{testId}/run/{runId}/dry-run" + localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1216,7 +689,7 @@ func (a *ApiApiService) ExpressionResolveExecute(r ApiExpressionResolveRequest) localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.resolveRequestInfo + localVarPostBody = r.testSpecs req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -1254,58 +727,59 @@ func (a *ApiApiService) ExpressionResolveExecute(r ApiExpressionResolveRequest) return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetEnvironmentRequest struct { - ctx context.Context - ApiService *ApiApiService - environmentId string +type ApiExecuteDefinitionRequest struct { + ctx context.Context + ApiService *ApiApiService + textDefinition *TextDefinition +} + +func (r ApiExecuteDefinitionRequest) TextDefinition(textDefinition TextDefinition) ApiExecuteDefinitionRequest { + r.textDefinition = &textDefinition + return r } -func (r ApiGetEnvironmentRequest) Execute() (*Environment, *http.Response, error) { - return r.ApiService.GetEnvironmentExecute(r) +func (r ApiExecuteDefinitionRequest) Execute() (*ExecuteDefinitionResponse, *http.Response, error) { + return r.ApiService.ExecuteDefinitionExecute(r) } /* -GetEnvironment get environment +ExecuteDefinition Execute a definition -get environment +Execute a definition - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId - @return ApiGetEnvironmentRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiExecuteDefinitionRequest */ -func (a *ApiApiService) GetEnvironment(ctx context.Context, environmentId string) ApiGetEnvironmentRequest { - return ApiGetEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, +func (a *ApiApiService) ExecuteDefinition(ctx context.Context) ApiExecuteDefinitionRequest { + return ApiExecuteDefinitionRequest{ + ApiService: a, + ctx: ctx, } } // Execute executes the request -// -// @return Environment -func (a *ApiApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*Environment, *http.Response, error) { +// @return ExecuteDefinitionResponse +func (a *ApiApiService) ExecuteDefinitionExecute(r ApiExecuteDefinitionRequest) (*ExecuteDefinitionResponse, *http.Response, error) { var ( - localVarHTTPMethod = http.MethodGet + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *Environment + localVarReturnValue *ExecuteDefinitionResponse ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetEnvironment") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExecuteDefinition") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + localVarPath := localBasePath + "/definition.yaml" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHTTPContentTypes := []string{} + localVarHTTPContentTypes := []string{"text/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) @@ -1321,6 +795,8 @@ func (a *ApiApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*Envi if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } + // body params + localVarPostBody = r.textDefinition req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -1358,51 +834,54 @@ func (a *ApiApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*Envi return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetEnvironmentDefinitionFileRequest struct { - ctx context.Context - ApiService *ApiApiService - environmentId string +type ApiExportTestRunRequest struct { + ctx context.Context + ApiService *ApiApiService + testId string + runId int32 } -func (r ApiGetEnvironmentDefinitionFileRequest) Execute() (string, *http.Response, error) { - return r.ApiService.GetEnvironmentDefinitionFileExecute(r) +func (r ApiExportTestRunRequest) Execute() (*ExportedTestInformation, *http.Response, error) { + return r.ApiService.ExportTestRunExecute(r) } /* -GetEnvironmentDefinitionFile Get the environment definition as an YAML file +ExportTestRun export test and test run information -Get the environment as an YAML file +export test and test run information for debugging - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId - @return ApiGetEnvironmentDefinitionFileRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiExportTestRunRequest */ -func (a *ApiApiService) GetEnvironmentDefinitionFile(ctx context.Context, environmentId string) ApiGetEnvironmentDefinitionFileRequest { - return ApiGetEnvironmentDefinitionFileRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, +func (a *ApiApiService) ExportTestRun(ctx context.Context, testId string, runId int32) ApiExportTestRunRequest { + return ApiExportTestRunRequest{ + ApiService: a, + ctx: ctx, + testId: testId, + runId: runId, } } // Execute executes the request -// -// @return string -func (a *ApiApiService) GetEnvironmentDefinitionFileExecute(r ApiGetEnvironmentDefinitionFileRequest) (string, *http.Response, error) { +// @return ExportedTestInformation +func (a *ApiApiService) ExportTestRunExecute(r ApiExportTestRunRequest) (*ExportedTestInformation, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue string + localVarReturnValue *ExportedTestInformation ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetEnvironmentDefinitionFile") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExportTestRun") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments/{environmentId}/definition.yaml" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + localVarPath := localBasePath + "/tests/{testId}/run/{runId}/export" + localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1418,7 +897,7 @@ func (a *ApiApiService) GetEnvironmentDefinitionFileExecute(r ApiGetEnvironmentD } // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/yaml"} + localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) @@ -1462,104 +941,59 @@ func (a *ApiApiService) GetEnvironmentDefinitionFileExecute(r ApiGetEnvironmentD return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetEnvironmentsRequest struct { - ctx context.Context - ApiService *ApiApiService - take *int32 - skip *int32 - query *string - sortBy *string - sortDirection *string -} - -// indicates how many resources can be returned by each page -func (r ApiGetEnvironmentsRequest) Take(take int32) ApiGetEnvironmentsRequest { - r.take = &take - return r -} - -// indicates how many resources will be skipped when paginating -func (r ApiGetEnvironmentsRequest) Skip(skip int32) ApiGetEnvironmentsRequest { - r.skip = &skip - return r -} - -// query to search resources -func (r ApiGetEnvironmentsRequest) Query(query string) ApiGetEnvironmentsRequest { - r.query = &query - return r -} - -// indicates the sort field for the resources -func (r ApiGetEnvironmentsRequest) SortBy(sortBy string) ApiGetEnvironmentsRequest { - r.sortBy = &sortBy - return r +type ApiExpressionResolveRequest struct { + ctx context.Context + ApiService *ApiApiService + resolveRequestInfo *ResolveRequestInfo } -// indicates the sort direction for the resources -func (r ApiGetEnvironmentsRequest) SortDirection(sortDirection string) ApiGetEnvironmentsRequest { - r.sortDirection = &sortDirection +func (r ApiExpressionResolveRequest) ResolveRequestInfo(resolveRequestInfo ResolveRequestInfo) ApiExpressionResolveRequest { + r.resolveRequestInfo = &resolveRequestInfo return r } -func (r ApiGetEnvironmentsRequest) Execute() ([]Environment, *http.Response, error) { - return r.ApiService.GetEnvironmentsExecute(r) +func (r ApiExpressionResolveRequest) Execute() (*ResolveResponseInfo, *http.Response, error) { + return r.ApiService.ExpressionResolveExecute(r) } /* -GetEnvironments Get Environments +ExpressionResolve resolves an expression and returns the result string -Get Environments +resolves an expression and returns the result string - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetEnvironmentsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiExpressionResolveRequest */ -func (a *ApiApiService) GetEnvironments(ctx context.Context) ApiGetEnvironmentsRequest { - return ApiGetEnvironmentsRequest{ +func (a *ApiApiService) ExpressionResolve(ctx context.Context) ApiExpressionResolveRequest { + return ApiExpressionResolveRequest{ ApiService: a, ctx: ctx, } } // Execute executes the request -// -// @return []Environment -func (a *ApiApiService) GetEnvironmentsExecute(r ApiGetEnvironmentsRequest) ([]Environment, *http.Response, error) { +// @return ResolveResponseInfo +func (a *ApiApiService) ExpressionResolveExecute(r ApiExpressionResolveRequest) (*ResolveResponseInfo, *http.Response, error) { var ( - localVarHTTPMethod = http.MethodGet + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue []Environment + localVarReturnValue *ResolveResponseInfo ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetEnvironments") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.ExpressionResolve") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments" + localVarPath := localBasePath + "/expressions/resolve" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if r.take != nil { - parameterAddToQuery(localVarQueryParams, "take", r.take, "") - } - if r.skip != nil { - parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") - } - if r.query != nil { - parameterAddToQuery(localVarQueryParams, "query", r.query, "") - } - if r.sortBy != nil { - parameterAddToQuery(localVarQueryParams, "sortBy", r.sortBy, "") - } - if r.sortDirection != nil { - parameterAddToQuery(localVarQueryParams, "sortDirection", r.sortDirection, "") - } // to determine the Content-Type header - localVarHTTPContentTypes := []string{} + localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) @@ -1575,6 +1009,8 @@ func (a *ApiApiService) GetEnvironmentsExecute(r ApiGetEnvironmentsRequest) ([]E if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } + // body params + localVarPostBody = r.resolveRequestInfo req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -1661,8 +1097,8 @@ GetResources Get resources get resources - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetResourcesRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetResourcesRequest */ func (a *ApiApiService) GetResources(ctx context.Context) ApiGetResourcesRequest { return ApiGetResourcesRequest{ @@ -1672,8 +1108,7 @@ func (a *ApiApiService) GetResources(ctx context.Context) ApiGetResourcesRequest } // Execute executes the request -// -// @return []Resource +// @return []Resource func (a *ApiApiService) GetResourcesExecute(r ApiGetResourcesRequest) ([]Resource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -1778,10 +1213,10 @@ GetRunResultJUnit get test run results in JUnit xml format get test run results in JUnit xml format - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiGetRunResultJUnitRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiGetRunResultJUnitRequest */ func (a *ApiApiService) GetRunResultJUnit(ctx context.Context, testId string, runId int32) ApiGetRunResultJUnitRequest { return ApiGetRunResultJUnitRequest{ @@ -1793,8 +1228,7 @@ func (a *ApiApiService) GetRunResultJUnit(ctx context.Context, testId string, ru } // Execute executes the request -// -// @return string +// @return string func (a *ApiApiService) GetRunResultJUnitExecute(r ApiGetRunResultJUnitRequest) (string, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -1885,9 +1319,9 @@ GetTest get test get test - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiGetTestRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiGetTestRequest */ func (a *ApiApiService) GetTest(ctx context.Context, testId string) ApiGetTestRequest { return ApiGetTestRequest{ @@ -1898,8 +1332,7 @@ func (a *ApiApiService) GetTest(ctx context.Context, testId string) ApiGetTestRe } // Execute executes the request -// -// @return Test +// @return Test func (a *ApiApiService) GetTestExecute(r ApiGetTestRequest) (*Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -1997,10 +1430,10 @@ GetTestResultSelectedSpans retrieve spans that will be selected by selector get the spans ids that would be selected by a specific selector query - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiGetTestResultSelectedSpansRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiGetTestResultSelectedSpansRequest */ func (a *ApiApiService) GetTestResultSelectedSpans(ctx context.Context, testId string, runId int32) ApiGetTestResultSelectedSpansRequest { return ApiGetTestResultSelectedSpansRequest{ @@ -2012,8 +1445,7 @@ func (a *ApiApiService) GetTestResultSelectedSpans(ctx context.Context, testId s } // Execute executes the request -// -// @return SelectedSpansResult +// @return SelectedSpansResult func (a *ApiApiService) GetTestResultSelectedSpansExecute(r ApiGetTestResultSelectedSpansRequest) (*SelectedSpansResult, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2108,10 +1540,10 @@ GetTestRun get test Run get a particular test Run - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiGetTestRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiGetTestRunRequest */ func (a *ApiApiService) GetTestRun(ctx context.Context, testId string, runId int32) ApiGetTestRunRequest { return ApiGetTestRunRequest{ @@ -2123,8 +1555,7 @@ func (a *ApiApiService) GetTestRun(ctx context.Context, testId string, runId int } // Execute executes the request -// -// @return TestRun +// @return TestRun func (a *ApiApiService) GetTestRunExecute(r ApiGetTestRunRequest) (*TestRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2216,10 +1647,10 @@ GetTestRunEvents get events from a test run get events from a test run - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiGetTestRunEventsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiGetTestRunEventsRequest */ func (a *ApiApiService) GetTestRunEvents(ctx context.Context, testId string, runId int32) ApiGetTestRunEventsRequest { return ApiGetTestRunEventsRequest{ @@ -2231,8 +1662,7 @@ func (a *ApiApiService) GetTestRunEvents(ctx context.Context, testId string, run } // Execute executes the request -// -// @return []TestRunEvent +// @return []TestRunEvent func (a *ApiApiService) GetTestRunEventsExecute(r ApiGetTestRunEventsRequest) ([]TestRunEvent, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2337,9 +1767,9 @@ GetTestRuns get the runs for a test get the runs from a particular test - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiGetTestRunsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiGetTestRunsRequest */ func (a *ApiApiService) GetTestRuns(ctx context.Context, testId string) ApiGetTestRunsRequest { return ApiGetTestRunsRequest{ @@ -2350,8 +1780,7 @@ func (a *ApiApiService) GetTestRuns(ctx context.Context, testId string) ApiGetTe } // Execute executes the request -// -// @return []TestRun +// @return []TestRun func (a *ApiApiService) GetTestRunsExecute(r ApiGetTestRunsRequest) ([]TestRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2447,9 +1876,9 @@ GetTestSpecs Get definition for a test Gets definition for a test - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiGetTestSpecsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiGetTestSpecsRequest */ func (a *ApiApiService) GetTestSpecs(ctx context.Context, testId string) ApiGetTestSpecsRequest { return ApiGetTestSpecsRequest{ @@ -2460,8 +1889,7 @@ func (a *ApiApiService) GetTestSpecs(ctx context.Context, testId string) ApiGetT } // Execute executes the request -// -// @return []TestSpecs +// @return []TestSpecs func (a *ApiApiService) GetTestSpecsExecute(r ApiGetTestSpecsRequest) ([]TestSpecs, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2552,10 +1980,10 @@ GetTestVersion get a test specific version get a test specific version - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param version version of the test - @return ApiGetTestVersionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param version version of the test + @return ApiGetTestVersionRequest */ func (a *ApiApiService) GetTestVersion(ctx context.Context, testId string, version int32) ApiGetTestVersionRequest { return ApiGetTestVersionRequest{ @@ -2567,8 +1995,7 @@ func (a *ApiApiService) GetTestVersion(ctx context.Context, testId string, versi } // Execute executes the request -// -// @return Test +// @return Test func (a *ApiApiService) GetTestVersionExecute(r ApiGetTestVersionRequest) (*Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2660,10 +2087,10 @@ GetTestVersionDefinitionFile Get the test definition as an YAML file Get the test definition as an YAML file - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param version version of the test - @return ApiGetTestVersionDefinitionFileRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param version version of the test + @return ApiGetTestVersionDefinitionFileRequest */ func (a *ApiApiService) GetTestVersionDefinitionFile(ctx context.Context, testId string, version int32) ApiGetTestVersionDefinitionFileRequest { return ApiGetTestVersionDefinitionFileRequest{ @@ -2675,8 +2102,7 @@ func (a *ApiApiService) GetTestVersionDefinitionFile(ctx context.Context, testId } // Execute executes the request -// -// @return string +// @return string func (a *ApiApiService) GetTestVersionDefinitionFileExecute(r ApiGetTestVersionDefinitionFileRequest) (string, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2801,8 +2227,8 @@ GetTests Get tests get tests - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetTestsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetTestsRequest */ func (a *ApiApiService) GetTests(ctx context.Context) ApiGetTestsRequest { return ApiGetTestsRequest{ @@ -2812,8 +2238,7 @@ func (a *ApiApiService) GetTests(ctx context.Context) ApiGetTestsRequest { } // Execute executes the request -// -// @return []Test +// @return []Test func (a *ApiApiService) GetTestsExecute(r ApiGetTestsRequest) ([]Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -2917,9 +2342,9 @@ GetTransaction get transaction get transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiGetTransactionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @return ApiGetTransactionRequest */ func (a *ApiApiService) GetTransaction(ctx context.Context, transactionId string) ApiGetTransactionRequest { return ApiGetTransactionRequest{ @@ -2930,8 +2355,7 @@ func (a *ApiApiService) GetTransaction(ctx context.Context, transactionId string } // Execute executes the request -// -// @return Transaction +// @return Transaction func (a *ApiApiService) GetTransactionExecute(r ApiGetTransactionRequest) (*Transaction, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3022,10 +2446,10 @@ GetTransactionRun Get a specific run from a particular transaction Get a specific run from a particular transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @param runId id of the run - @return ApiGetTransactionRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @param runId id of the run + @return ApiGetTransactionRunRequest */ func (a *ApiApiService) GetTransactionRun(ctx context.Context, transactionId string, runId int32) ApiGetTransactionRunRequest { return ApiGetTransactionRunRequest{ @@ -3037,8 +2461,7 @@ func (a *ApiApiService) GetTransactionRun(ctx context.Context, transactionId str } // Execute executes the request -// -// @return TransactionRun +// @return TransactionRun func (a *ApiApiService) GetTransactionRunExecute(r ApiGetTransactionRunRequest) (*TransactionRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3143,9 +2566,9 @@ GetTransactionRuns Get all runs from a particular transaction Get all runs from a particular transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiGetTransactionRunsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @return ApiGetTransactionRunsRequest */ func (a *ApiApiService) GetTransactionRuns(ctx context.Context, transactionId string) ApiGetTransactionRunsRequest { return ApiGetTransactionRunsRequest{ @@ -3156,8 +2579,7 @@ func (a *ApiApiService) GetTransactionRuns(ctx context.Context, transactionId st } // Execute executes the request -// -// @return []TransactionRun +// @return []TransactionRun func (a *ApiApiService) GetTransactionRunsExecute(r ApiGetTransactionRunsRequest) ([]TransactionRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3254,10 +2676,10 @@ GetTransactionVersion get a transaction specific version get a transaction specific version - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @param version version of the test - @return ApiGetTransactionVersionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @param version version of the test + @return ApiGetTransactionVersionRequest */ func (a *ApiApiService) GetTransactionVersion(ctx context.Context, transactionId string, version int32) ApiGetTransactionVersionRequest { return ApiGetTransactionVersionRequest{ @@ -3269,8 +2691,7 @@ func (a *ApiApiService) GetTransactionVersion(ctx context.Context, transactionId } // Execute executes the request -// -// @return Transaction +// @return Transaction func (a *ApiApiService) GetTransactionVersionExecute(r ApiGetTransactionVersionRequest) (*Transaction, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3362,10 +2783,10 @@ GetTransactionVersionDefinitionFile Get the transaction definition as an YAML fi Get the transaction as an YAML file - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @param version version of the test - @return ApiGetTransactionVersionDefinitionFileRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @param version version of the test + @return ApiGetTransactionVersionDefinitionFileRequest */ func (a *ApiApiService) GetTransactionVersionDefinitionFile(ctx context.Context, transactionId string, version int32) ApiGetTransactionVersionDefinitionFileRequest { return ApiGetTransactionVersionDefinitionFileRequest{ @@ -3377,8 +2798,7 @@ func (a *ApiApiService) GetTransactionVersionDefinitionFile(ctx context.Context, } // Execute executes the request -// -// @return string +// @return string func (a *ApiApiService) GetTransactionVersionDefinitionFileExecute(r ApiGetTransactionVersionDefinitionFileRequest) (string, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3503,8 +2923,8 @@ GetTransactions Get transactions get transactions - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetTransactionsRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetTransactionsRequest */ func (a *ApiApiService) GetTransactions(ctx context.Context) ApiGetTransactionsRequest { return ApiGetTransactionsRequest{ @@ -3514,8 +2934,7 @@ func (a *ApiApiService) GetTransactions(ctx context.Context) ApiGetTransactionsR } // Execute executes the request -// -// @return []Transaction +// @return []Transaction func (a *ApiApiService) GetTransactionsExecute(r ApiGetTransactionsRequest) ([]Transaction, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -3624,8 +3043,8 @@ ImportTestRun import test and test run information import test and test run information for debugging - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiImportTestRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiImportTestRunRequest */ func (a *ApiApiService) ImportTestRun(ctx context.Context) ApiImportTestRunRequest { return ApiImportTestRunRequest{ @@ -3635,8 +3054,7 @@ func (a *ApiApiService) ImportTestRun(ctx context.Context) ApiImportTestRunReque } // Execute executes the request -// -// @return ExportedTestInformation +// @return ExportedTestInformation func (a *ApiApiService) ImportTestRunExecute(r ApiImportTestRunRequest) (*ExportedTestInformation, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -3728,10 +3146,10 @@ RerunTestRun rerun a test run rerun a test run - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiRerunTestRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiRerunTestRunRequest */ func (a *ApiApiService) RerunTestRun(ctx context.Context, testId string, runId int32) ApiRerunTestRunRequest { return ApiRerunTestRunRequest{ @@ -3743,8 +3161,7 @@ func (a *ApiApiService) RerunTestRun(ctx context.Context, testId string, runId i } // Execute executes the request -// -// @return TestRun +// @return TestRun func (a *ApiApiService) RerunTestRunExecute(r ApiRerunTestRunRequest) (*TestRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -3841,9 +3258,9 @@ RunTest run test run a particular test - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiRunTestRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiRunTestRequest */ func (a *ApiApiService) RunTest(ctx context.Context, testId string) ApiRunTestRequest { return ApiRunTestRequest{ @@ -3854,8 +3271,7 @@ func (a *ApiApiService) RunTest(ctx context.Context, testId string) ApiRunTestRe } // Execute executes the request -// -// @return TestRun +// @return TestRun func (a *ApiApiService) RunTestExecute(r ApiRunTestRequest) (*TestRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -3963,9 +3379,9 @@ RunTransaction run transaction run a particular transaction - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiRunTransactionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @return ApiRunTransactionRequest */ func (a *ApiApiService) RunTransaction(ctx context.Context, transactionId string) ApiRunTransactionRequest { return ApiRunTransactionRequest{ @@ -3976,8 +3392,7 @@ func (a *ApiApiService) RunTransaction(ctx context.Context, transactionId string } // Execute executes the request -// -// @return TransactionRun +// @return TransactionRun func (a *ApiApiService) RunTransactionExecute(r ApiRunTransactionRequest) (*TransactionRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -4070,10 +3485,10 @@ StopTestRun stops the execution of a test run stops the execution of a test run - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param runId id of the run - @return ApiStopTestRunRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @param runId id of the run + @return ApiStopTestRunRequest */ func (a *ApiApiService) StopTestRun(ctx context.Context, testId string, runId int32) ApiStopTestRunRequest { return ApiStopTestRunRequest{ @@ -4170,8 +3585,8 @@ TestConnection Tests the config data store/exporter connection Tests the config data store/exporter connection - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiTestConnectionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestConnectionRequest */ func (a *ApiApiService) TestConnection(ctx context.Context) ApiTestConnectionRequest { return ApiTestConnectionRequest{ @@ -4181,8 +3596,7 @@ func (a *ApiApiService) TestConnection(ctx context.Context) ApiTestConnectionReq } // Execute executes the request -// -// @return TestConnectionResponse +// @return TestConnectionResponse func (a *ApiApiService) TestConnectionExecute(r ApiTestConnectionRequest) (*TestConnectionResponse, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -4258,106 +3672,6 @@ func (a *ApiApiService) TestConnectionExecute(r ApiTestConnectionRequest) (*Test return localVarReturnValue, localVarHTTPResponse, nil } -type ApiUpdateEnvironmentRequest struct { - ctx context.Context - ApiService *ApiApiService - environmentId string - environment *Environment -} - -func (r ApiUpdateEnvironmentRequest) Environment(environment Environment) ApiUpdateEnvironmentRequest { - r.environment = &environment - return r -} - -func (r ApiUpdateEnvironmentRequest) Execute() (*http.Response, error) { - return r.ApiService.UpdateEnvironmentExecute(r) -} - -/* -UpdateEnvironment update environment - -update environment action - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId - @return ApiUpdateEnvironmentRequest -*/ -func (a *ApiApiService) UpdateEnvironment(ctx context.Context, environmentId string) ApiUpdateEnvironmentRequest { - return ApiUpdateEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, - } -} - -// Execute executes the request -func (a *ApiApiService) UpdateEnvironmentExecute(r ApiUpdateEnvironmentRequest) (*http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPut - localVarPostBody interface{} - formFiles []formFile - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.UpdateEnvironment") - if err != nil { - return nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.environment - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarHTTPResponse, newErr - } - - return localVarHTTPResponse, nil -} - type ApiUpdateTestRequest struct { ctx context.Context ApiService *ApiApiService @@ -4379,9 +3693,9 @@ UpdateTest update test update test action - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiUpdateTestRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param testId id of the test + @return ApiUpdateTestRequest */ func (a *ApiApiService) UpdateTest(ctx context.Context, testId string) ApiUpdateTestRequest { return ApiUpdateTestRequest{ @@ -4479,9 +3793,9 @@ UpdateTransaction update transaction update transaction action - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiUpdateTransactionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param transactionId id of the transaction + @return ApiUpdateTransactionRequest */ func (a *ApiApiService) UpdateTransaction(ctx context.Context, transactionId string) ApiUpdateTransactionRequest { return ApiUpdateTransactionRequest{ @@ -4578,8 +3892,8 @@ UpsertDefinition Upsert a definition Upsert a definition - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiUpsertDefinitionRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiUpsertDefinitionRequest */ func (a *ApiApiService) UpsertDefinition(ctx context.Context) ApiUpsertDefinitionRequest { return ApiUpsertDefinitionRequest{ @@ -4589,8 +3903,7 @@ func (a *ApiApiService) UpsertDefinition(ctx context.Context) ApiUpsertDefinitio } // Execute executes the request -// -// @return UpsertDefinitionResponse +// @return UpsertDefinitionResponse func (a *ApiApiService) UpsertDefinitionExecute(r ApiUpsertDefinitionRequest) (*UpsertDefinitionResponse, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPut diff --git a/cli/openapi/api_resource_api.go b/cli/openapi/api_resource_api.go index 9a803473f0..a7308f9ba1 100644 --- a/cli/openapi/api_resource_api.go +++ b/cli/openapi/api_resource_api.go @@ -42,8 +42,8 @@ CreateDemo Create a Demonstration setting Create a demonstration used on Tracetest as quick start examples. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateDemoRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateDemoRequest */ func (a *ResourceApiApiService) CreateDemo(ctx context.Context) ApiCreateDemoRequest { return ApiCreateDemoRequest{ @@ -53,8 +53,7 @@ func (a *ResourceApiApiService) CreateDemo(ctx context.Context) ApiCreateDemoReq } // Execute executes the request -// -// @return Demo +// @return Demo func (a *ResourceApiApiService) CreateDemoExecute(r ApiCreateDemoRequest) (*Demo, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost @@ -130,6 +129,113 @@ func (a *ResourceApiApiService) CreateDemoExecute(r ApiCreateDemoRequest) (*Demo return localVarReturnValue, localVarHTTPResponse, nil } +type ApiCreateEnvironmentRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + environmentResource *EnvironmentResource +} + +func (r ApiCreateEnvironmentRequest) EnvironmentResource(environmentResource EnvironmentResource) ApiCreateEnvironmentRequest { + r.environmentResource = &environmentResource + return r +} + +func (r ApiCreateEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { + return r.ApiService.CreateEnvironmentExecute(r) +} + +/* +CreateEnvironment Create an environment + +Create an environment that can be used by tests and transactions + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateEnvironmentRequest +*/ +func (a *ResourceApiApiService) CreateEnvironment(ctx context.Context) ApiCreateEnvironmentRequest { + return ApiCreateEnvironmentRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return EnvironmentResource +func (a *ResourceApiApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *EnvironmentResource + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json", "text/yaml"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.environmentResource + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiDeleteDataStoreRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -145,9 +251,9 @@ DeleteDataStore Delete a Data Store Delete a Data Store - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test - @return ApiDeleteDataStoreRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test + @return ApiDeleteDataStoreRequest */ func (a *ResourceApiApiService) DeleteDataStore(ctx context.Context, dataStoreId string) ApiDeleteDataStoreRequest { return ApiDeleteDataStoreRequest{ @@ -237,9 +343,9 @@ DeleteDemo Delete a Demonstration setting Delete a demonstration used on Tracetest as quick start examples. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param demoId ID of a demonstration used on Tracetest as quick start examples - @return ApiDeleteDemoRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param demoId ID of a demonstration used on Tracetest as quick start examples + @return ApiDeleteDemoRequest */ func (a *ResourceApiApiService) DeleteDemo(ctx context.Context, demoId string) ApiDeleteDemoRequest { return ApiDeleteDemoRequest{ @@ -314,6 +420,98 @@ func (a *ResourceApiApiService) DeleteDemoExecute(r ApiDeleteDemoRequest) (*http return localVarHTTPResponse, nil } +type ApiDeleteEnvironmentRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + environmentId string +} + +func (r ApiDeleteEnvironmentRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteEnvironmentExecute(r) +} + +/* +DeleteEnvironment Delete an environment + +Delete an environment from Tracetest + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param environmentId ID of an enviroment used on Tracetest to inject values into tests and transactions + @return ApiDeleteEnvironmentRequest +*/ +func (a *ResourceApiApiService) DeleteEnvironment(ctx context.Context, environmentId string) ApiDeleteEnvironmentRequest { + return ApiDeleteEnvironmentRequest{ + ApiService: a, + ctx: ctx, + environmentId: environmentId, + } +} + +// Execute executes the request +func (a *ResourceApiApiService) DeleteEnvironmentExecute(r ApiDeleteEnvironmentRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteEnvironment") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments/{environmentId}" + localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + type ApiGetConfigurationRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -329,9 +527,9 @@ GetConfiguration Get Tracetest configuration Get Tracetest configuration - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param configId ID of the configuration resource used on Tracetest. It should be set as 'current' - @return ApiGetConfigurationRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param configId ID of the configuration resource used on Tracetest. It should be set as 'current' + @return ApiGetConfigurationRequest */ func (a *ResourceApiApiService) GetConfiguration(ctx context.Context, configId string) ApiGetConfigurationRequest { return ApiGetConfigurationRequest{ @@ -342,8 +540,7 @@ func (a *ResourceApiApiService) GetConfiguration(ctx context.Context, configId s } // Execute executes the request -// -// @return ConfigurationResource +// @return ConfigurationResource func (a *ResourceApiApiService) GetConfigurationExecute(r ApiGetConfigurationRequest) (*ConfigurationResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -433,9 +630,9 @@ GetDataStore Get a Data Store Get a Data Store - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test - @return ApiGetDataStoreRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test + @return ApiGetDataStoreRequest */ func (a *ResourceApiApiService) GetDataStore(ctx context.Context, dataStoreId string) ApiGetDataStoreRequest { return ApiGetDataStoreRequest{ @@ -446,8 +643,7 @@ func (a *ResourceApiApiService) GetDataStore(ctx context.Context, dataStoreId st } // Execute executes the request -// -// @return DataStoreResource +// @return DataStoreResource func (a *ResourceApiApiService) GetDataStoreExecute(r ApiGetDataStoreRequest) (*DataStoreResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -537,9 +733,9 @@ GetDemo Get Demonstration setting Get a demonstration used on Tracetest as quick start examples. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param demoId ID of a demonstration used on Tracetest as quick start examples - @return ApiGetDemoRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param demoId ID of a demonstration used on Tracetest as quick start examples + @return ApiGetDemoRequest */ func (a *ResourceApiApiService) GetDemo(ctx context.Context, demoId string) ApiGetDemoRequest { return ApiGetDemoRequest{ @@ -550,8 +746,7 @@ func (a *ResourceApiApiService) GetDemo(ctx context.Context, demoId string) ApiG } // Execute executes the request -// -// @return Demo +// @return Demo func (a *ResourceApiApiService) GetDemoExecute(r ApiGetDemoRequest) (*Demo, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -626,6 +821,109 @@ func (a *ResourceApiApiService) GetDemoExecute(r ApiGetDemoRequest) (*Demo, *htt return localVarReturnValue, localVarHTTPResponse, nil } +type ApiGetEnvironmentRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + environmentId string +} + +func (r ApiGetEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { + return r.ApiService.GetEnvironmentExecute(r) +} + +/* +GetEnvironment Get a specific environment + +Get one environment by its id + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param environmentId ID of an enviroment used on Tracetest to inject values into tests and transactions + @return ApiGetEnvironmentRequest +*/ +func (a *ResourceApiApiService) GetEnvironment(ctx context.Context, environmentId string) ApiGetEnvironmentRequest { + return ApiGetEnvironmentRequest{ + ApiService: a, + ctx: ctx, + environmentId: environmentId, + } +} + +// Execute executes the request +// @return EnvironmentResource +func (a *ResourceApiApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *EnvironmentResource + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments/{environmentId}" + localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiGetPollingProfileRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -641,9 +939,9 @@ GetPollingProfile Get Polling Profile Get a polling profile used on Tracetest to configure how to fetch traces in a test. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param pollingProfileId ID of a polling profile used on Tracetest to configure how to fetch traces in a test. It should be set as 'current' - @return ApiGetPollingProfileRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param pollingProfileId ID of a polling profile used on Tracetest to configure how to fetch traces in a test. It should be set as 'current' + @return ApiGetPollingProfileRequest */ func (a *ResourceApiApiService) GetPollingProfile(ctx context.Context, pollingProfileId string) ApiGetPollingProfileRequest { return ApiGetPollingProfileRequest{ @@ -654,8 +952,7 @@ func (a *ResourceApiApiService) GetPollingProfile(ctx context.Context, pollingPr } // Execute executes the request -// -// @return PollingProfile +// @return PollingProfile func (a *ResourceApiApiService) GetPollingProfileExecute(r ApiGetPollingProfileRequest) (*PollingProfile, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -772,8 +1069,8 @@ ListDemos List Demonstrations List demonstrations used on Tracetest as quick start examples. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListDemosRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListDemosRequest */ func (a *ResourceApiApiService) ListDemos(ctx context.Context) ApiListDemosRequest { return ApiListDemosRequest{ @@ -783,8 +1080,7 @@ func (a *ResourceApiApiService) ListDemos(ctx context.Context) ApiListDemosReque } // Execute executes the request -// -// @return ListDemos200Response +// @return ListDemos200Response func (a *ResourceApiApiService) ListDemosExecute(r ApiListDemosRequest) (*ListDemos200Response, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet @@ -870,6 +1166,145 @@ func (a *ResourceApiApiService) ListDemosExecute(r ApiListDemosRequest) (*ListDe return localVarReturnValue, localVarHTTPResponse, nil } +type ApiListEnvironmentsRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + take *int32 + skip *int32 + sortBy *string + sortDirection *string +} + +// indicates how many resources can be returned by each page +func (r ApiListEnvironmentsRequest) Take(take int32) ApiListEnvironmentsRequest { + r.take = &take + return r +} + +// indicates how many resources will be skipped when paginating +func (r ApiListEnvironmentsRequest) Skip(skip int32) ApiListEnvironmentsRequest { + r.skip = &skip + return r +} + +// indicates the sort field for the resources +func (r ApiListEnvironmentsRequest) SortBy(sortBy string) ApiListEnvironmentsRequest { + r.sortBy = &sortBy + return r +} + +// indicates the sort direction for the resources +func (r ApiListEnvironmentsRequest) SortDirection(sortDirection string) ApiListEnvironmentsRequest { + r.sortDirection = &sortDirection + return r +} + +func (r ApiListEnvironmentsRequest) Execute() (*ListEnvironments200Response, *http.Response, error) { + return r.ApiService.ListEnvironmentsExecute(r) +} + +/* +ListEnvironments List environments + +List environments available in Tracetest. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListEnvironmentsRequest +*/ +func (a *ResourceApiApiService) ListEnvironments(ctx context.Context) ApiListEnvironmentsRequest { + return ApiListEnvironmentsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return ListEnvironments200Response +func (a *ResourceApiApiService) ListEnvironmentsExecute(r ApiListEnvironmentsRequest) (*ListEnvironments200Response, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *ListEnvironments200Response + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListEnvironments") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.take != nil { + parameterAddToQuery(localVarQueryParams, "take", r.take, "") + } + if r.skip != nil { + parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") + } + if r.sortBy != nil { + parameterAddToQuery(localVarQueryParams, "sortBy", r.sortBy, "") + } + if r.sortDirection != nil { + parameterAddToQuery(localVarQueryParams, "sortDirection", r.sortDirection, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiUpdateConfigurationRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -891,9 +1326,9 @@ UpdateConfiguration Update Tracetest configuration Update Tracetest configuration - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param configId ID of the configuration resource used on Tracetest. It should be set as 'current' - @return ApiUpdateConfigurationRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param configId ID of the configuration resource used on Tracetest. It should be set as 'current' + @return ApiUpdateConfigurationRequest */ func (a *ResourceApiApiService) UpdateConfiguration(ctx context.Context, configId string) ApiUpdateConfigurationRequest { return ApiUpdateConfigurationRequest{ @@ -904,8 +1339,7 @@ func (a *ResourceApiApiService) UpdateConfiguration(ctx context.Context, configI } // Execute executes the request -// -// @return ConfigurationResource +// @return ConfigurationResource func (a *ResourceApiApiService) UpdateConfigurationExecute(r ApiUpdateConfigurationRequest) (*ConfigurationResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPut @@ -1003,9 +1437,9 @@ UpdateDataStore Update a Data Store Update a Data Store - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test - @return ApiUpdateDataStoreRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param dataStoreId ID of a datastore used on Tracetest to configure how to fetch traces in a test + @return ApiUpdateDataStoreRequest */ func (a *ResourceApiApiService) UpdateDataStore(ctx context.Context, dataStoreId string) ApiUpdateDataStoreRequest { return ApiUpdateDataStoreRequest{ @@ -1103,9 +1537,9 @@ UpdateDemo Update a Demonstration setting Update a demonstration used on Tracetest as quick start examples. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param demoId ID of a demonstration used on Tracetest as quick start examples - @return ApiUpdateDemoRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param demoId ID of a demonstration used on Tracetest as quick start examples + @return ApiUpdateDemoRequest */ func (a *ResourceApiApiService) UpdateDemo(ctx context.Context, demoId string) ApiUpdateDemoRequest { return ApiUpdateDemoRequest{ @@ -1116,8 +1550,7 @@ func (a *ResourceApiApiService) UpdateDemo(ctx context.Context, demoId string) A } // Execute executes the request -// -// @return Demo +// @return Demo func (a *ResourceApiApiService) UpdateDemoExecute(r ApiUpdateDemoRequest) (*Demo, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPut @@ -1194,6 +1627,117 @@ func (a *ResourceApiApiService) UpdateDemoExecute(r ApiUpdateDemoRequest) (*Demo return localVarReturnValue, localVarHTTPResponse, nil } +type ApiUpdateEnvironmentRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + environmentId string + environmentResource *EnvironmentResource +} + +func (r ApiUpdateEnvironmentRequest) EnvironmentResource(environmentResource EnvironmentResource) ApiUpdateEnvironmentRequest { + r.environmentResource = &environmentResource + return r +} + +func (r ApiUpdateEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { + return r.ApiService.UpdateEnvironmentExecute(r) +} + +/* +UpdateEnvironment Update an environment + +Update an environment used on Tracetest + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param environmentId ID of an enviroment used on Tracetest to inject values into tests and transactions + @return ApiUpdateEnvironmentRequest +*/ +func (a *ResourceApiApiService) UpdateEnvironment(ctx context.Context, environmentId string) ApiUpdateEnvironmentRequest { + return ApiUpdateEnvironmentRequest{ + ApiService: a, + ctx: ctx, + environmentId: environmentId, + } +} + +// Execute executes the request +// @return EnvironmentResource +func (a *ResourceApiApiService) UpdateEnvironmentExecute(r ApiUpdateEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *EnvironmentResource + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.UpdateEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments/{environmentId}" + localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json", "text/yaml"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.environmentResource + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiUpdatePollingProfileRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -1215,9 +1759,9 @@ UpdatePollingProfile Update a Polling Profile Update a polling profile used on Tracetest to configure how to fetch traces in a test. - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param pollingProfileId ID of a polling profile used on Tracetest to configure how to fetch traces in a test. It should be set as 'current' - @return ApiUpdatePollingProfileRequest + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param pollingProfileId ID of a polling profile used on Tracetest to configure how to fetch traces in a test. It should be set as 'current' + @return ApiUpdatePollingProfileRequest */ func (a *ResourceApiApiService) UpdatePollingProfile(ctx context.Context, pollingProfileId string) ApiUpdatePollingProfileRequest { return ApiUpdatePollingProfileRequest{ @@ -1228,8 +1772,7 @@ func (a *ResourceApiApiService) UpdatePollingProfile(ctx context.Context, pollin } // Execute executes the request -// -// @return PollingProfile +// @return PollingProfile func (a *ResourceApiApiService) UpdatePollingProfileExecute(r ApiUpdatePollingProfileRequest) (*PollingProfile, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPut diff --git a/cli/openapi/model_environment_resource.go b/cli/openapi/model_environment_resource.go new file mode 100644 index 0000000000..ec1b29a3e4 --- /dev/null +++ b/cli/openapi/model_environment_resource.go @@ -0,0 +1,161 @@ +/* +TraceTest + +OpenAPI definition for TraceTest endpoint and resources + +API version: 0.2.1 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the EnvironmentResource type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvironmentResource{} + +// EnvironmentResource Represents an environment structured into the Resources format. +type EnvironmentResource struct { + // Represents the type of this resource. It should always be set as 'Environment'. + Type *string `json:"type,omitempty"` + Spec *Environment `json:"spec,omitempty"` +} + +// NewEnvironmentResource instantiates a new EnvironmentResource object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentResource() *EnvironmentResource { + this := EnvironmentResource{} + return &this +} + +// NewEnvironmentResourceWithDefaults instantiates a new EnvironmentResource object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentResourceWithDefaults() *EnvironmentResource { + this := EnvironmentResource{} + return &this +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *EnvironmentResource) GetType() string { + if o == nil || isNil(o.Type) { + var ret string + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentResource) GetTypeOk() (*string, bool) { + if o == nil || isNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *EnvironmentResource) HasType() bool { + if o != nil && !isNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given string and assigns it to the Type field. +func (o *EnvironmentResource) SetType(v string) { + o.Type = &v +} + +// GetSpec returns the Spec field value if set, zero value otherwise. +func (o *EnvironmentResource) GetSpec() Environment { + if o == nil || isNil(o.Spec) { + var ret Environment + return ret + } + return *o.Spec +} + +// GetSpecOk returns a tuple with the Spec field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentResource) GetSpecOk() (*Environment, bool) { + if o == nil || isNil(o.Spec) { + return nil, false + } + return o.Spec, true +} + +// HasSpec returns a boolean if a field has been set. +func (o *EnvironmentResource) HasSpec() bool { + if o != nil && !isNil(o.Spec) { + return true + } + + return false +} + +// SetSpec gets a reference to the given Environment and assigns it to the Spec field. +func (o *EnvironmentResource) SetSpec(v Environment) { + o.Spec = &v +} + +func (o EnvironmentResource) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvironmentResource) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !isNil(o.Type) { + toSerialize["type"] = o.Type + } + if !isNil(o.Spec) { + toSerialize["spec"] = o.Spec + } + return toSerialize, nil +} + +type NullableEnvironmentResource struct { + value *EnvironmentResource + isSet bool +} + +func (v NullableEnvironmentResource) Get() *EnvironmentResource { + return v.value +} + +func (v *NullableEnvironmentResource) Set(val *EnvironmentResource) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentResource) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentResource) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentResource(val *EnvironmentResource) *NullableEnvironmentResource { + return &NullableEnvironmentResource{value: val, isSet: true} +} + +func (v NullableEnvironmentResource) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentResource) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/cli/openapi/model_list_environments_200_response.go b/cli/openapi/model_list_environments_200_response.go new file mode 100644 index 0000000000..149e59f2b3 --- /dev/null +++ b/cli/openapi/model_list_environments_200_response.go @@ -0,0 +1,160 @@ +/* +TraceTest + +OpenAPI definition for TraceTest endpoint and resources + +API version: 0.2.1 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the ListEnvironments200Response type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ListEnvironments200Response{} + +// ListEnvironments200Response struct for ListEnvironments200Response +type ListEnvironments200Response struct { + Count *int32 `json:"count,omitempty"` + Items []EnvironmentResource `json:"items,omitempty"` +} + +// NewListEnvironments200Response instantiates a new ListEnvironments200Response object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewListEnvironments200Response() *ListEnvironments200Response { + this := ListEnvironments200Response{} + return &this +} + +// NewListEnvironments200ResponseWithDefaults instantiates a new ListEnvironments200Response object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewListEnvironments200ResponseWithDefaults() *ListEnvironments200Response { + this := ListEnvironments200Response{} + return &this +} + +// GetCount returns the Count field value if set, zero value otherwise. +func (o *ListEnvironments200Response) GetCount() int32 { + if o == nil || isNil(o.Count) { + var ret int32 + return ret + } + return *o.Count +} + +// GetCountOk returns a tuple with the Count field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ListEnvironments200Response) GetCountOk() (*int32, bool) { + if o == nil || isNil(o.Count) { + return nil, false + } + return o.Count, true +} + +// HasCount returns a boolean if a field has been set. +func (o *ListEnvironments200Response) HasCount() bool { + if o != nil && !isNil(o.Count) { + return true + } + + return false +} + +// SetCount gets a reference to the given int32 and assigns it to the Count field. +func (o *ListEnvironments200Response) SetCount(v int32) { + o.Count = &v +} + +// GetItems returns the Items field value if set, zero value otherwise. +func (o *ListEnvironments200Response) GetItems() []EnvironmentResource { + if o == nil || isNil(o.Items) { + var ret []EnvironmentResource + return ret + } + return o.Items +} + +// GetItemsOk returns a tuple with the Items field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ListEnvironments200Response) GetItemsOk() ([]EnvironmentResource, bool) { + if o == nil || isNil(o.Items) { + return nil, false + } + return o.Items, true +} + +// HasItems returns a boolean if a field has been set. +func (o *ListEnvironments200Response) HasItems() bool { + if o != nil && !isNil(o.Items) { + return true + } + + return false +} + +// SetItems gets a reference to the given []EnvironmentResource and assigns it to the Items field. +func (o *ListEnvironments200Response) SetItems(v []EnvironmentResource) { + o.Items = v +} + +func (o ListEnvironments200Response) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ListEnvironments200Response) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !isNil(o.Count) { + toSerialize["count"] = o.Count + } + if !isNil(o.Items) { + toSerialize["items"] = o.Items + } + return toSerialize, nil +} + +type NullableListEnvironments200Response struct { + value *ListEnvironments200Response + isSet bool +} + +func (v NullableListEnvironments200Response) Get() *ListEnvironments200Response { + return v.value +} + +func (v *NullableListEnvironments200Response) Set(val *ListEnvironments200Response) { + v.value = val + v.isSet = true +} + +func (v NullableListEnvironments200Response) IsSet() bool { + return v.isSet +} + +func (v *NullableListEnvironments200Response) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableListEnvironments200Response(val *ListEnvironments200Response) *NullableListEnvironments200Response { + return &NullableListEnvironments200Response{value: val, isSet: true} +} + +func (v NullableListEnvironments200Response) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableListEnvironments200Response) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/cli/utils/api.go b/cli/utils/api.go index 0efd1a0e09..149fbd4873 100644 --- a/cli/utils/api.go +++ b/cli/utils/api.go @@ -87,36 +87,37 @@ func (resourceClient ResourceClient) NewRequest(url string, method string, body return request, err } -func (resourceClient ResourceClient) Update(ctx context.Context, file file.File, ID string) error { +func (resourceClient ResourceClient) Update(ctx context.Context, file file.File, ID string) (*file.File, error) { url := fmt.Sprintf("%s/%s", resourceClient.BaseUrl, ID) request, err := resourceClient.NewRequest(url, http.MethodPut, file.Contents()) if err != nil { - return fmt.Errorf("could not create request: %w", err) + return nil, fmt.Errorf("could not create request: %w", err) } resp, err := resourceClient.Client.Do(request) if err != nil { - return fmt.Errorf("could not update %s: %w", resourceClient.ResourceType, err) + return nil, fmt.Errorf("could not update %s: %w", resourceClient.ResourceType, err) } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("%s id doesn't exist on server. Remove it from the definition file and try again", resourceClient.ResourceType) + return nil, fmt.Errorf("%s id doesn't exist on server. Remove it from the definition file and try again", resourceClient.ResourceType) } - if resp.StatusCode == http.StatusUnprocessableEntity { + if resp.StatusCode == http.StatusUnprocessableEntity || resp.StatusCode == http.StatusBadRequest { // validation error body, err := ioutil.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("could not send request: %w", err) + return nil, fmt.Errorf("could not send request: %w", err) } validationError := string(body) - return fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) + return nil, fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) } - _, err = file.SaveChanges(IOReadCloserToString(resp.Body)) - return err + file = file.SaveChanges(IOReadCloserToString(resp.Body)) + + return &file, nil } func (resourceClient ResourceClient) Delete(ctx context.Context, ID string) error { @@ -130,56 +131,65 @@ func (resourceClient ResourceClient) Delete(ctx context.Context, ID string) erro return err } -func (resourceClient ResourceClient) Get(ctx context.Context, id string) (string, error) { +func (resourceClient ResourceClient) Get(ctx context.Context, id string) (*file.File, error) { request, err := resourceClient.NewRequest(fmt.Sprintf("%s/%s", resourceClient.BaseUrl, id), http.MethodGet, "") if err != nil { - return "", fmt.Errorf("could not create request: %w", err) + return nil, fmt.Errorf("could not create request: %w", err) } resp, err := resourceClient.Client.Do(request) if err != nil { - return "", fmt.Errorf("could not get %s: %w", resourceClient.ResourceType, err) + return nil, fmt.Errorf("could not get %s: %w", resourceClient.ResourceType, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, err := ioutil.ReadAll(resp.Body) if err != nil { - return "", err + return nil, err } validationError := string(body) - return "", fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) + return nil, fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) + } + + file, err := file.NewFromRaw(fmt.Sprintf("%s_%s.yaml", resourceClient.ResourceType, id), []byte(IOReadCloserToString(resp.Body))) + if err != nil { + return nil, err } - return IOReadCloserToString(resp.Body), nil + return &file, nil } -func (resourceClient ResourceClient) List(ctx context.Context, listArgs ListArgs) (string, error) { +func (resourceClient ResourceClient) List(ctx context.Context, listArgs ListArgs) (*file.File, error) { url := fmt.Sprintf("%s?skip=%d&take=%d&sortBy=%s&sortDirection=%s", resourceClient.BaseUrl, listArgs.Skip, listArgs.Take, listArgs.SortBy, listArgs.SortDirection) request, err := resourceClient.NewRequest(url, http.MethodGet, "") if err != nil { - return "", fmt.Errorf("could not create request: %w", err) + return nil, fmt.Errorf("could not create request: %w", err) } resp, err := resourceClient.Client.Do(request) if err != nil { - return "", fmt.Errorf("could not send request: %w", err) + return nil, fmt.Errorf("could not send request: %w", err) } - defer resp.Body.Close() - return IOReadCloserToString(resp.Body), nil + file, err := file.NewFromRaw(fmt.Sprintf("%s_list.yaml", resourceClient.ResourceType), []byte(IOReadCloserToString(resp.Body))) + if err != nil { + return nil, err + } + + return &file, nil } -func (resourceClient ResourceClient) Create(ctx context.Context, file file.File) error { +func (resourceClient ResourceClient) Create(ctx context.Context, file file.File) (*file.File, error) { request, err := resourceClient.NewRequest(resourceClient.BaseUrl, http.MethodPost, file.Contents()) if err != nil { - return fmt.Errorf("could not create request: %w", err) + return nil, fmt.Errorf("could not create request: %w", err) } resp, err := resourceClient.Client.Do(request) if err != nil { - return fmt.Errorf("could not send request: %w", err) + return nil, fmt.Errorf("could not send request: %w", err) } defer resp.Body.Close() @@ -187,16 +197,16 @@ func (resourceClient ResourceClient) Create(ctx context.Context, file file.File) // validation error body, err := ioutil.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("could not send request: %w", err) + return nil, fmt.Errorf("could not send request: %w", err) } validationError := string(body) - return fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) + return nil, fmt.Errorf("invalid %s: %s", resourceClient.ResourceType, validationError) } if err != nil { - return fmt.Errorf("could not create %s: %w", resourceClient.ResourceType, err) + return nil, fmt.Errorf("could not create %s: %w", resourceClient.ResourceType, err) } - _, err = file.SaveChanges(IOReadCloserToString(resp.Body)) - return err + file = file.SaveChanges(IOReadCloserToString(resp.Body)) + return &file, nil } diff --git a/cli/utils/common.go b/cli/utils/common.go index 433c18c161..30c50952d7 100644 --- a/cli/utils/common.go +++ b/cli/utils/common.go @@ -2,6 +2,8 @@ package utils import ( "io" + "os" + "path/filepath" "strings" ) @@ -13,3 +15,22 @@ func IOReadCloserToString(r io.ReadCloser) string { b, _ := io.ReadAll(r) return string(b) } + +func StringReferencesFile(path string) bool { + // for the current working dir, check if the file exists + // by finding its absolute path and executing a stat command + + absolutePath, err := filepath.Abs(path) + if err != nil { + return false + } + + info, err := os.Stat(absolutePath) + if err != nil { + return false + } + + // if the string is empty the absolute path will the entire dir + // otherwise the user also could send a directory by mistake + return info != nil && !info.IsDir() +} diff --git a/docs/docs/cli/creating-environments.md b/docs/docs/cli/creating-environments.md index cbcf278d0d..edf3f3e587 100644 --- a/docs/docs/cli/creating-environments.md +++ b/docs/docs/cli/creating-environments.md @@ -19,7 +19,7 @@ spec: In order to apply this configuration to your Tracetest instance, make sure to have your [CLI configured](./configuring-your-cli.md) and run: ``` -tracetest environment apply -f +tracetest apply environment -f ``` > If the file contains the property `spec.id`, the operation will be considered an environment udpate. If you try to apply an environment and you get an error: `could not apply environment: 404 Not Found`, it means the provided id doesn't exist. Either update the id to reference an existing environment, or just remove the property from the file, so Tracetest will create a new environmenta and a new id. diff --git a/server/app/app.go b/server/app/app.go index e6fdb110aa..79d22f879b 100644 --- a/server/app/app.go +++ b/server/app/app.go @@ -15,6 +15,7 @@ import ( "github.com/kubeshop/tracetest/server/config" "github.com/kubeshop/tracetest/server/config/configresource" "github.com/kubeshop/tracetest/server/config/demoresource" + "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor" "github.com/kubeshop/tracetest/server/executor/pollingprofile" "github.com/kubeshop/tracetest/server/executor/trigger" @@ -189,6 +190,7 @@ func (app *App) Start(opts ...appOption) error { pollingProfileRepo := pollingprofile.NewRepository(db) dataStoreRepo := datastoreresource.NewRepository(db) + environmentRepo := environment.NewRepository(db) eventEmitter := executor.NewEventEmitter(testDB, subscriptionManager) registerOtlpServer(app, testDB, eventEmitter, dataStoreRepo) @@ -238,14 +240,15 @@ func (app *App) Start(opts ...appOption) error { registerWSHandler(router, mappers, subscriptionManager) apiRouter := router.PathPrefix("/api").Subrouter() - registerConfigResource(configRepo, apiRouter, db, provisioner) + registerConfigResource(configRepo, apiRouter, db, provisioner, tracer) - registerPollingProfilesResource(pollingProfileRepo, apiRouter, db, provisioner) + registerPollingProfilesResource(pollingProfileRepo, apiRouter, db, provisioner, tracer) + registerEnvironmentResource(&environmentRepo, apiRouter, db, provisioner, tracer) demoRepo := demoresource.NewRepository(db) - registerDemosResource(demoRepo, apiRouter, db, provisioner) + registerDemosResource(demoRepo, apiRouter, db, provisioner, tracer) - registerDataStoreResource(dataStoreRepo, apiRouter, db, provisioner) + registerDataStoreResource(dataStoreRepo, apiRouter, db, provisioner, tracer) registerSPAHandler(router, app.cfg, configFromDB.IsAnalyticsEnabled(), serverID) @@ -299,45 +302,61 @@ func registerOtlpServer(app *App, testDB model.Repository, eventEmitter executor }) } -func registerConfigResource(configRepo *configresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner) { +func registerConfigResource(configRepo *configresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) { manager := resourcemanager.New[configresource.Config]( configresource.ResourceName, configresource.ResourceNamePlural, configRepo, resourcemanager.WithOperations(configresource.Operations...), + resourcemanager.WithTracer(tracer), ) manager.RegisterRoutes(router) provisioner.AddResourceProvisioner(manager) } -func registerPollingProfilesResource(repository *pollingprofile.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner) { +func registerPollingProfilesResource(repository *pollingprofile.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) { manager := resourcemanager.New[pollingprofile.PollingProfile]( pollingprofile.ResourceName, pollingprofile.ResourceNamePlural, repository, resourcemanager.WithOperations(pollingprofile.Operations...), + resourcemanager.WithTracer(tracer), ) manager.RegisterRoutes(router) provisioner.AddResourceProvisioner(manager) } -func registerDemosResource(repository *demoresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner) { +func registerEnvironmentResource(repository *environment.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) { + manager := resourcemanager.New[environment.Environment]( + environment.ResourceName, + environment.ResourceNamePlural, + repository, + resourcemanager.WithOperations(environment.Operations...), + resourcemanager.WithTracer(tracer), + ) + manager.RegisterRoutes(router) + provisioner.AddResourceProvisioner(manager) +} + +func registerDemosResource(repository *demoresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) { manager := resourcemanager.New[demoresource.Demo]( demoresource.ResourceName, demoresource.ResourceNamePlural, repository, resourcemanager.WithOperations(demoresource.Operations...), + resourcemanager.WithTracer(tracer), ) manager.RegisterRoutes(router) provisioner.AddResourceProvisioner(manager) } -func registerDataStoreResource(repository *datastoreresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner) { +func registerDataStoreResource(repository *datastoreresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) { manager := resourcemanager.New[datastoreresource.DataStore]( datastoreresource.ResourceName, datastoreresource.ResourceNamePlural, repository, resourcemanager.WithOperations(datastoreresource.Operations...), + resourcemanager.WithTracer(tracer), ) manager.RegisterRoutes(router) provisioner.AddResourceProvisioner(manager) diff --git a/server/environment/main_test.go b/server/environment/main_test.go new file mode 100644 index 0000000000..8ce556f336 --- /dev/null +++ b/server/environment/main_test.go @@ -0,0 +1,18 @@ +package environment_test + +import ( + "os" + "testing" + + "github.com/kubeshop/tracetest/server/testmock" +) + +func TestMain(m *testing.M) { + testmock.StartTestEnvironment() + + exitVal := m.Run() + + testmock.StopTestEnvironment() + + os.Exit(exitVal) +} diff --git a/server/environment/manager.go b/server/environment/manager.go new file mode 100644 index 0000000000..7e74201b10 --- /dev/null +++ b/server/environment/manager.go @@ -0,0 +1,330 @@ +package environment + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/kubeshop/tracetest/server/pkg/id" + "github.com/kubeshop/tracetest/server/resourcemanager" +) + +type Repository struct { + db *sql.DB +} + +func NewRepository(db *sql.DB) Repository { + return Repository{db} +} + +type scanner interface { + Scan(dest ...interface{}) error +} + +const ( + insertQuery = ` + INSERT INTO environments ( + "id", + "name", + "description", + "created_at", + "values" + ) VALUES ($1, $2, $3, $4, $5)` + + updateQuery = ` + UPDATE environments SET + "id" = $2, + "name" = $3, + "description" = $4, + "created_at" = $5, + "values" = $6 + WHERE id = $1 + ` + + getQuery = ` + SELECT + e.id, + e.name, + e.description, + e.created_at, + e.values + FROM environments e +` + + deleteQuery = "DELETE FROM environments WHERE id = $1" + + idExistsQuery = ` + SELECT COUNT(*) > 0 as exists FROM environments WHERE id = $1 + ` + + countQuery = ` + SELECT COUNT(*) FROM environments e + ` +) + +var _ resourcemanager.Create[Environment] = &Repository{} +var _ resourcemanager.Delete[Environment] = &Repository{} +var _ resourcemanager.Get[Environment] = &Repository{} +var _ resourcemanager.List[Environment] = &Repository{} +var _ resourcemanager.Update[Environment] = &Repository{} +var _ resourcemanager.IDSetter[Environment] = &Repository{} +var _ resourcemanager.Provision[Environment] = &Repository{} + +func (*Repository) SortingFields() []string { + return []string{"name", "createdAt"} +} + +func (r *Repository) SetID(environment Environment, id id.ID) Environment { + environment.ID = id + return environment +} + +func (r *Repository) Create(ctx context.Context, environment Environment) (Environment, error) { + environment.ID = environment.Slug() + environment.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano) + + return r.insertIntoEnvironments(ctx, environment) +} + +func (r *Repository) Update(ctx context.Context, environment Environment) (Environment, error) { + oldEnvironment, err := r.Get(ctx, environment.ID) + if err != nil { + return Environment{}, err + } + + // keep the same creation date to keep sort order + environment.CreatedAt = oldEnvironment.CreatedAt + environment.ID = oldEnvironment.ID + + return r.updateIntoEnvironments(ctx, environment, oldEnvironment.ID) +} + +func (r *Repository) Delete(ctx context.Context, id id.ID) error { + _, err := r.Get(ctx, id) + if err != nil { + return err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("sql BeginTx: %w", err) + } + defer tx.Rollback() + + _, err = tx.ExecContext(ctx, deleteQuery, id) + if err != nil { + return fmt.Errorf("sql error: %w", err) + } + + err = tx.Commit() + if err != nil { + return fmt.Errorf("sql Commit: %w", err) + } + + return nil +} + +func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Environment, error) { + if take == 0 { + take = 20 + } + + params := []any{take, skip} + + sql := getQuery + + const condition = "WHERE (e.name ilike $3 OR e.description ilike $3) " + if query != "" { + sql += condition + params = append(params, query) + } + + sortingFields := map[string]string{ + "created": "e.created_at", + "name": "e.name", + } + + sql = sortQuery(sql, sortBy, sortDirection, sortingFields) + sql += ` LIMIT $1 OFFSET $2 ` + + stmt, err := r.db.Prepare(sql) + if err != nil { + return []Environment{}, err + } + defer stmt.Close() + + rows, err := stmt.QueryContext(ctx, params...) + if err != nil { + return []Environment{}, err + } + + environments := []Environment{} + + for rows.Next() { + environment, err := r.readEnvironmentRow(ctx, rows) + if err != nil { + return []Environment{}, err + } + + environments = append(environments, environment) + } + + return environments, nil +} + +func (r *Repository) Count(ctx context.Context, query string) (int, error) { + return r.countEnvironments(ctx, query) +} + +func sortQuery(sql, sortBy, sortDirection string, sortingFields map[string]string) string { + sortField, ok := sortingFields[sortBy] + + if !ok { + sortField = sortingFields["created"] + } + + dir := "DESC" + if strings.ToLower(sortDirection) == "asc" { + dir = "ASC" + } + + return fmt.Sprintf("%s ORDER BY %s %s", sql, sortField, dir) +} + +func (r *Repository) Get(ctx context.Context, id id.ID) (Environment, error) { + stmt, err := r.db.Prepare(getQuery + " WHERE e.id = $1") + + if err != nil { + return Environment{}, fmt.Errorf("prepare: %w", err) + } + defer stmt.Close() + + environment, err := r.readEnvironmentRow(ctx, stmt.QueryRowContext(ctx, id)) + if err != nil { + return Environment{}, err + } + + return environment, nil +} + +func (r *Repository) EnvironmentIDExists(ctx context.Context, id string) (bool, error) { + exists := false + + row := r.db.QueryRowContext(ctx, idExistsQuery, id) + + err := row.Scan(&exists) + + return exists, err +} + +func (r *Repository) readEnvironmentRow(ctx context.Context, row scanner) (Environment, error) { + environment := Environment{} + + var ( + jsonValues []byte + ) + err := row.Scan( + &environment.ID, + &environment.Name, + &environment.Description, + &environment.CreatedAt, + &jsonValues, + ) + + switch err { + case sql.ErrNoRows: + return Environment{}, err + case nil: + err = json.Unmarshal(jsonValues, &environment.Values) + if err != nil { + return Environment{}, fmt.Errorf("cannot parse environment: %w", err) + } + + return environment, nil + default: + return Environment{}, err + } +} + +func (r *Repository) countEnvironments(ctx context.Context, query string) (int, error) { + var ( + count int + params []any + ) + + sql := countQuery + query + + err := r.db. + QueryRowContext(ctx, sql, params...). + Scan(&count) + + if err != nil { + return 0, err + } + return count, nil +} + +func (r *Repository) insertIntoEnvironments(ctx context.Context, environment Environment) (Environment, error) { + stmt, err := r.db.Prepare(insertQuery) + if err != nil { + return Environment{}, fmt.Errorf("sql prepare: %w", err) + } + defer stmt.Close() + + jsonValues, err := json.Marshal(environment.Values) + if err != nil { + return Environment{}, fmt.Errorf("encoding error: %w", err) + } + + _, err = stmt.ExecContext( + ctx, + environment.ID, + environment.Name, + environment.Description, + environment.CreatedAt, + jsonValues, + ) + + if err != nil { + return Environment{}, fmt.Errorf("sql exec: %w", err) + } + + return environment, nil +} + +func (r *Repository) updateIntoEnvironments(ctx context.Context, environment Environment, oldId id.ID) (Environment, error) { + stmt, err := r.db.Prepare(updateQuery) + if err != nil { + return Environment{}, fmt.Errorf("sql prepare: %w", err) + } + defer stmt.Close() + + jsonValues, err := json.Marshal(environment.Values) + if err != nil { + return Environment{}, fmt.Errorf("encoding error: %w", err) + } + + _, err = stmt.ExecContext( + ctx, + oldId, + environment.Slug(), + environment.Name, + environment.Description, + environment.CreatedAt, + jsonValues, + ) + + if err != nil { + return Environment{}, fmt.Errorf("sql exec: %w", err) + } + + return environment, nil +} + +func (r *Repository) Provision(ctx context.Context, environment Environment) error { + _, err := r.Create(ctx, environment) + return err +} diff --git a/server/environment/manager_test.go b/server/environment/manager_test.go new file mode 100644 index 0000000000..ae0b16cbb8 --- /dev/null +++ b/server/environment/manager_test.go @@ -0,0 +1,114 @@ +package environment_test + +import ( + "context" + "database/sql" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/kubeshop/tracetest/server/environment" + "github.com/kubeshop/tracetest/server/pkg/id" + "github.com/kubeshop/tracetest/server/resourcemanager" + rmtests "github.com/kubeshop/tracetest/server/resourcemanager/testutil" + "github.com/stretchr/testify/require" +) + +func TestEnvironment(t *testing.T) { + sampleEnvironment := environment.Environment{ + ID: "dev", + Name: "dev", + Description: "dev variables", + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + Values: []environment.EnvironmentValue{ + {Key: "URL", Value: "http://dev-app.com"}, + }, + } + + secondEnvironment := environment.Environment{ + ID: "new-dev", + Name: "new dev", + Description: "new dev variables", + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + Values: []environment.EnvironmentValue{ + {Key: "URL", Value: "http://dev-app.com"}, + {Key: "AUTH", Value: "user:pass"}, + }, + } + + thirdEnvironment := environment.Environment{ + ID: "stg", + Name: "staging", + Description: "staging variables", + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + Values: []environment.EnvironmentValue{ + {Key: "URL", Value: "http://stg-app.com"}, + {Key: "AUTH", Value: "user:pass"}, + }, + } + + resourceTypeTest := rmtests.ResourceTypeTest{ + ResourceTypeSingular: environment.ResourceName, + ResourceTypePlural: environment.ResourceNamePlural, + RegisterManagerFn: func(router *mux.Router, db *sql.DB) resourcemanager.Manager { + environmentRepository := environment.NewRepository(db) + + manager := resourcemanager.New[environment.Environment]( + environment.ResourceName, + environment.ResourceNamePlural, + &environmentRepository, + resourcemanager.WithIDGen(id.GenerateID), + resourcemanager.WithOperations(environment.Operations...), + ) + manager.RegisterRoutes(router) + + return manager + }, + Prepare: func(t *testing.T, op rmtests.Operation, manager resourcemanager.Manager) { + environmentRepository := manager.Handler().(*environment.Repository) + switch op { + case rmtests.OperationGetSuccess, + rmtests.OperationUpdateSuccess, + rmtests.OperationDeleteSuccess, + rmtests.OperationListSuccess: + environmentRepository.Create(context.TODO(), sampleEnvironment) + case rmtests.OperationListPaginatedSuccess: + environmentRepository.Create(context.TODO(), sampleEnvironment) + environmentRepository.Create(context.TODO(), secondEnvironment) + environmentRepository.Create(context.TODO(), thirdEnvironment) + } + }, + SampleJSON: `{ + "type": "Environment", + "spec": { + "id": "dev", + "name": "dev", + "description": "dev variables", + "values": [ + { "key": "URL", "value": "http://dev-app.com" } + ] + } + }`, + SampleJSONUpdated: `{ + "type": "Environment", + "spec": { + "id": "dev", + "name": "new-dev", + "description": "new dev variables", + "values": [ + { "key": "URL", "value": "http://dev-app.com" }, + { "key": "AUTH", "value": "user:password" } + ] + } + }`, + } + + rmtests.TestResourceType(t, resourceTypeTest, rmtests.JSONComparer(environmentJSONComparer)) +} + +func environmentJSONComparer(t require.TestingT, operation rmtests.Operation, firstValue, secondValue string) { + expected := rmtests.RemoveFieldFromJSONResource("createdAt", firstValue) + obtained := rmtests.RemoveFieldFromJSONResource("createdAt", secondValue) + + require.JSONEq(t, expected, obtained) +} diff --git a/server/environment/model.go b/server/environment/model.go new file mode 100644 index 0000000000..498a349fb8 --- /dev/null +++ b/server/environment/model.go @@ -0,0 +1,65 @@ +package environment + +import ( + "strings" + + "github.com/kubeshop/tracetest/server/pkg/id" +) + +type ( + Environment struct { + ID id.ID `mapstructure:"id"` + Name string `mapstructure:"name"` + Description string `mapstructure:"description"` + CreatedAt string `mapstructure:"createdAt"` + Values []EnvironmentValue `mapstructure:"values"` + } + + EnvironmentValue struct { + Key string `mapstructure:"key"` + Value string `mapstructure:"value"` + } +) + +func (e Environment) Validate() error { + return nil +} + +func (e Environment) HasID() bool { + return e.ID != "" +} + +func (e Environment) Slug() id.ID { + return id.ID(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(e.Name), " ", "-"))) +} + +func (e Environment) Get(key string) string { + for _, v := range e.Values { + if v.Key == key { + return v.Value + } + } + return "" +} + +func (e Environment) Merge(env Environment) Environment { + values := make(map[string]string) + for _, variable := range e.Values { + values[variable.Key] = variable.Value + } + + for _, variable := range env.Values { + values[variable.Key] = variable.Value + } + + newValues := make([]EnvironmentValue, 0, len(values)) + for key, value := range values { + newValues = append(newValues, EnvironmentValue{ + Key: key, + Value: value, + }) + } + + e.Values = newValues + return e +} diff --git a/server/environment/resource.go b/server/environment/resource.go new file mode 100644 index 0000000000..443c1557cc --- /dev/null +++ b/server/environment/resource.go @@ -0,0 +1,16 @@ +package environment + +import "github.com/kubeshop/tracetest/server/resourcemanager" + +const ( + ResourceName = "Environment" + ResourceNamePlural = "Environments" +) + +var Operations = []resourcemanager.Operation{ + resourcemanager.OperationCreate, + resourcemanager.OperationDelete, + resourcemanager.OperationGet, + resourcemanager.OperationList, + resourcemanager.OperationUpdate, +} diff --git a/server/go.mod b/server/go.mod index 7d20378e1c..e93503e7fa 100644 --- a/server/go.mod +++ b/server/go.mod @@ -20,6 +20,7 @@ require ( github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.5.0 + github.com/goware/urlx v0.3.2 github.com/hashicorp/go-multierror v1.1.1 github.com/j2gg0s/otsql v0.14.0 github.com/jhump/protoreflect v1.12.0 @@ -76,7 +77,6 @@ require ( github.com/go-redis/redis/v7 v7.4.1 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/go-cmp v0.5.9 // indirect - github.com/goware/urlx v0.3.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect diff --git a/server/http/controller.go b/server/http/controller.go index 241608850f..5658a88a59 100644 --- a/server/http/controller.go +++ b/server/http/controller.go @@ -630,77 +630,6 @@ func (c *controller) CreateEnvironment(ctx context.Context, in openapi.Environme return openapi.Response(200, c.mappers.Out.Environment(environment)), nil } -func (c *controller) DeleteEnvironment(ctx context.Context, environmentId string) (openapi.ImplResponse, error) { - environment, err := c.testDB.GetEnvironment(ctx, environmentId) - if err != nil { - return handleDBError(err), err - } - - err = c.testDB.DeleteEnvironment(ctx, environment) - if err != nil { - return handleDBError(err), err - } - - return openapi.Response(http.StatusNoContent, nil), nil -} - -func (c *controller) GetEnvironment(ctx context.Context, environmentId string) (openapi.ImplResponse, error) { - environment, err := c.testDB.GetEnvironment(ctx, environmentId) - if err != nil { - return handleDBError(err), err - } - - return openapi.Response(200, c.mappers.Out.Environment(environment)), nil -} - -func (c *controller) GetEnvironments(ctx context.Context, take, skip int32, query string, sortBy string, sortDirection string) (openapi.ImplResponse, error) { - if take == 0 { - take = 20 - } - - environments, err := c.testDB.GetEnvironments(ctx, take, skip, query, sortBy, sortDirection) - if err != nil { - return handleDBError(err), err - } - - return openapi.Response(200, paginated[openapi.Environment]{ - items: c.mappers.Out.Environments(environments.Items), - count: environments.TotalCount, - }), nil -} - -func (c *controller) GetEnvironmentDefinitionFile(ctx context.Context, environmentId string) (openapi.ImplResponse, error) { - environment, err := c.testDB.GetEnvironment(ctx, environmentId) - if err != nil { - return handleDBError(err), err - } - - enc, err := yaml.Encode(yamlconvert.Environment(environment)) - if err != nil { - return openapi.Response(http.StatusUnprocessableEntity, err.Error()), err - } - - return openapi.Response(200, enc), nil -} - -func (c *controller) UpdateEnvironment(ctx context.Context, environmentId string, in openapi.Environment) (openapi.ImplResponse, error) { - updated := c.mappers.In.Environment(in) - - environment, err := c.testDB.GetEnvironment(ctx, environmentId) - if err != nil { - return handleDBError(err), err - } - - updated.ID = environment.ID - - _, err = c.testDB.UpdateEnvironment(ctx, updated) - if err != nil { - return handleDBError(err), err - } - - return openapi.Response(204, nil), nil -} - // expressions func (c *controller) ExpressionResolve(ctx context.Context, in openapi.ResolveRequestInfo) (openapi.ImplResponse, error) { dsList, err := c.buildDataStores(ctx, in) diff --git a/server/http/custom_routes.go b/server/http/custom_routes.go index 18eb0763b7..b8993061f3 100644 --- a/server/http/custom_routes.go +++ b/server/http/custom_routes.go @@ -37,12 +37,10 @@ func (c *customController) Routes() openapi.Routes { routes[c.getRouteIndex("GetRunResultJUnit")].HandlerFunc = c.GetRunResultJUnit routes[c.getRouteIndex("GetTestVersionDefinitionFile")].HandlerFunc = c.GetTestVersionDefinitionFile routes[c.getRouteIndex("GetTransactionVersionDefinitionFile")].HandlerFunc = c.GetTransactionVersionDefinitionFile - routes[c.getRouteIndex("GetEnvironmentDefinitionFile")].HandlerFunc = c.GetEnvironmentDefinitionFile routes[c.getRouteIndex("GetTestRuns")].HandlerFunc = c.GetTestRuns routes[c.getRouteIndex("GetTests")].HandlerFunc = paginatedEndpoint[openapi.Test](c.service.GetTests, c.errorHandler) - routes[c.getRouteIndex("GetEnvironments")].HandlerFunc = paginatedEndpoint[openapi.Environment](c.service.GetEnvironments, c.errorHandler) routes[c.getRouteIndex("GetTransactions")].HandlerFunc = paginatedEndpoint[openapi.Transaction](c.service.GetTransactions, c.errorHandler) routes[c.getRouteIndex("GetResources")].HandlerFunc = paginatedEndpoint[openapi.Resource](c.service.GetResources, c.errorHandler) @@ -151,21 +149,6 @@ func (c *customController) GetTransactionVersionDefinitionFile(w http.ResponseWr w.Write(result.Body.([]byte)) } -// GetTransactionVersionDefinitionFile - Get the test definition as an YAML file -func (c *customController) GetEnvironmentDefinitionFile(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - result, err := c.service.GetEnvironmentDefinitionFile(r.Context(), environmentIdParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - w.Header().Set("Content-Type", "application/yaml; charset=UTF-8") - w.Write(result.Body.([]byte)) -} - func paginatedEndpoint[T any]( f func(c context.Context, take, skip int32, query string, sortBy string, sortDirection string) (openapi.ImplResponse, error), errorHandler openapi.ErrorHandler, diff --git a/server/openapi/api.go b/server/openapi/api.go index 6cd2ac588b..4b78c4247d 100644 --- a/server/openapi/api.go +++ b/server/openapi/api.go @@ -18,10 +18,8 @@ import ( // The ApiApiRouter implementation should parse necessary information from the http request, // pass the data to a ApiApiServicer to perform the required actions, then write the service results to the http response. type ApiApiRouter interface { - CreateEnvironment(http.ResponseWriter, *http.Request) CreateTest(http.ResponseWriter, *http.Request) CreateTransaction(http.ResponseWriter, *http.Request) - DeleteEnvironment(http.ResponseWriter, *http.Request) DeleteTest(http.ResponseWriter, *http.Request) DeleteTestRun(http.ResponseWriter, *http.Request) DeleteTransaction(http.ResponseWriter, *http.Request) @@ -30,9 +28,6 @@ type ApiApiRouter interface { ExecuteDefinition(http.ResponseWriter, *http.Request) ExportTestRun(http.ResponseWriter, *http.Request) ExpressionResolve(http.ResponseWriter, *http.Request) - GetEnvironment(http.ResponseWriter, *http.Request) - GetEnvironmentDefinitionFile(http.ResponseWriter, *http.Request) - GetEnvironments(http.ResponseWriter, *http.Request) GetResources(http.ResponseWriter, *http.Request) GetRunResultJUnit(http.ResponseWriter, *http.Request) GetTest(http.ResponseWriter, *http.Request) @@ -56,7 +51,6 @@ type ApiApiRouter interface { RunTransaction(http.ResponseWriter, *http.Request) StopTestRun(http.ResponseWriter, *http.Request) TestConnection(http.ResponseWriter, *http.Request) - UpdateEnvironment(http.ResponseWriter, *http.Request) UpdateTest(http.ResponseWriter, *http.Request) UpdateTransaction(http.ResponseWriter, *http.Request) UpsertDefinition(http.ResponseWriter, *http.Request) @@ -67,16 +61,21 @@ type ApiApiRouter interface { // pass the data to a ResourceApiApiServicer to perform the required actions, then write the service results to the http response. type ResourceApiApiRouter interface { CreateDemo(http.ResponseWriter, *http.Request) + CreateEnvironment(http.ResponseWriter, *http.Request) DeleteDataStore(http.ResponseWriter, *http.Request) DeleteDemo(http.ResponseWriter, *http.Request) + DeleteEnvironment(http.ResponseWriter, *http.Request) GetConfiguration(http.ResponseWriter, *http.Request) GetDataStore(http.ResponseWriter, *http.Request) GetDemo(http.ResponseWriter, *http.Request) + GetEnvironment(http.ResponseWriter, *http.Request) GetPollingProfile(http.ResponseWriter, *http.Request) ListDemos(http.ResponseWriter, *http.Request) + ListEnvironments(http.ResponseWriter, *http.Request) UpdateConfiguration(http.ResponseWriter, *http.Request) UpdateDataStore(http.ResponseWriter, *http.Request) UpdateDemo(http.ResponseWriter, *http.Request) + UpdateEnvironment(http.ResponseWriter, *http.Request) UpdatePollingProfile(http.ResponseWriter, *http.Request) } @@ -85,10 +84,8 @@ type ResourceApiApiRouter interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type ApiApiServicer interface { - CreateEnvironment(context.Context, Environment) (ImplResponse, error) CreateTest(context.Context, Test) (ImplResponse, error) CreateTransaction(context.Context, Transaction) (ImplResponse, error) - DeleteEnvironment(context.Context, string) (ImplResponse, error) DeleteTest(context.Context, string) (ImplResponse, error) DeleteTestRun(context.Context, string, int32) (ImplResponse, error) DeleteTransaction(context.Context, string) (ImplResponse, error) @@ -97,9 +94,6 @@ type ApiApiServicer interface { ExecuteDefinition(context.Context, TextDefinition) (ImplResponse, error) ExportTestRun(context.Context, string, int32) (ImplResponse, error) ExpressionResolve(context.Context, ResolveRequestInfo) (ImplResponse, error) - GetEnvironment(context.Context, string) (ImplResponse, error) - GetEnvironmentDefinitionFile(context.Context, string) (ImplResponse, error) - GetEnvironments(context.Context, int32, int32, string, string, string) (ImplResponse, error) GetResources(context.Context, int32, int32, string, string, string) (ImplResponse, error) GetRunResultJUnit(context.Context, string, int32) (ImplResponse, error) GetTest(context.Context, string) (ImplResponse, error) @@ -123,7 +117,6 @@ type ApiApiServicer interface { RunTransaction(context.Context, string, RunInformation) (ImplResponse, error) StopTestRun(context.Context, string, int32) (ImplResponse, error) TestConnection(context.Context, DataStore) (ImplResponse, error) - UpdateEnvironment(context.Context, string, Environment) (ImplResponse, error) UpdateTest(context.Context, string, Test) (ImplResponse, error) UpdateTransaction(context.Context, string, Transaction) (ImplResponse, error) UpsertDefinition(context.Context, TextDefinition) (ImplResponse, error) @@ -135,15 +128,20 @@ type ApiApiServicer interface { // and updated with the logic required for the API. type ResourceApiApiServicer interface { CreateDemo(context.Context, Demo) (ImplResponse, error) + CreateEnvironment(context.Context, EnvironmentResource) (ImplResponse, error) DeleteDataStore(context.Context, string) (ImplResponse, error) DeleteDemo(context.Context, string) (ImplResponse, error) + DeleteEnvironment(context.Context, string) (ImplResponse, error) GetConfiguration(context.Context, string) (ImplResponse, error) GetDataStore(context.Context, string) (ImplResponse, error) GetDemo(context.Context, string) (ImplResponse, error) + GetEnvironment(context.Context, string) (ImplResponse, error) GetPollingProfile(context.Context, string) (ImplResponse, error) ListDemos(context.Context, int32, int32, string, string) (ImplResponse, error) + ListEnvironments(context.Context, int32, int32, string, string) (ImplResponse, error) UpdateConfiguration(context.Context, string, ConfigurationResource) (ImplResponse, error) UpdateDataStore(context.Context, string, DataStore) (ImplResponse, error) UpdateDemo(context.Context, string, Demo) (ImplResponse, error) + UpdateEnvironment(context.Context, string, EnvironmentResource) (ImplResponse, error) UpdatePollingProfile(context.Context, string, PollingProfile) (ImplResponse, error) } diff --git a/server/openapi/api_api.go b/server/openapi/api_api.go index dff14a1553..04ca388da5 100644 --- a/server/openapi/api_api.go +++ b/server/openapi/api_api.go @@ -50,12 +50,6 @@ func NewApiApiController(s ApiApiServicer, opts ...ApiApiOption) Router { // Routes returns all the api routes for the ApiApiController func (c *ApiApiController) Routes() Routes { return Routes{ - { - "CreateEnvironment", - strings.ToUpper("Post"), - "/api/environments", - c.CreateEnvironment, - }, { "CreateTest", strings.ToUpper("Post"), @@ -68,12 +62,6 @@ func (c *ApiApiController) Routes() Routes { "/api/transactions", c.CreateTransaction, }, - { - "DeleteEnvironment", - strings.ToUpper("Delete"), - "/api/environments/{environmentId}", - c.DeleteEnvironment, - }, { "DeleteTest", strings.ToUpper("Delete"), @@ -122,24 +110,6 @@ func (c *ApiApiController) Routes() Routes { "/api/expressions/resolve", c.ExpressionResolve, }, - { - "GetEnvironment", - strings.ToUpper("Get"), - "/api/environments/{environmentId}", - c.GetEnvironment, - }, - { - "GetEnvironmentDefinitionFile", - strings.ToUpper("Get"), - "/api/environments/{environmentId}/definition.yaml", - c.GetEnvironmentDefinitionFile, - }, - { - "GetEnvironments", - strings.ToUpper("Get"), - "/api/environments", - c.GetEnvironments, - }, { "GetResources", strings.ToUpper("Get"), @@ -278,12 +248,6 @@ func (c *ApiApiController) Routes() Routes { "/api/config/connection", c.TestConnection, }, - { - "UpdateEnvironment", - strings.ToUpper("Put"), - "/api/environments/{environmentId}", - c.UpdateEnvironment, - }, { "UpdateTest", strings.ToUpper("Put"), @@ -305,30 +269,6 @@ func (c *ApiApiController) Routes() Routes { } } -// CreateEnvironment - Create new environment -func (c *ApiApiController) CreateEnvironment(w http.ResponseWriter, r *http.Request) { - environmentParam := Environment{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&environmentParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertEnvironmentRequired(environmentParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - result, err := c.service.CreateEnvironment(r.Context(), environmentParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // CreateTest - Create new test func (c *ApiApiController) CreateTest(w http.ResponseWriter, r *http.Request) { testParam := Test{} @@ -377,22 +317,6 @@ func (c *ApiApiController) CreateTransaction(w http.ResponseWriter, r *http.Requ } -// DeleteEnvironment - delete a environment -func (c *ApiApiController) DeleteEnvironment(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - result, err := c.service.DeleteEnvironment(r.Context(), environmentIdParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // DeleteTest - delete a test func (c *ApiApiController) DeleteTest(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -572,65 +496,6 @@ func (c *ApiApiController) ExpressionResolve(w http.ResponseWriter, r *http.Requ } -// GetEnvironment - get environment -func (c *ApiApiController) GetEnvironment(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - result, err := c.service.GetEnvironment(r.Context(), environmentIdParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - -// GetEnvironmentDefinitionFile - Get the environment definition as an YAML file -func (c *ApiApiController) GetEnvironmentDefinitionFile(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - result, err := c.service.GetEnvironmentDefinitionFile(r.Context(), environmentIdParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - -// GetEnvironments - Get Environments -func (c *ApiApiController) GetEnvironments(w http.ResponseWriter, r *http.Request) { - query := r.URL.Query() - takeParam, err := parseInt32Parameter(query.Get("take"), false) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - skipParam, err := parseInt32Parameter(query.Get("skip"), false) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - queryParam := query.Get("query") - sortByParam := query.Get("sortBy") - sortDirectionParam := query.Get("sortDirection") - result, err := c.service.GetEnvironments(r.Context(), takeParam, skipParam, queryParam, sortByParam, sortDirectionParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // GetResources - Get resources func (c *ApiApiController) GetResources(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() @@ -1160,33 +1025,6 @@ func (c *ApiApiController) TestConnection(w http.ResponseWriter, r *http.Request } -// UpdateEnvironment - update environment -func (c *ApiApiController) UpdateEnvironment(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - environmentParam := Environment{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&environmentParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertEnvironmentRequired(environmentParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - result, err := c.service.UpdateEnvironment(r.Context(), environmentIdParam, environmentParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // UpdateTest - update test func (c *ApiApiController) UpdateTest(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) diff --git a/server/openapi/api_resource_api.go b/server/openapi/api_resource_api.go index b78db1cb53..4f8d109627 100644 --- a/server/openapi/api_resource_api.go +++ b/server/openapi/api_resource_api.go @@ -56,6 +56,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos", c.CreateDemo, }, + { + "CreateEnvironment", + strings.ToUpper("Post"), + "/api/environments", + c.CreateEnvironment, + }, { "DeleteDataStore", strings.ToUpper("Delete"), @@ -68,6 +74,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.DeleteDemo, }, + { + "DeleteEnvironment", + strings.ToUpper("Delete"), + "/api/environments/{environmentId}", + c.DeleteEnvironment, + }, { "GetConfiguration", strings.ToUpper("Get"), @@ -86,6 +98,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.GetDemo, }, + { + "GetEnvironment", + strings.ToUpper("Get"), + "/api/environments/{environmentId}", + c.GetEnvironment, + }, { "GetPollingProfile", strings.ToUpper("Get"), @@ -98,6 +116,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos", c.ListDemos, }, + { + "ListEnvironments", + strings.ToUpper("Get"), + "/api/environments", + c.ListEnvironments, + }, { "UpdateConfiguration", strings.ToUpper("Put"), @@ -116,6 +140,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.UpdateDemo, }, + { + "UpdateEnvironment", + strings.ToUpper("Put"), + "/api/environments/{environmentId}", + c.UpdateEnvironment, + }, { "UpdatePollingProfile", strings.ToUpper("Put"), @@ -149,6 +179,30 @@ func (c *ResourceApiApiController) CreateDemo(w http.ResponseWriter, r *http.Req } +// CreateEnvironment - Create an environment +func (c *ResourceApiApiController) CreateEnvironment(w http.ResponseWriter, r *http.Request) { + environmentResourceParam := EnvironmentResource{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&environmentResourceParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertEnvironmentResourceRequired(environmentResourceParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.CreateEnvironment(r.Context(), environmentResourceParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // DeleteDataStore - Delete a Data Store func (c *ResourceApiApiController) DeleteDataStore(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -181,6 +235,22 @@ func (c *ResourceApiApiController) DeleteDemo(w http.ResponseWriter, r *http.Req } +// DeleteEnvironment - Delete an environment +func (c *ResourceApiApiController) DeleteEnvironment(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + environmentIdParam := params["environmentId"] + + result, err := c.service.DeleteEnvironment(r.Context(), environmentIdParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // GetConfiguration - Get Tracetest configuration func (c *ResourceApiApiController) GetConfiguration(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -229,6 +299,22 @@ func (c *ResourceApiApiController) GetDemo(w http.ResponseWriter, r *http.Reques } +// GetEnvironment - Get a specific environment +func (c *ResourceApiApiController) GetEnvironment(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + environmentIdParam := params["environmentId"] + + result, err := c.service.GetEnvironment(r.Context(), environmentIdParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // GetPollingProfile - Get Polling Profile func (c *ResourceApiApiController) GetPollingProfile(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -271,6 +357,32 @@ func (c *ResourceApiApiController) ListDemos(w http.ResponseWriter, r *http.Requ } +// ListEnvironments - List environments +func (c *ResourceApiApiController) ListEnvironments(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + takeParam, err := parseInt32Parameter(query.Get("take"), false) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + skipParam, err := parseInt32Parameter(query.Get("skip"), false) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + sortByParam := query.Get("sortBy") + sortDirectionParam := query.Get("sortDirection") + result, err := c.service.ListEnvironments(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // UpdateConfiguration - Update Tracetest configuration func (c *ResourceApiApiController) UpdateConfiguration(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -352,6 +464,33 @@ func (c *ResourceApiApiController) UpdateDemo(w http.ResponseWriter, r *http.Req } +// UpdateEnvironment - Update an environment +func (c *ResourceApiApiController) UpdateEnvironment(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + environmentIdParam := params["environmentId"] + + environmentResourceParam := EnvironmentResource{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&environmentResourceParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertEnvironmentResourceRequired(environmentResourceParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.UpdateEnvironment(r.Context(), environmentIdParam, environmentResourceParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // UpdatePollingProfile - Update a Polling Profile func (c *ResourceApiApiController) UpdatePollingProfile(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) diff --git a/server/openapi/api_resource_api_service.go b/server/openapi/api_resource_api_service.go index 4393821ab2..1cb15e86be 100644 --- a/server/openapi/api_resource_api_service.go +++ b/server/openapi/api_resource_api_service.go @@ -40,6 +40,20 @@ func (s *ResourceApiApiService) CreateDemo(ctx context.Context, demo Demo) (Impl return Response(http.StatusNotImplemented, nil), errors.New("CreateDemo method not implemented") } +// CreateEnvironment - Create an environment +func (s *ResourceApiApiService) CreateEnvironment(ctx context.Context, environmentResource EnvironmentResource) (ImplResponse, error) { + // TODO - update CreateEnvironment with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(201, EnvironmentResource{}) or use other options such as http.Ok ... + //return Response(201, EnvironmentResource{}), nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("CreateEnvironment method not implemented") +} + // DeleteDataStore - Delete a Data Store func (s *ResourceApiApiService) DeleteDataStore(ctx context.Context, dataStoreId string) (ImplResponse, error) { // TODO - update DeleteDataStore with the required logic for this service method. @@ -48,9 +62,6 @@ func (s *ResourceApiApiService) DeleteDataStore(ctx context.Context, dataStoreId //TODO: Uncomment the next line to return response Response(204, {}) or use other options such as http.Ok ... //return Response(204, nil),nil - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("DeleteDataStore method not implemented") } @@ -74,6 +85,26 @@ func (s *ResourceApiApiService) DeleteDemo(ctx context.Context, demoId string) ( return Response(http.StatusNotImplemented, nil), errors.New("DeleteDemo method not implemented") } +// DeleteEnvironment - Delete an environment +func (s *ResourceApiApiService) DeleteEnvironment(ctx context.Context, environmentId string) (ImplResponse, error) { + // TODO - update DeleteEnvironment with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(204, {}) or use other options such as http.Ok ... + //return Response(204, nil),nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeleteEnvironment method not implemented") +} + // GetConfiguration - Get Tracetest configuration func (s *ResourceApiApiService) GetConfiguration(ctx context.Context, configId string) (ImplResponse, error) { // TODO - update GetConfiguration with the required logic for this service method. @@ -122,6 +153,23 @@ func (s *ResourceApiApiService) GetDemo(ctx context.Context, demoId string) (Imp return Response(http.StatusNotImplemented, nil), errors.New("GetDemo method not implemented") } +// GetEnvironment - Get a specific environment +func (s *ResourceApiApiService) GetEnvironment(ctx context.Context, environmentId string) (ImplResponse, error) { + // TODO - update GetEnvironment with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, EnvironmentResource{}) or use other options such as http.Ok ... + //return Response(200, EnvironmentResource{}), nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetEnvironment method not implemented") +} + // GetPollingProfile - Get Polling Profile func (s *ResourceApiApiService) GetPollingProfile(ctx context.Context, pollingProfileId string) (ImplResponse, error) { // TODO - update GetPollingProfile with the required logic for this service method. @@ -156,6 +204,23 @@ func (s *ResourceApiApiService) ListDemos(ctx context.Context, take int32, skip return Response(http.StatusNotImplemented, nil), errors.New("ListDemos method not implemented") } +// ListEnvironments - List environments +func (s *ResourceApiApiService) ListEnvironments(ctx context.Context, take int32, skip int32, sortBy string, sortDirection string) (ImplResponse, error) { + // TODO - update ListEnvironments with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, ListEnvironments200Response{}) or use other options such as http.Ok ... + //return Response(200, ListEnvironments200Response{}), nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("ListEnvironments method not implemented") +} + // UpdateConfiguration - Update Tracetest configuration func (s *ResourceApiApiService) UpdateConfiguration(ctx context.Context, configId string, configurationResource ConfigurationResource) (ImplResponse, error) { // TODO - update UpdateConfiguration with the required logic for this service method. @@ -207,6 +272,26 @@ func (s *ResourceApiApiService) UpdateDemo(ctx context.Context, demoId string, d return Response(http.StatusNotImplemented, nil), errors.New("UpdateDemo method not implemented") } +// UpdateEnvironment - Update an environment +func (s *ResourceApiApiService) UpdateEnvironment(ctx context.Context, environmentId string, environmentResource EnvironmentResource) (ImplResponse, error) { + // TODO - update UpdateEnvironment with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, EnvironmentResource{}) or use other options such as http.Ok ... + //return Response(200, EnvironmentResource{}), nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdateEnvironment method not implemented") +} + // UpdatePollingProfile - Update a Polling Profile func (s *ResourceApiApiService) UpdatePollingProfile(ctx context.Context, pollingProfileId string, pollingProfile PollingProfile) (ImplResponse, error) { // TODO - update UpdatePollingProfile with the required logic for this service method. diff --git a/server/openapi/model_environment_resource.go b/server/openapi/model_environment_resource.go new file mode 100644 index 0000000000..e2f9cf5a41 --- /dev/null +++ b/server/openapi/model_environment_resource.go @@ -0,0 +1,39 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +// EnvironmentResource - Represents an environment structured into the Resources format. +type EnvironmentResource struct { + + // Represents the type of this resource. It should always be set as 'Environment'. + Type string `json:"type,omitempty"` + + Spec Environment `json:"spec,omitempty"` +} + +// AssertEnvironmentResourceRequired checks if the required fields are not zero-ed +func AssertEnvironmentResourceRequired(obj EnvironmentResource) error { + if err := AssertEnvironmentRequired(obj.Spec); err != nil { + return err + } + return nil +} + +// AssertRecurseEnvironmentResourceRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of EnvironmentResource (e.g. [][]EnvironmentResource), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseEnvironmentResourceRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aEnvironmentResource, ok := obj.(EnvironmentResource) + if !ok { + return ErrTypeAssertionError + } + return AssertEnvironmentResourceRequired(aEnvironmentResource) + }) +} diff --git a/server/openapi/model_list_environments_200_response.go b/server/openapi/model_list_environments_200_response.go new file mode 100644 index 0000000000..25ca20377f --- /dev/null +++ b/server/openapi/model_list_environments_200_response.go @@ -0,0 +1,38 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +type ListEnvironments200Response struct { + Count int32 `json:"count,omitempty"` + + Items []EnvironmentResource `json:"items,omitempty"` +} + +// AssertListEnvironments200ResponseRequired checks if the required fields are not zero-ed +func AssertListEnvironments200ResponseRequired(obj ListEnvironments200Response) error { + for _, el := range obj.Items { + if err := AssertEnvironmentResourceRequired(el); err != nil { + return err + } + } + return nil +} + +// AssertRecurseListEnvironments200ResponseRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of ListEnvironments200Response (e.g. [][]ListEnvironments200Response), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseListEnvironments200ResponseRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aListEnvironments200Response, ok := obj.(ListEnvironments200Response) + if !ok { + return ErrTypeAssertionError + } + return AssertListEnvironments200ResponseRequired(aListEnvironments200Response) + }) +} diff --git a/server/resourcemanager/provisioner.go b/server/resourcemanager/provisioner.go index 10079d2344..9e682914af 100644 --- a/server/resourcemanager/provisioner.go +++ b/server/resourcemanager/provisioner.go @@ -4,8 +4,6 @@ import ( "context" "errors" "fmt" - - "github.com/mitchellh/mapstructure" ) var ErrTypeNotSupported = errors.New("type not supported") @@ -20,7 +18,7 @@ func (m *manager[T]) Provision(ctx context.Context, values map[string]any) error } targetResource := Resource[T]{} - err := mapstructure.Decode(values, &targetResource) + err := decode(values, &targetResource) if err != nil { return fmt.Errorf( "cannot read provisioning for resource type %s: %w", diff --git a/server/resourcemanager/resource_manager.go b/server/resourcemanager/resource_manager.go index c80722a47a..628839352a 100644 --- a/server/resourcemanager/resource_manager.go +++ b/server/resourcemanager/resource_manager.go @@ -3,13 +3,20 @@ package resourcemanager import ( "context" "database/sql" + "encoding/json" "errors" "fmt" "io" "net/http" + "reflect" "strconv" "strings" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/propagation" + semconv "go.opentelemetry.io/otel/semconv/v1.4.0" + "go.opentelemetry.io/otel/trace" "golang.org/x/exp/slices" "github.com/gorilla/mux" @@ -50,6 +57,7 @@ type manager[T ResourceSpec] struct { type config struct { enabledOperations []Operation idgen func() id.ID + tracer trace.Tracer } type managerOption func(*config) @@ -66,6 +74,12 @@ func WithOperations(ops ...Operation) managerOption { } } +func WithTracer(tracer trace.Tracer) managerOption { + return func(c *config) { + c.tracer = tracer + } +} + func New[T ResourceSpec](resourceTypeSingular, resourceTypePlural string, handler any, opts ...managerOption) Manager { rh := &resourceHandler[T]{} @@ -113,28 +127,78 @@ func (m *manager[T]) RegisterRoutes(r *mux.Router) *mux.Router { enabledOps := m.EnabledOperations() if slices.Contains(enabledOps, OperationList) { - subrouter.HandleFunc("", m.list).Methods(http.MethodGet).Name("list") + m.instrumentRoute(subrouter.HandleFunc("", m.list).Methods(http.MethodGet).Name("list")) } if slices.Contains(enabledOps, OperationCreate) { - subrouter.HandleFunc("", m.create).Methods(http.MethodPost).Name(fmt.Sprintf("%s.Create", m.resourceTypePlural)) + m.instrumentRoute(subrouter.HandleFunc("", m.create).Methods(http.MethodPost).Name(fmt.Sprintf("%s.Create", m.resourceTypePlural))) } if slices.Contains(enabledOps, OperationUpdate) { - subrouter.HandleFunc("/{id}", m.update).Methods(http.MethodPut).Name(fmt.Sprintf("%s.Update", m.resourceTypePlural)) + m.instrumentRoute(subrouter.HandleFunc("/{id}", m.update).Methods(http.MethodPut).Name(fmt.Sprintf("%s.Update", m.resourceTypePlural))) } if slices.Contains(enabledOps, OperationGet) { - subrouter.HandleFunc("/{id}", m.get).Methods(http.MethodGet).Name(fmt.Sprintf("%s.Get", m.resourceTypePlural)) + m.instrumentRoute(subrouter.HandleFunc("/{id}", m.get).Methods(http.MethodGet).Name(fmt.Sprintf("%s.Get", m.resourceTypePlural))) } if slices.Contains(enabledOps, OperationDelete) { - subrouter.HandleFunc("/{id}", m.delete).Methods(http.MethodDelete).Name(fmt.Sprintf("%s.Delete", m.resourceTypePlural)) + m.instrumentRoute(subrouter.HandleFunc("/{id}", m.delete).Methods(http.MethodDelete).Name(fmt.Sprintf("%s.Delete", m.resourceTypePlural))) } return subrouter } +func (m *manager[T]) instrumentRoute(route *mux.Route) { + originalHandler := route.GetHandler() + pathTemplate, _ := route.GetPathTemplate() + + newHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if m.config.tracer == nil { + originalHandler.ServeHTTP(w, r) + return + } + + method := r.Method + + ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) + ctx, span := m.config.tracer.Start(ctx, fmt.Sprintf("%s %s", method, pathTemplate)) + defer span.End() + + params := make(map[string]interface{}, 0) + for key, value := range mux.Vars(r) { + params[key] = value + } + + paramsJson, _ := json.Marshal(params) + + queryString := make(map[string]interface{}, 0) + for key, value := range r.URL.Query() { + queryString[key] = value + } + queryStringJson, _ := json.Marshal(queryString) + + headers := make(map[string]interface{}, 0) + for key, value := range r.Header { + headers[key] = value + } + headersJson, _ := json.Marshal(headers) + + span.SetAttributes( + attribute.String(string(semconv.HTTPMethodKey), r.Method), + attribute.String(string(semconv.HTTPRouteKey), pathTemplate), + attribute.String(string(semconv.HTTPTargetKey), r.URL.String()), + attribute.String("http.request.params", string(paramsJson)), + attribute.String("http.request.query", string(queryStringJson)), + attribute.String("http.request.headers", string(headersJson)), + ) + + originalHandler.ServeHTTP(w, r.WithContext(ctx)) + }) + + route.Handler(newHandler) +} + func (m *manager[T]) create(w http.ResponseWriter, r *http.Request) { m.operationWithBody(w, r, http.StatusCreated, "creating", m.rh.Create) } @@ -234,7 +298,7 @@ func (m *manager[T]) list(w http.ResponseWriter, r *http.Request) { } var values map[string]any - err := mapstructure.Decode(resource, &values) + err := encode(resource, &values) if err != nil { writeError(w, encoder, http.StatusInternalServerError, fmt.Errorf("cannot marshal entity: %w", err)) return @@ -330,7 +394,7 @@ func (m *manager[T]) operationWithBody(w http.ResponseWriter, r *http.Request, s } targetResource := Resource[T]{} - err = mapstructure.Decode(values, &targetResource) + err = decode(values, &targetResource) if err != nil { writeError(w, encoder, http.StatusBadRequest, fmt.Errorf("cannot unmarshal body values: %w", err)) return @@ -383,12 +447,11 @@ func writeError(w http.ResponseWriter, enc encoder, code int, err error) { } func encodeValues(resource any, enc encoder) ([]byte, error) { - // mapstructure doesn't have a `Decode`, but encoding with reversed provides this func. - // See https://github.com/mitchellh/mapstructure/issues/53#issuecomment-273342420 var values map[string]any - err := mapstructure.Decode(resource, &values) + + err := encode(resource, &values) if err != nil { - return nil, fmt.Errorf("cannot encode values: %w", err) + return nil, fmt.Errorf("cannot encode resource: %w", err) } return enc.Marshal(values) @@ -420,3 +483,49 @@ func readBody(r *http.Request) ([]byte, error) { return body, nil } + +func decode(input any, output any) error { + return mapstructure.Decode(input, output) +} + +func encode(input any, output *map[string]any) error { + err := mapstructure.Decode(input, output) + if err != nil { + return err + } + + fixInternalSlicesMapping(output) + + return nil +} + +func fixInternalSlicesMapping(output *map[string]any) { + for k, v := range *output { + value := reflect.ValueOf(v) + if value.Kind() == reflect.Map { + if submap, ok := v.(map[string]any); ok { + fixInternalSlicesMapping(&submap) + } + } + + if value.Kind() == reflect.Slice { + if value.Len() == 0 { + continue + } + + firstItem := value.Index(0) + if firstItem.Kind() != reflect.Struct { + continue + } + + newOutput := make([]map[string]any, value.Len()) + + for i := 0; i < value.Len(); i++ { + mapstructure.Decode(value.Index(i).Interface(), &newOutput[i]) + } + + deferencedOutput := *output + deferencedOutput[k] = newOutput + } + } +} diff --git a/server/resourcemanager/testutil/operations_list.go b/server/resourcemanager/testutil/operations_list.go index f64b4de79c..3d9c889605 100644 --- a/server/resourcemanager/testutil/operations_list.go +++ b/server/resourcemanager/testutil/operations_list.go @@ -91,7 +91,7 @@ var listSuccessOperation = buildSingleStepOperation(singleStepOperationTester{ json.Unmarshal([]byte(jsonBody), &parsedJsonBody) require.Equal(t, 1, parsedJsonBody.Count) - require.Equal(t, len(parsedJsonBody.Items), 1) + require.Equal(t, 1, len(parsedJsonBody.Items)) obtainedAsBytes, err := json.Marshal(parsedJsonBody.Items[0]) require.NoError(t, err) diff --git a/tracetesting/features/environment/01_create_environment.yml b/tracetesting/features/environment/01_create_environment.yml index 6ce258c340..0a6fd40276 100644 --- a/tracetesting/features/environment/01_create_environment.yml +++ b/tracetesting/features/environment/01_create_environment.yml @@ -1,4 +1,3 @@ ---- type: Test spec: name: Create Environment @@ -13,6 +12,8 @@ spec: value: application/json body: | { + "type": "Environment", + "spec": { "name": "test-environment", "description": "test-environment", "values": [ @@ -25,17 +26,18 @@ spec: "value": "3000" } ] + } } specs: - selector: span[name = "Tracetest trigger"] assertions: - attr:tracetest.selected_spans.count = 1 - - attr:tracetest.response.status = 200 + - attr:tracetest.response.status = 201 # ensure we can reference outputs declared in the same test - - attr:tracetest.response.body | json_path '$.id' = env:ENVIRONMENT_ID + - attr:tracetest.response.body | json_path '$.spec.id' = env:ENVIRONMENT_ID - selector: span[name="POST /api/environments" tracetest.span.type="http"] assertions: - - attr:tracetest.selected_spans.count = 1 + - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec INSERT"] assertions: - attr:tracetest.selected_spans.count = 1 @@ -43,6 +45,6 @@ spec: assertions: - attr:sql.query contains "INSERT INTO environments" outputs: - - name: ENVIRONMENT_ID - selector: span[name = "Tracetest trigger"] - value: attr:tracetest.response.body | json_path '$.id' + - name: ENVIRONMENT_ID + selector: span[name = "Tracetest trigger"] + value: attr:tracetest.response.body | json_path '$.spec.id' diff --git a/tracetesting/features/environment/02_list_environment.yml b/tracetesting/features/environment/02_list_environment.yml index 0394e0d7e9..4fc01c03e7 100644 --- a/tracetesting/features/environment/02_list_environment.yml +++ b/tracetesting/features/environment/02_list_environment.yml @@ -1,4 +1,3 @@ ---- type: Test spec: name: List Environment @@ -16,10 +15,10 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 200 - - attr:tracetest.response.body | json_path '$[*].id' contains env:ENVIRONMENT_ID # check if the environment is listed + - attr:tracetest.response.body | json_path '$.items[*].spec.id' contains env:ENVIRONMENT_ID # check if the environment is listed - selector: span[name="GET /api/environments" tracetest.span.type="http"] assertions: - - attr:tracetest.selected_spans.count = 1 + - attr:tracetest.selected_spans.count = 1 - selector: span[name = "query SELECT"] assertions: - attr:tracetest.selected_spans.count = 2 diff --git a/tracetesting/features/environment/03_delete_environment.yml b/tracetesting/features/environment/03_delete_environment.yml index 99945a486a..92a022d7bd 100644 --- a/tracetesting/features/environment/03_delete_environment.yml +++ b/tracetesting/features/environment/03_delete_environment.yml @@ -16,7 +16,7 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 204 - - selector: span[name="DELETE /api/environments/{environmentId}" tracetest.span.type="http"] + - selector: span[tracetest.span.type="http" http.method = "DELETE"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec DELETE"] diff --git a/web/src/components/EnvironmentForm/EnvironmentForm.tsx b/web/src/components/EnvironmentForm/EnvironmentForm.tsx index 6812588271..794135b9e1 100644 --- a/web/src/components/EnvironmentForm/EnvironmentForm.tsx +++ b/web/src/components/EnvironmentForm/EnvironmentForm.tsx @@ -21,6 +21,9 @@ const EnvironmentForm = ({form, initialValues, onSubmit, onValidate}: IProps) => onFinish={onSubmit} onValuesChange={onValidate} > + diff --git a/web/src/components/EnvironmentModal/EnvironmentModal.tsx b/web/src/components/EnvironmentModal/EnvironmentModal.tsx index 28c591b387..6add01e455 100644 --- a/web/src/components/EnvironmentModal/EnvironmentModal.tsx +++ b/web/src/components/EnvironmentModal/EnvironmentModal.tsx @@ -5,6 +5,7 @@ import EnvironmentForm from 'components/EnvironmentForm'; import Environment from 'models/Environment.model'; import * as S from './EnvironmentModal.styled'; import EnvironmentModalFooter from './EnvironmentModalFooter'; +import EnvironmentService from '../../services/Environment.service'; interface IProps { environment?: Environment; @@ -29,8 +30,8 @@ const EnvironmentModal = ({environment, isOpen, onClose, onSubmit, isLoading}: I } }, [environment, form, isOpen]); - const handleOnValidate = (changedValues: any, {name, description, values}: Environment) => { - setIsFormValid(Boolean(name) && Boolean(description) && Boolean(values.length)); + const handleOnValidate = (changedValues: any, draft: Environment) => { + setIsFormValid(EnvironmentService.validateDraft(draft)); }; const handleOnSubmit = async (values: Environment) => { diff --git a/web/src/components/FileViewerModal/FileViewerModal.provider.tsx b/web/src/components/FileViewerModal/FileViewerModal.provider.tsx index d6d6a3809f..1aeb2763de 100644 --- a/web/src/components/FileViewerModal/FileViewerModal.provider.tsx +++ b/web/src/components/FileViewerModal/FileViewerModal.provider.tsx @@ -1,7 +1,11 @@ import {capitalize, noop} from 'lodash'; import {createContext, useCallback, useContext, useMemo, useState} from 'react'; import FileViewerModal from 'components/FileViewerModal'; -import {useLazyGetJUnitByRunIdQuery, useLazyGetResourceDefinitionQuery} from 'redux/apis/TraceTest.api'; +import { + useLazyGetJUnitByRunIdQuery, + useLazyGetResourceDefinitionQuery, + useLazyGetResourceDefinitionV2Query, +} from 'redux/apis/TraceTest.api'; import {ResourceType} from 'types/Resource.type'; interface IContext { @@ -43,6 +47,7 @@ const FileViewerModalProvider = ({children}: IProps) => { }); const [getJUnit] = useLazyGetJUnitByRunIdQuery(); const [getResourceDefinition] = useLazyGetResourceDefinitionQuery(); + const [getResourceDefinitionV2] = useLazyGetResourceDefinitionV2Query(); const [fileProps, setProps] = useState({ title: '', language: '', @@ -62,7 +67,9 @@ const FileViewerModalProvider = ({children}: IProps) => { const loadDefinition = useCallback( async (resourceType: ResourceType, resourceId: string, version?: number) => { - const data = await getResourceDefinition({resourceId, version, resourceType}).unwrap(); + const data = await (resourceType === ResourceType.Environment + ? getResourceDefinitionV2({resourceId, resourceType}).unwrap() + : getResourceDefinition({resourceId, version, resourceType}).unwrap()); setIsFileViewerOpen(true); setFileViewerData({data, type: 'definition'}); setProps({ @@ -72,7 +79,7 @@ const FileViewerModalProvider = ({children}: IProps) => { fileName: `${resourceType}-${resourceId}-${version || 0}-definition.yaml`, }); }, - [getResourceDefinition] + [getResourceDefinition, getResourceDefinitionV2] ); const value: IContext = useMemo(() => ({loadJUnit, loadDefinition}), [loadJUnit, loadDefinition]); diff --git a/web/src/models/Environment.model.ts b/web/src/models/Environment.model.ts index a505a68456..01fc5eaf51 100644 --- a/web/src/models/Environment.model.ts +++ b/web/src/models/Environment.model.ts @@ -1,17 +1,26 @@ import {Model, TEnvironmentSchemas} from 'types/Common.types'; import {IKeyValue} from '../constants/Test.constants'; -export type TRawEnvironment = TEnvironmentSchemas['Environment']; +export type TRawEnvironment = TEnvironmentSchemas['EnvironmentResource']; export type TEnvironmentValue = TEnvironmentSchemas['EnvironmentValue']; -type Environment = Model; +type Environment = Model; -function Environment({id = '', name = '', description = '', values = []}: TRawEnvironment): Environment { +function Environment({spec: {id = '', name = '', description = '', values = []} = {}}: TRawEnvironment): Environment { + return Environment.fromRun({id, name, description, values}); +} + +Environment.fromRun = ({ + id = '', + name = '', + description = '', + values = [], +}: TEnvironmentSchemas['Environment']): Environment => { return { id, name, description, values: values?.map(value => ({key: value?.key ?? '', value: value?.value ?? ''})), }; -} +}; export default Environment; diff --git a/web/src/models/TestRun.model.ts b/web/src/models/TestRun.model.ts index 43f5b23b98..8302781486 100644 --- a/web/src/models/TestRun.model.ts +++ b/web/src/models/TestRun.model.ts @@ -125,7 +125,7 @@ const TestRun = ({ passedAssertionCount: getTestResultCount(result, 'passed'), metadata, outputs: outputs?.map(rawOutput => TestRunOutput(rawOutput)), - environment: Environment(environment), + environment: Environment.fromRun(environment), transactionId, transactionRunId, }; diff --git a/web/src/models/TransactionRun.model.ts b/web/src/models/TransactionRun.model.ts index df7dfaa823..8968edc9e2 100644 --- a/web/src/models/TransactionRun.model.ts +++ b/web/src/models/TransactionRun.model.ts @@ -30,7 +30,7 @@ const TransactionRun = ({ completedAt, state, steps: steps.map(step => TestRun(step)), - environment: Environment(environment), + environment: Environment.fromRun(environment), metadata, version, pass, diff --git a/web/src/providers/Environment/Environment.provider.tsx b/web/src/providers/Environment/Environment.provider.tsx index 5c47fecb75..7609760976 100644 --- a/web/src/providers/Environment/Environment.provider.tsx +++ b/web/src/providers/Environment/Environment.provider.tsx @@ -6,6 +6,7 @@ import {setUserPreference} from 'redux/slices/User.slice'; import EnvironmentSelectors from 'selectors/Environment.selectors'; import Environment from 'models/Environment.model'; import EnvironmentModal from 'components/EnvironmentModal'; +import EnvironmentService from 'services/Environment.service'; import useEnvironmentCrud from './hooks/useEnvironmentCrud'; interface IContext { @@ -54,10 +55,11 @@ const EnvironmentProvider = ({children}: IProps) => { const onSubmit = useCallback( (values: Environment) => { + const request = EnvironmentService.getRequest(values); if (environment) { - edit(environment.id, values); + edit(environment.id, request); } else { - create(values); + create(request); } setIsModalOpen(false); }, diff --git a/web/src/providers/Environment/hooks/useEnvironmentCrud.ts b/web/src/providers/Environment/hooks/useEnvironmentCrud.ts index f552e034ee..2dde3c50f5 100644 --- a/web/src/providers/Environment/hooks/useEnvironmentCrud.ts +++ b/web/src/providers/Environment/hooks/useEnvironmentCrud.ts @@ -5,8 +5,8 @@ import { useUpdateEnvironmentMutation, } from 'redux/apis/TraceTest.api'; import {useConfirmationModal} from 'providers/ConfirmationModal/ConfirmationModal.provider'; -import Environment from 'models/Environment.model'; import {useNotification} from 'providers/Notification/Notification.provider'; +import {TRawEnvironment} from 'models/Environment.model'; const useEnvironmentCrud = () => { const [deleteEnvironment] = useDeleteEnvironmentMutation(); @@ -33,7 +33,7 @@ const useEnvironmentCrud = () => { ); const edit = useCallback( - async (environmentId: string, environment: Environment) => { + async (environmentId: string, environment: TRawEnvironment) => { await updateEnvironment({environmentId, environment}); showNotification({ type: 'success', @@ -44,7 +44,7 @@ const useEnvironmentCrud = () => { ); const create = useCallback( - async (environment: Environment) => { + async (environment: TRawEnvironment) => { await createEnvironment(environment); showNotification({ diff --git a/web/src/redux/apis/TraceTest.api.ts b/web/src/redux/apis/TraceTest.api.ts index 168df7c680..cbf77e2c81 100644 --- a/web/src/redux/apis/TraceTest.api.ts +++ b/web/src/redux/apis/TraceTest.api.ts @@ -82,6 +82,7 @@ export const { useGetDemoQuery, useCreateSettingMutation, useUpdateSettingMutation, + useLazyGetResourceDefinitionV2Query, } = TraceTestAPI; export const {endpoints} = TraceTestAPI; diff --git a/web/src/redux/apis/endpoints/Environment.endpoint.ts b/web/src/redux/apis/endpoints/Environment.endpoint.ts index 0d1c08a9b0..28d71d1c86 100644 --- a/web/src/redux/apis/endpoints/Environment.endpoint.ts +++ b/web/src/redux/apis/endpoints/Environment.endpoint.ts @@ -3,22 +3,30 @@ import {TracetestApiTags} from 'constants/Test.constants'; import {PaginationResponse} from 'hooks/usePagination'; import Environment, {TRawEnvironment} from 'models/Environment.model'; import {TTestApiEndpointBuilder} from 'types/Test.types'; -import {getTotalCountFromHeaders} from 'utils/Common'; +import {TListResponse} from 'types/Settings.types'; const EnvironmentEndpoint = (builder: TTestApiEndpointBuilder) => ({ getEnvironments: builder.query, {take?: number; skip?: number; query?: string}>({ - query: ({take = 25, skip = 0, query = ''}) => `/environments?take=${take}&skip=${skip}&query=${query}`, + query: ({take = 25, skip = 0, query = ''}) => ({ + url: `/environments?take=${take}&skip=${skip}&query=${query}`, + headers: { + 'content-type': 'application/json', + }, + }), providesTags: () => [{type: TracetestApiTags.ENVIRONMENT, id: 'LIST'}], - transformResponse: (rawEnvironments: TRawEnvironment[], meta) => ({ - items: rawEnvironments.map(rawEnv => Environment(rawEnv)), - total: getTotalCountFromHeaders(meta), + transformResponse: ({items, count}: TListResponse) => ({ + items: items.map(rawEnv => Environment(rawEnv)), + total: count, }), }), - createEnvironment: builder.mutation({ + createEnvironment: builder.mutation({ query: environment => ({ url: '/environments', method: HTTP_METHOD.POST, body: environment, + headers: { + 'content-type': 'application/json', + }, }), invalidatesTags: [{type: TracetestApiTags.ENVIRONMENT, id: 'LIST'}], }), @@ -27,6 +35,9 @@ const EnvironmentEndpoint = (builder: TTestApiEndpointBuilder) => ({ url: `/environments/${environmentId}`, method: HTTP_METHOD.PUT, body: environment, + headers: { + 'content-type': 'application/json', + }, }), invalidatesTags: [{type: TracetestApiTags.ENVIRONMENT, id: 'LIST'}], }), @@ -34,6 +45,9 @@ const EnvironmentEndpoint = (builder: TTestApiEndpointBuilder) => ({ query: ({environmentId}) => ({ url: `/environments/${environmentId}`, method: HTTP_METHOD.DELETE, + headers: { + 'content-type': 'application/json', + }, }), invalidatesTags: [{type: TracetestApiTags.ENVIRONMENT, id: 'LIST'}], }), diff --git a/web/src/redux/apis/endpoints/Resource.endpoint.ts b/web/src/redux/apis/endpoints/Resource.endpoint.ts index f9d934612d..e48dc3f369 100644 --- a/web/src/redux/apis/endpoints/Resource.endpoint.ts +++ b/web/src/redux/apis/endpoints/Resource.endpoint.ts @@ -29,6 +29,18 @@ const ResourceEndpoint = (builder: TTestApiEndpointBuilder) => ({ {type: TracetestApiTags.RESOURCE, id: `${resourceId}-${version}-definition`}, ], }), + getResourceDefinitionV2: builder.query({ + query: ({resourceId, resourceType}) => ({ + url: `/${resourceType}s/${resourceId}`, + responseHandler: 'text', + headers: { + 'content-type': 'text/yaml', + } + }), + providesTags: (result, error, {resourceId, version}) => [ + {type: TracetestApiTags.RESOURCE, id: `${resourceId}-${version}-definition`}, + ], + }), }); export default ResourceEndpoint; diff --git a/web/src/services/Environment.service.ts b/web/src/services/Environment.service.ts new file mode 100644 index 0000000000..4d8df076c0 --- /dev/null +++ b/web/src/services/Environment.service.ts @@ -0,0 +1,16 @@ +import Environment, {TRawEnvironment} from 'models/Environment.model'; + +const EnvironmentService = () => ({ + getRequest(environment: Environment): TRawEnvironment { + return { + type: 'Environment', + spec: environment, + }; + }, + + validateDraft({name = '', description = '', values = []}: Environment) { + return !!name && !!description && !!values.length; + }, +}); + +export default EnvironmentService(); diff --git a/web/src/types/Generated.types.ts b/web/src/types/Generated.types.ts index 7b824cbbac..8ad8c53c46 100644 --- a/web/src/types/Generated.types.ts +++ b/web/src/types/Generated.types.ts @@ -114,24 +114,6 @@ export interface paths { /** get events from a test run */ get: operations["getTestRunEvents"]; }; - "/environments": { - /** Get Environments */ - get: operations["getEnvironments"]; - /** Create new environment action */ - post: operations["createEnvironment"]; - }; - "/environments/{environmentId}": { - /** get environment */ - get: operations["getEnvironment"]; - /** update environment action */ - put: operations["updateEnvironment"]; - /** delete a environment */ - delete: operations["deleteEnvironment"]; - }; - "/environments/{environmentId}/definition.yaml": { - /** Get the environment as an YAML file */ - get: operations["getEnvironmentDefinitionFile"]; - }; "/expressions/resolve": { /** resolves an expression and returns the result string */ post: operations["ExpressionResolve"]; @@ -178,6 +160,20 @@ export interface paths { /** Delete a Data Store */ delete: operations["deleteDataStore"]; }; + "/environments": { + /** List environments available in Tracetest. */ + get: operations["listEnvironments"]; + /** Create an environment that can be used by tests and transactions */ + post: operations["createEnvironment"]; + }; + "/environments/{environmentId}": { + /** Get one environment by its id */ + get: operations["getEnvironment"]; + /** Update an environment used on Tracetest */ + put: operations["updateEnvironment"]; + /** Delete an environment from Tracetest */ + delete: operations["deleteEnvironment"]; + }; } export interface components {} @@ -652,107 +648,6 @@ export interface operations { }; }; }; - /** Get Environments */ - getEnvironments: { - parameters: {}; - responses: { - /** successful operation */ - 200: { - headers: { - /** Total records count */ - "X-Total-Count"?: number; - }; - content: { - "application/json": external["environments.yaml"]["components"]["schemas"]["Environment"][]; - }; - }; - /** problem with getting environments */ - 500: unknown; - }; - }; - /** Create new environment action */ - createEnvironment: { - responses: { - /** successful operation */ - 200: { - content: { - "application/json": external["environments.yaml"]["components"]["schemas"]["Environment"]; - }; - }; - /** trying to create a environment with an already existing ID */ - 400: unknown; - }; - requestBody: { - content: { - "application/json": external["environments.yaml"]["components"]["schemas"]["Environment"]; - }; - }; - }; - /** get environment */ - getEnvironment: { - parameters: { - path: { - environmentId: string; - }; - }; - responses: { - /** successful operation */ - 200: { - content: { - "application/json": external["environments.yaml"]["components"]["schemas"]["Environment"]; - }; - }; - /** problem with getting a environment */ - 500: unknown; - }; - }; - /** update environment action */ - updateEnvironment: { - parameters: { - path: { - environmentId: string; - }; - }; - responses: { - /** successful operation */ - 204: never; - /** problem with updating environment */ - 500: unknown; - }; - requestBody: { - content: { - "application/json": external["environments.yaml"]["components"]["schemas"]["Environment"]; - }; - }; - }; - /** delete a environment */ - deleteEnvironment: { - parameters: { - path: { - environmentId: string; - }; - }; - responses: { - /** OK */ - 204: never; - }; - }; - /** Get the environment as an YAML file */ - getEnvironmentDefinitionFile: { - parameters: { - path: { - environmentId: string; - }; - }; - responses: { - /** OK */ - 200: { - content: { - "application/yaml": string; - }; - }; - }; - }; /** resolves an expression and returns the result string */ ExpressionResolve: { responses: { @@ -1013,11 +908,108 @@ export interface operations { }; /** Delete a Data Store */ deleteDataStore: { + parameters: {}; + responses: { + /** OK */ + 204: never; + }; + }; + /** List environments available in Tracetest. */ + listEnvironments: { + parameters: {}; + responses: { + /** successful operation */ + 200: { + content: { + "application/json": { + count?: number; + items?: external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"][]; + }; + "text/yaml": { + count?: number; + items?: external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"][]; + }; + }; + }; + /** invalid query for environments, some data was sent in incorrect format. */ + 400: unknown; + /** problem listing environments */ + 500: unknown; + }; + }; + /** Create an environment that can be used by tests and transactions */ + createEnvironment: { + responses: { + /** successful operation */ + 201: { + content: { + "application/json": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + "text/yaml": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + }; + }; + /** problem creating an environment */ + 500: unknown; + }; + requestBody: { + content: { + "application/json": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + "text/yaml": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + }; + }; + }; + /** Get one environment by its id */ + getEnvironment: { + parameters: {}; + responses: { + /** successful operation */ + 200: { + content: { + "application/json": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + "text/yaml": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + }; + }; + /** environment not found */ + 404: unknown; + /** problem getting the environment */ + 500: unknown; + }; + }; + /** Update an environment used on Tracetest */ + updateEnvironment: { + parameters: {}; + responses: { + /** successful operation */ + 200: { + content: { + "application/json": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + "text/yaml": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + }; + }; + /** invalid environment, some data was sent in incorrect format. */ + 400: unknown; + /** environment not found */ + 404: unknown; + /** problem updating the environment */ + 500: unknown; + }; + requestBody: { + content: { + "application/json": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + "text/yaml": external["environments.yaml"]["components"]["schemas"]["EnvironmentResource"]; + }; + }; + }; + /** Delete an environment from Tracetest */ + deleteEnvironment: { parameters: {}; responses: { /** successful operation */ 204: never; - /** problem with data store deletion */ + /** invalid environment, some data was sent in incorrect format. */ + 400: unknown; + /** environment not found */ + 404: unknown; + /** problem deleting an environment */ 500: unknown; }; }; @@ -1281,6 +1273,15 @@ export interface external { paths: {}; components: { schemas: { + /** @description Represents an environment structured into the Resources format. */ + EnvironmentResource: { + /** + * @description Represents the type of this resource. It should always be set as 'Environment'. + * @enum {string} + */ + type?: "Environment"; + spec?: external["environments.yaml"]["components"]["schemas"]["Environment"]; + }; Environment: { id?: string; name?: string; @@ -1435,6 +1436,8 @@ export interface external { pollingProfileId: string; /** @description ID of a datastore used on Tracetest to configure how to fetch traces in a test */ dataStoreId: string; + /** @description ID of an enviroment used on Tracetest to inject values into tests and transactions */ + environmentId: string; }; }; operations: {};