From 16027db3df76c4aa159a18852c5d843d1236aa60 Mon Sep 17 00:00:00 2001 From: Tibor Kiss <32801432+the1bit@users.noreply.github.com> Date: Fri, 26 Jan 2024 15:25:43 +0100 Subject: [PATCH] Add golangci-lint config (#55) * Update Makefile * Prepare Linting * Importas * importas * Importas * eppnats * emlogger * ceeventv2 * eppapi * matsgo * cev2 * eventingv1alpha1, eventingv2alpha1, epptestingutils * ocpropagation * Hint for naming convention * Rename alias golog --> log * Cloud Events without version * Remove versions * Centralized * Go lint * Importas lint --- .github/workflows/lint-go.yml | 19 ++ .github/workflows/lint.yml | 30 -- .gitignore | 6 + .golangci.yaml | 281 ------------------ Makefile | 37 ++- cmd/eventing-publisher-proxy/main.go | 14 +- .../applicationtest/applicationtest.go | 10 +- pkg/application/clean.go | 6 +- pkg/application/clean_test.go | 6 +- pkg/application/fake/lister.go | 14 +- pkg/application/lister.go | 18 +- pkg/cloudevents/builder/eventmesh.go | 4 +- pkg/cloudevents/builder/eventmesh_test.go | 17 +- pkg/cloudevents/builder/generic.go | 4 +- pkg/cloudevents/builder/generic_test.go | 20 +- pkg/cloudevents/builder/types.go | 4 +- pkg/commander/nats/nats.go | 12 +- pkg/handler/handler.go | 22 +- pkg/handler/handler_test.go | 10 +- pkg/handler/handler_v1alpha1_test.go | 40 +-- pkg/legacy/helpers.go | 4 +- pkg/legacy/legacy.go | 44 +-- pkg/legacy/legacy_test.go | 70 ++--- pkg/nats/connect_test.go | 14 +- pkg/oauth/client_test.go | 6 +- pkg/receiver/receiver.go | 4 +- pkg/receiver/receiver_test.go | 4 +- pkg/sender/eventmesh/eventmesh.go | 4 +- pkg/sender/eventmesh/eventmesh_test.go | 12 +- pkg/sender/jetstream/jetstream_test.go | 24 +- pkg/subscribed/helpers.go | 30 +- pkg/subscribed/helpers_test.go | 66 ++-- pkg/tracing/helpers.go | 4 +- pkg/tracing/helpers_test.go | 4 +- testing/fixtures.go | 6 +- testing/nats.go | 10 +- testing/utils.go | 4 +- 37 files changed, 316 insertions(+), 568 deletions(-) create mode 100644 .github/workflows/lint-go.yml delete mode 100644 .github/workflows/lint.yml delete mode 100644 .golangci.yaml diff --git a/.github/workflows/lint-go.yml b/.github/workflows/lint-go.yml new file mode 100644 index 0000000..a359b01 --- /dev/null +++ b/.github/workflows/lint-go.yml @@ -0,0 +1,19 @@ +name: Lint Go code + +on: + pull_request: + branches: + - "main" + - "release-*" + paths-ignore: + - 'docs/**' + - '**.md' + - 'sec-scanners-config.yaml' + +jobs: + code-linter: + name: "Run golangci-lint" + uses: kyma-project/eventing-tools/.github/workflows/lint-go-reusable.yml@main + with: + go-version: '1.21' + lint-config-uri: https://raw.githubusercontent.com/kyma-project/eventing-tools/b740019d37e5b69c1a1383c71bb5fb5a44c6534e/config/lint/.golangci.yaml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml deleted file mode 100644 index 3ef1c99..0000000 --- a/.github/workflows/lint.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Linting - -on: - pull_request: - branches: - - "main" - - "release-*" - paths-ignore: - - 'docs/**' - - '**.md' - - 'sec-scanners-config.yaml' - -jobs: - linting: - runs-on: ubuntu-latest - steps: - - name: Setup go environment - uses: actions/setup-go@v5 - with: - go-version: '1.21' - cache: false - - - name: Checkout repo - uses: actions/checkout@v4 - - - name: Run linting - uses: golangci/golangci-lint-action@v3 - with: - version: v1.55 - args: --timeout=5m --config=./.golangci.yaml diff --git a/.gitignore b/.gitignore index 25bc235..9203068 100755 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,9 @@ vendor/ **/.env **/.env.dev + + +# Lint files +lint-report.json +.golangci.yaml + diff --git a/.golangci.yaml b/.golangci.yaml deleted file mode 100644 index 1afe962..0000000 --- a/.golangci.yaml +++ /dev/null @@ -1,281 +0,0 @@ -# This code is licensed under the terms of the MIT license. - -## Golden config for golangci-lint v1.49.0 -# -# This is the best config for golangci-lint based on my experience and opinion. -# It is very strict, but not extremely strict. -# Feel free to adopt and change it for your needs. - -run: - # Timeout for analysis, e.g. 30s, 5m. - # Default: 1m - timeout: 3m - - -# This file contains only configs which differ from defaults. -# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml -linters-settings: - cyclop: - # The maximal code complexity to report. - # Default: 10 - max-complexity: 30 - # The maximal average package complexity. - # If it's higher than 0.0 (float) the check is enabled - # Default: 0.0 - package-average: 10.0 - - errcheck: - # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. - # Such cases aren't reported by default. - # Default: false - check-type-assertions: true - - funlen: - # Checks the number of lines in a function. - # If lower than 0, disable the check. - # Default: 60 - lines: 100 - # Checks the number of statements in a function. - # If lower than 0, disable the check. - # Default: 40 - statements: 50 - - gocognit: - # Minimal code complexity to report - # Default: 30 (but we recommend 10-20) - min-complexity: 20 - - gocritic: - # Settings passed to gocritic. - # The settings key is the name of a supported gocritic checker. - # The list of supported checkers can be find in https://go-critic.github.io/overview. - settings: - captLocal: - # Whether to restrict checker to params only. - # Default: true - paramsOnly: false - underef: - # Whether to skip (*x).method() calls where x is a pointer receiver. - # Default: true - skipRecvDeref: false - - gomnd: - # List of function patterns to exclude from analysis. - # Values always ignored: `time.Date` - # Default: [] - ignored-functions: - - os.Chmod - - os.Mkdir - - os.MkdirAll - - os.OpenFile - - os.WriteFile - - prometheus.ExponentialBuckets - - prometheus.ExponentialBucketsRange - - prometheus.LinearBuckets - - strconv.FormatFloat - - strconv.FormatInt - - strconv.FormatUint - - strconv.ParseFloat - - strconv.ParseInt - - strconv.ParseUint - - gomodguard: - blocked: - # List of blocked modules. - # Default: [] - modules: - - github.com/golang/protobuf: - recommendations: - - google.golang.org/protobuf - reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules" - - github.com/satori/go.uuid: - recommendations: - - github.com/google/uuid - reason: "satori's package is not maintained" - - github.com/gofrs/uuid: - recommendations: - - github.com/google/uuid - reason: "see recommendation from dev-infra team: https://confluence.gtforge.com/x/gQI6Aw" - - govet: - # Enable all analyzers. - # Default: false - enable-all: true - # Disable analyzers by name. - # Run `go tool vet help` to see all analyzers. - # Default: [] - disable: - - fieldalignment # too strict - # Settings per analyzer. - settings: - shadow: - # Whether to be strict about shadowing; can be noisy. - # Default: false - strict: false - - nakedret: - # Make an issue if func has more lines of code than this setting, and it has naked returns. - # Default: 30 - max-func-lines: 0 - - nolintlint: - # Exclude following linters from requiring an explanation. - # Default: [] - allow-no-explanation: [ funlen, gocognit, lll ] - # Enable to require an explanation of nonzero length after each nolint directive. - # Default: false - require-explanation: true - # Enable to require nolint directives to mention the specific linter being suppressed. - # Default: false - require-specific: true - - rowserrcheck: - # database/sql is always checked - # Default: [] - packages: - - github.com/jmoiron/sqlx - - tenv: - # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. - # Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. - # Default: false - all: true - - -linters: - disable-all: true - enable: - ## enabled by default - - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases - - gosimple # specializes in simplifying a code - - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - ineffassign # detects when assignments to existing variables are not used - - staticcheck # is a go vet on steroids, applying a ton of static analysis checks - - typecheck # like the front-end of a Go compiler, parses and type-checks Go code - - unused # checks for unused constants, variables, functions and types - ## disabled by default - - asasalint # checks for pass []any as any in variadic func(...any) - - asciicheck # checks that your code does not contain non-ASCII identifiers - - bidichk # checks for dangerous unicode character sequences - - bodyclose # checks whether HTTP response body is closed successfully - #- contextcheck # checks the function whether use a non-inherited context # TODO: enable after golangci-lint uses https://github.com/sylvia7788/contextcheck/releases/tag/v1.0.7 - - cyclop # checks function and package cyclomatic complexity - - dupl # tool for code clone detection - - durationcheck # checks for two durations multiplied together - - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error - - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 - - execinquery # checks query string in Query function which reads your Go src files and warning it finds - - exhaustive # checks exhaustiveness of enum switch statements - - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # forbids identifiers - - funlen # tool for detection of long functions - - gochecknoglobals # checks that no global variables exist - - gochecknoinits # checks that no init functions are present in Go code - - gocognit # computes and checks the cognitive complexity of functions - - goconst # finds repeated strings that could be replaced by a constant - - gocritic # provides diagnostics that check for bugs, performance and style issues - - gocyclo # computes and checks the cyclomatic complexity of functions - - godot # checks if comments end in a period - - goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt - - gomnd # detects magic numbers - ## - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod - - gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations - - goprintffuncname # checks that printf-like functions are named with f at the end - - gosec # inspects source code for security problems - - lll # reports long lines - - makezero # finds slice declarations with non-zero initial length - - nakedret # finds naked returns in functions greater than a specified function length - - nestif # reports deeply nested if statements - - nilerr # finds the code that returns nil even if it checks that the error is not nil - - nilnil # checks that there is no simultaneous return of nil error and an invalid value - - noctx # finds sending http request without context.Context - - nolintlint # reports ill-formed or insufficient nolint directives - - nonamedreturns # reports all named returns - - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL - - predeclared # finds code that shadows one of Go's predeclared identifiers - - promlinter # checks Prometheus metrics naming via promlint - - reassign # checks that package variables are not reassigned - - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint - - rowserrcheck # checks whether Err of rows is checked successfully - - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed - - stylecheck # is a replacement for golint - - tenv # detects using os.Setenv instead of t.Setenv since Go1.17 - # - testpackage # makes you use a separate _test package - - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes - - unconvert # removes unnecessary type conversions - - unparam # reports unused function parameters - - usestdlibvars # detects the possibility to use variables/constants from the Go standard library - - wastedassign # finds wasted assignment statements - - whitespace # detects leading and trailing whitespace - - ## you may want to enable - #- decorder # checks declaration order and count of types, constants, variables and functions - #- exhaustruct # checks if all structure fields are initialized - #- gci # controls golang package import order and makes it always deterministic - #- godox # detects FIXME, TODO and other comment keywords - #- goheader # checks is file header matches to pattern - #- interfacebloat # checks the number of methods inside an interface - #- ireturn # accept interfaces, return concrete types - #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated - #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope - #- wrapcheck # checks that errors returned from external packages are wrapped - - ## disabled - #- containedctx # detects struct contained context.Context field - #- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages - #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted - #- forcetypeassert # [replaced by errcheck] finds forced type assertions - #- goerr113 # [too strict] checks the errors handling expressions - #- gofmt # [replaced by goimports] checks whether code was gofmt-ed - #- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed - #- grouper # analyzes expression groups - #- importas # enforces consistent import aliases - #- logrlint # [owner archived repository] checks logr arguments - #- maintidx # measures the maintainability index of each function - #- misspell # [useless] finds commonly misspelled English words in comments - #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity - #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test - #- tagliatelle # checks the struct tags - #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers - #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines - - ## deprecated - #- deadcode # [deprecated, replaced by unused] finds unused code - #- exhaustivestruct # [deprecated, replaced by exhaustruct] checks if all struct's fields are initialized - #- golint # [deprecated, replaced by revive] golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - #- ifshort # [deprecated] checks that your code uses short syntax for if-statements whenever possible - #- interfacer # [deprecated] suggests narrower interface types - #- maligned # [deprecated, replaced by govet fieldalignment] detects Go structs that would take less memory if their fields were sorted - #- nosnakecase # [deprecated, replaced by revive var-naming] detects snake case of variable naming and function name - #- scopelint # [deprecated, replaced by exportloopref] checks for unpinned variables in go programs - #- structcheck # [deprecated, replaced by unused] finds unused struct fields - #- varcheck # [deprecated, replaced by unused] finds unused global variables and constants - - -issues: - # Maximum count of issues with the same text. - # Set to 0 to disable. - # Default: 3 - max-same-issues: 50 - - exclude-rules: - - source: "^//\\s*go:generate\\s" - linters: [ lll ] - - source: "(noinspection|TODO)" - linters: [ godot ] - - source: "//noinspection" - linters: [ gocritic ] - - source: "^\\s+if _, ok := err\\.\\([^.]+\\.InternalError\\); ok {" - linters: [ errorlint ] - - path: "_test\\.go" - linters: - - bodyclose - - dupl - - funlen - - goconst - - gosec - - noctx - - wrapcheck - - text: 'shadow: declaration of "(err|ctx)" shadows declaration at' - linters: [ govet ] diff --git a/Makefile b/Makefile index 3d75c9c..b6ff91e 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,9 @@ IMG_REGISTRY_PORT ?= 8888 IMG_REGISTRY ?= op-skr-registry.localhost:$(IMG_REGISTRY_PORT)/unsigned/eventing-images IMG ?= $(IMG_REGISTRY)/$(APP_NAME):$(APP_VERSION) +# Lint issue category +CATEGORY = "default" + # Setting SHELL to bash allows bash commands to be executed by recipes. # Options are set to exit when a recipe line exits non-zero or a piped command fails. SHELL = /usr/bin/env bash -o pipefail @@ -40,9 +43,41 @@ help: ## Display this help. ##@ Development .PHONY: lint -lint: ## Check and fix lint issues using `golangci-lint` +lint: ## Check lint issues using `golangci-lint` + golangci-lint run --timeout 5m --config=./.golangci.yaml + +.PHONY: lint-compact +lint-compact: ## Check lint issues using `golangci-lint` in compact result format + golangci-lint run --timeout 5m --config=./.golangci.yaml --print-issued-lines=false + +.PHONY: lint-fix +lint-fix: ## Check and fix lint issues using `golangci-lint` golangci-lint run --fix --timeout 5m --config=./.golangci.yaml +.PHONY: lint-report +lint-report: ## Check lint issues using `golangci-lint` then export them to a file, then print the list of linters used + golangci-lint run --timeout 5m --config=./.golangci.yaml --issues-exit-code 0 --out-format json > ./lint-report.json + +.PHONY: lint-report-issue-category +lint-report-issue-category: ## Get lint issues categories + make lint-report-clean + make lint-report + cat ./lint-report.json | jq '.Issues[].FromLinter' | jq -s 'map({(.):1})|add|keys_unsorted' + +.PHONY: lint-report-get-category +lint-report-get-category: ## Get lint issues by category + cat ./lint-report.json | jq --arg CATEGORY $$CATEGORY '.Issues[] | select(.FromLinter==$$CATEGORY)' + +.PHONY: lint-report-count-issue +lint-report-count-issue: ## Count lint issues + make lint-report-clean + make lint-report + cat ./lint-report.json | jq '.Issues | length' + +.PHONY: lint-report-clean +lint-report-clean: ## Clean lint report + rm -f ./lint-report.json + .PHONY: fmt fmt: ## Reformat files using `go fmt` go fmt $$($(DIRS_TO_CHECK)) diff --git a/cmd/eventing-publisher-proxy/main.go b/cmd/eventing-publisher-proxy/main.go index bf873a7..f0bc730 100644 --- a/cmd/eventing-publisher-proxy/main.go +++ b/cmd/eventing-publisher-proxy/main.go @@ -1,10 +1,10 @@ package main //nolint:cyclop // it is only starting required instances. import ( - golog "log" + log "log" "github.com/kelseyhightower/envconfig" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/prometheus/client_golang/prometheus" "github.com/kyma-project/eventing-publisher-proxy/pkg/commander" @@ -34,23 +34,23 @@ type Config struct { func main() { opts := options.New() if err := opts.Parse(); err != nil { - golog.Fatalf("Failed to parse options, error: %v", err) + log.Fatalf("Failed to parse options, error: %v", err) } // parse the config for main: cfg := new(Config) if err := envconfig.Process("", cfg); err != nil { - golog.Fatalf("Failed to read configuration, error: %v", err) + log.Fatalf("Failed to read configuration, error: %v", err) } // init the logger - logger, err := kymalogger.New(cfg.AppLogFormat, cfg.AppLogLevel) + logger, err := emlogger.New(cfg.AppLogFormat, cfg.AppLogLevel) if err != nil { - golog.Fatalf("Failed to initialize logger, error: %v", err) + log.Fatalf("Failed to initialize logger, error: %v", err) } defer func() { if err := logger.WithContext().Sync(); err != nil { - golog.Printf("Failed to flush logger, error: %v", err) + log.Printf("Failed to flush logger, error: %v", err) } }() setupLogger := logger.WithContext().With("backend", cfg.Backend) diff --git a/pkg/application/applicationtest/applicationtest.go b/pkg/application/applicationtest/applicationtest.go index b53f95c..c6ae127 100644 --- a/pkg/application/applicationtest/applicationtest.go +++ b/pkg/application/applicationtest/applicationtest.go @@ -2,14 +2,14 @@ package applicationtest import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - applicationv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" + kymaappconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" ) -func NewApplication(name string, labels map[string]string) *applicationv1alpha1.Application { - return &applicationv1alpha1.Application{ - ObjectMeta: metav1.ObjectMeta{ +func NewApplication(name string, labels map[string]string) *kymaappconnv1alpha1.Application { + return &kymaappconnv1alpha1.Application{ + ObjectMeta: kmetav1.ObjectMeta{ Name: name, Labels: labels, }, diff --git a/pkg/application/clean.go b/pkg/application/clean.go index 345c1c2..caadf68 100644 --- a/pkg/application/clean.go +++ b/pkg/application/clean.go @@ -4,7 +4,7 @@ import ( "regexp" "strings" - applicationv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" + kymaappconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" ) const ( @@ -19,7 +19,7 @@ var ( // GetCleanTypeOrName cleans the application name form none-alphanumeric characters and returns it // if the application type label exists, it will be cleaned and returned instead of the application name. -func GetCleanTypeOrName(application *applicationv1alpha1.Application) string { +func GetCleanTypeOrName(application *kymaappconnv1alpha1.Application) string { if application == nil { return "" } @@ -35,7 +35,7 @@ func GetCleanTypeOrName(application *applicationv1alpha1.Application) string { // GetTypeOrName returns the application name. // if the application type label exists, it will be returned instead of the application name. -func GetTypeOrName(application *applicationv1alpha1.Application) string { +func GetTypeOrName(application *kymaappconnv1alpha1.Application) string { if application == nil { return "" } diff --git a/pkg/application/clean_test.go b/pkg/application/clean_test.go index 048490a..267866d 100644 --- a/pkg/application/clean_test.go +++ b/pkg/application/clean_test.go @@ -5,14 +5,14 @@ import ( "github.com/stretchr/testify/require" - applicationv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" + kymaappconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/applicationtest" ) func TestCleanName(t *testing.T) { testCases := []struct { - givenApplication *applicationv1alpha1.Application + givenApplication *kymaappconnv1alpha1.Application wantName string }{ // application type label is missing, then use the application name @@ -80,7 +80,7 @@ func Test_GetTypeOrName(t *testing.T) { testCases := []struct { name string - givenApplication *applicationv1alpha1.Application + givenApplication *kymaappconnv1alpha1.Application wantName string }{ // application type label is missing, then use the application name diff --git a/pkg/application/fake/lister.go b/pkg/application/fake/lister.go index 552860c..c47e555 100644 --- a/pkg/application/fake/lister.go +++ b/pkg/application/fake/lister.go @@ -4,27 +4,27 @@ import ( "context" "log" - corev1 "k8s.io/api/core/v1" + kcorev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" - dynamicfake "k8s.io/client-go/dynamic/fake" + kdynamicfake "k8s.io/client-go/dynamic/fake" - applicationv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" + kymaappconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" ) -func NewApplicationListerOrDie(ctx context.Context, app *applicationv1alpha1.Application) *application.Lister { +func NewApplicationListerOrDie(ctx context.Context, app *kymaappconnv1alpha1.Application) *application.Lister { scheme := setupSchemeOrDie() - dynamicClient := dynamicfake.NewSimpleDynamicClient(scheme, app) + dynamicClient := kdynamicfake.NewSimpleDynamicClient(scheme, app) return application.NewLister(ctx, dynamicClient) } func setupSchemeOrDie() *runtime.Scheme { scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { + if err := kcorev1.AddToScheme(scheme); err != nil { log.Fatalf("Failed to setup scheme with error: %v", err) } - if err := applicationv1alpha1.AddToScheme(scheme); err != nil { + if err := kymaappconnv1alpha1.AddToScheme(scheme); err != nil { log.Fatalf("Failed to setup scheme with error: %v", err) } return scheme diff --git a/pkg/application/lister.go b/pkg/application/lister.go index 941a8ea..cc21d9d 100644 --- a/pkg/application/lister.go +++ b/pkg/application/lister.go @@ -5,9 +5,9 @@ import ( "errors" "time" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" - applicationv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" - v1 "k8s.io/api/core/v1" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" + kymaappconnv1alpha1 "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apis/applicationconnector/v1alpha1" + kcorev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -25,15 +25,15 @@ type Lister struct { func NewLister(ctx context.Context, client dynamic.Interface) *Lister { const defaultResync = 10 * time.Second gvr := GroupVersionResource() - factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(client, defaultResync, v1.NamespaceAll, nil) + factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(client, defaultResync, kcorev1.NamespaceAll, nil) factory.ForResource(gvr) lister := factory.ForResource(gvr).Lister() - logger, _ := kymalogger.New("json", "error") + logger, _ := emlogger.New("json", "error") informers.WaitForCacheSyncOrDie(ctx, factory, logger) return &Lister{lister: lister} } -func (l Lister) Get(name string) (*applicationv1alpha1.Application, error) { +func (l Lister) Get(name string) (*kymaappconnv1alpha1.Application, error) { object, err := l.lister.Get(name) if err != nil { return nil, err @@ -44,7 +44,7 @@ func (l Lister) Get(name string) (*applicationv1alpha1.Application, error) { return nil, errors.New("failed to convert runtime object to unstructured") } - a := &applicationv1alpha1.Application{} + a := &kymaappconnv1alpha1.Application{} if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, a); err != nil { return nil, err } @@ -54,8 +54,8 @@ func (l Lister) Get(name string) (*applicationv1alpha1.Application, error) { func GroupVersionResource() schema.GroupVersionResource { return schema.GroupVersionResource{ - Group: applicationv1alpha1.SchemeGroupVersion.Group, - Version: applicationv1alpha1.SchemeGroupVersion.Version, + Group: kymaappconnv1alpha1.SchemeGroupVersion.Group, + Version: kymaappconnv1alpha1.SchemeGroupVersion.Version, Resource: "applications", } } diff --git a/pkg/cloudevents/builder/eventmesh.go b/pkg/cloudevents/builder/eventmesh.go index 54686b9..769c6a1 100644 --- a/pkg/cloudevents/builder/eventmesh.go +++ b/pkg/cloudevents/builder/eventmesh.go @@ -1,7 +1,7 @@ package builder import ( - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/logger" @@ -27,7 +27,7 @@ func NewEventMeshBuilder(prefix string, eventMeshNamespace string, cleaner clean } } -func (emb *EventMeshBuilder) Build(event cev2event.Event) (*cev2event.Event, error) { +func (emb *EventMeshBuilder) Build(event ceevent.Event) (*ceevent.Event, error) { ceEvent, err := emb.genericBuilder.Build(event) if err != nil { return nil, err diff --git a/pkg/cloudevents/builder/eventmesh_test.go b/pkg/cloudevents/builder/eventmesh_test.go index d2542e1..330c268 100644 --- a/pkg/cloudevents/builder/eventmesh_test.go +++ b/pkg/cloudevents/builder/eventmesh_test.go @@ -4,17 +4,16 @@ import ( "context" "encoding/json" "fmt" - golog "log" + log "log" "testing" - cloudevents "github.com/cloudevents/sdk-go/v2" - + ce "github.com/cloudevents/sdk-go/v2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/applicationtest" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/fake" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" "github.com/stretchr/testify/require" ) @@ -25,9 +24,9 @@ func Test_EventMesh_Build(t *testing.T) { const eventMeshPrefix = "one.two.three" // init the logger - logger, err := kymalogger.New("json", "debug") + logger, err := emlogger.New("json", "debug") if err != nil { - golog.Fatalf("Failed to initialize logger, error: %v", err) + log.Fatalf("Failed to initialize logger, error: %v", err) } testCases := []struct { @@ -97,9 +96,9 @@ func Test_EventMesh_Build(t *testing.T) { // given // build cloud event - builder := testingutils.NewCloudEventBuilder() + builder := epptestingutils.NewCloudEventBuilder() payload, _ := builder.BuildStructured() - newEvent := cloudevents.NewEvent() + newEvent := ce.NewEvent() err = json.Unmarshal([]byte(payload), &newEvent) require.NoError(t, err) newEvent.SetType(tc.givenType) diff --git a/pkg/cloudevents/builder/generic.go b/pkg/cloudevents/builder/generic.go index 30f9c1a..f80e6c4 100644 --- a/pkg/cloudevents/builder/generic.go +++ b/pkg/cloudevents/builder/generic.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/logger" @@ -35,7 +35,7 @@ func (gb *GenericBuilder) isApplicationListerEnabled() bool { return gb.applicationLister != nil } -func (gb *GenericBuilder) Build(event cev2event.Event) (*cev2event.Event, error) { +func (gb *GenericBuilder) Build(event ceevent.Event) (*ceevent.Event, error) { // format logger namedLogger := gb.namedLogger(event.Source(), event.Type()) diff --git a/pkg/cloudevents/builder/generic_test.go b/pkg/cloudevents/builder/generic_test.go index c4bb6b0..b8bc929 100644 --- a/pkg/cloudevents/builder/generic_test.go +++ b/pkg/cloudevents/builder/generic_test.go @@ -3,14 +3,14 @@ package builder import ( "context" "encoding/json" - golog "log" + log "log" "testing" - cloudevents "github.com/cloudevents/sdk-go/v2" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + ce "github.com/cloudevents/sdk-go/v2" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/applicationtest" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/fake" @@ -21,9 +21,9 @@ func Test_Build(t *testing.T) { t.Parallel() // init the logger - logger, err := kymalogger.New("json", "debug") + logger, err := emlogger.New("json", "debug") if err != nil { - golog.Fatalf("Failed to initialize logger, error: %v", err) + log.Fatalf("Failed to initialize logger, error: %v", err) } testCases := []struct { @@ -100,9 +100,9 @@ func Test_Build(t *testing.T) { // given // build cloud event - builder := testingutils.NewCloudEventBuilder() + builder := epptestingutils.NewCloudEventBuilder() payload, _ := builder.BuildStructured() - newEvent := cloudevents.NewEvent() + newEvent := ce.NewEvent() err = json.Unmarshal([]byte(payload), &newEvent) require.NoError(t, err) newEvent.SetType(tc.givenType) @@ -143,9 +143,9 @@ func Test_GetAppNameOrSource(t *testing.T) { t.Parallel() // init the logger - logger, err := kymalogger.New("json", "debug") + logger, err := emlogger.New("json", "debug") if err != nil { - golog.Fatalf("Failed to initialize logger, error: %v", err) + log.Fatalf("Failed to initialize logger, error: %v", err) } testCases := []struct { diff --git a/pkg/cloudevents/builder/types.go b/pkg/cloudevents/builder/types.go index f18e652..e23c07d 100644 --- a/pkg/cloudevents/builder/types.go +++ b/pkg/cloudevents/builder/types.go @@ -1,7 +1,7 @@ package builder import ( - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" @@ -12,7 +12,7 @@ const ( ) type CloudEventBuilder interface { - Build(event cev2event.Event) (*cev2event.Event, error) + Build(event ceevent.Event) (*ceevent.Event, error) } type GenericBuilder struct { diff --git a/pkg/commander/nats/nats.go b/pkg/commander/nats/nats.go index bb6c827..95bd1f6 100644 --- a/pkg/commander/nats/nats.go +++ b/pkg/commander/nats/nats.go @@ -14,7 +14,7 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/informers" "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy" "github.com/kyma-project/eventing-publisher-proxy/pkg/metrics" - pkgnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" + eppnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" "github.com/kyma-project/eventing-publisher-proxy/pkg/options" "github.com/kyma-project/eventing-publisher-proxy/pkg/receiver" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender/jetstream" @@ -72,11 +72,11 @@ func (c *Commander) Start() error { messageReceiver := receiver.NewHTTPMessageReceiver(c.envCfg.Port) // connect to nats - connection, err := pkgnats.Connect(c.envCfg.URL, - pkgnats.WithRetryOnFailedConnect(c.envCfg.RetryOnFailedConnect), - pkgnats.WithMaxReconnects(c.envCfg.MaxReconnects), - pkgnats.WithReconnectWait(c.envCfg.ReconnectWait), - pkgnats.WithName("Kyma Publisher"), + connection, err := eppnats.Connect(c.envCfg.URL, + eppnats.WithRetryOnFailedConnect(c.envCfg.RetryOnFailedConnect), + eppnats.WithMaxReconnects(c.envCfg.MaxReconnects), + eppnats.WithReconnectWait(c.envCfg.ReconnectWait), + eppnats.WithName("Kyma Publisher"), ) if err != nil { return xerrors.Errorf("failed to connect to backend server for %s : %v", natsCommanderName, err) diff --git a/pkg/handler/handler.go b/pkg/handler/handler.go index 8eb7822..830a9d9 100644 --- a/pkg/handler/handler.go +++ b/pkg/handler/handler.go @@ -17,9 +17,9 @@ import ( "go.uber.org/zap" "github.com/cloudevents/sdk-go/v2/binding" - cev2client "github.com/cloudevents/sdk-go/v2/client" - cev2event "github.com/cloudevents/sdk-go/v2/event" - cev2http "github.com/cloudevents/sdk-go/v2/protocol/http" + ceclient "github.com/cloudevents/sdk-go/v2/client" + ceevent "github.com/cloudevents/sdk-go/v2/event" + cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" "github.com/kyma-project/eventing-publisher-proxy/pkg/cloudevents/builder" "github.com/kyma-project/eventing-publisher-proxy/pkg/cloudevents/eventtype" @@ -45,7 +45,7 @@ type Handler struct { Sender sender.GenericSender HealthChecker health.Checker // Defaulter sets default values to incoming events - Defaulter cev2client.EventDefaulter + Defaulter ceclient.EventDefaulter // LegacyTransformer handles transformations needed to handle legacy events LegacyTransformer legacy.RequestToCETransformer // RequestTimeout timeout for outgoing requests @@ -126,7 +126,7 @@ func (h *Handler) maxBytes(f http.HandlerFunc) http.HandlerFunc { // It writes to the user request if any error occurs. // Otherwise, returns the result. func (h *Handler) handleSendEventAndRecordMetricsLegacy( - writer http.ResponseWriter, request *http.Request, event *cev2event.Event) error { + writer http.ResponseWriter, request *http.Request, event *ceevent.Event) error { err := h.sendEventAndRecordMetrics(request.Context(), event, h.Sender.URL(), request.Header) if err != nil { h.namedLogger().Error(err) @@ -145,7 +145,7 @@ func (h *Handler) handleSendEventAndRecordMetricsLegacy( // It writes to the user request if any error occurs. // Otherwise, return the published event. func (h *Handler) handlePublishLegacyEvent(w http.ResponseWriter, r *http.Request, - data *api.PublishRequestData) (*cev2event.Event, error) { + data *api.PublishRequestData) (*ceevent.Event, error) { ceEvent, err := h.LegacyTransformer.TransformPublishRequestToCloudEvent(data) if err != nil { legacy.WriteJSONResponse(w, legacy.ErrorResponse(http.StatusInternalServerError, err)) @@ -172,7 +172,7 @@ func (h *Handler) handlePublishLegacyEvent(w http.ResponseWriter, r *http.Reques // It writes to the user request if any error occurs. // Otherwise, return the published event. func (h *Handler) handlePublishLegacyEventV1alpha1(w http.ResponseWriter, r *http.Request, - data *api.PublishRequestData) (*cev2event.Event, error) { + data *api.PublishRequestData) (*ceevent.Event, error) { event, _ := h.LegacyTransformer.WriteLegacyRequestsToCE(w, data) if event == nil { h.namedLogger().Error("Failed to transform legacy event to CloudEvent, event is nil") @@ -284,8 +284,8 @@ func (h *Handler) publishCloudEvents(w http.ResponseWriter, r *http.Request) { } // extractCloudEventFromRequest converts an incoming CloudEvent request to an Event. -func extractCloudEventFromRequest(r *http.Request) (*cev2event.Event, error) { - message := cev2http.NewMessageFromHttpRequest(r) +func extractCloudEventFromRequest(r *http.Request) (*ceevent.Event, error) { + message := cehttp.NewMessageFromHttpRequest(r) defer func() { _ = message.Finish(nil) }() event, err := binding.ToEvent(context.Background(), message) @@ -301,7 +301,7 @@ func extractCloudEventFromRequest(r *http.Request) (*cev2event.Event, error) { } // sendEventAndRecordMetrics dispatches an Event and records metrics based on dispatch success. -func (h *Handler) sendEventAndRecordMetrics(ctx context.Context, event *cev2event.Event, +func (h *Handler) sendEventAndRecordMetrics(ctx context.Context, event *ceevent.Event, host string, header http.Header) error { ctx, cancel := context.WithTimeout(ctx, h.RequestTimeout) defer cancel() @@ -349,7 +349,7 @@ func writeResponse(writer http.ResponseWriter, statusCode int, respBody []byte) } // applyDefaults applies the default values (if any) to the given Cloud Event. -func (h *Handler) applyDefaults(ctx context.Context, event *cev2event.Event) { +func (h *Handler) applyDefaults(ctx context.Context, event *ceevent.Event) { if h.Defaulter != nil { newEvent := h.Defaulter(ctx, *event) *event = newEvent diff --git a/pkg/handler/handler_test.go b/pkg/handler/handler_test.go index 49fbd32..32c4e80 100644 --- a/pkg/handler/handler_test.go +++ b/pkg/handler/handler_test.go @@ -18,7 +18,7 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/sender/jetstream" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - eclogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/stretchr/testify/assert" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/applicationtest" @@ -32,7 +32,7 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/metrics/metricstest" "github.com/kyma-project/eventing-publisher-proxy/pkg/options" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) func TestHandler_publishCloudEvents(t *testing.T) { @@ -185,7 +185,7 @@ func TestHandler_publishCloudEvents(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // given - logger, err := eclogger.New("text", "debug") + logger, err := emlogger.New("text", "debug") assert.NoError(t, err) app := applicationtest.NewApplication("appName1", nil) @@ -200,7 +200,7 @@ func TestHandler_publishCloudEvents(t *testing.T) { eventTypeCleaner: tt.fields.eventTypeCleaner, ceBuilder: ceBuilder, Options: &options.Options{}, - OldEventTypePrefix: testingutils.OldEventTypePrefix, + OldEventTypePrefix: epptestingutils.OldEventTypePrefix, } writer := httptest.NewRecorder() @@ -301,7 +301,7 @@ func TestHandler_publishLegacyEventsAsCE(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // given - logger, err := eclogger.New("text", "debug") + logger, err := emlogger.New("text", "debug") require.NoError(t, err) ceBuilder := builder.NewGenericBuilder("prefix", cleaner.NewJetStreamCleaner(logger), appLister, logger) diff --git a/pkg/handler/handler_v1alpha1_test.go b/pkg/handler/handler_v1alpha1_test.go index 8d92b8e..bed8c53 100644 --- a/pkg/handler/handler_v1alpha1_test.go +++ b/pkg/handler/handler_v1alpha1_test.go @@ -16,10 +16,10 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/cloudevents/builder" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender/common" - cloudevents "github.com/cloudevents/sdk-go/v2" + ce "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/client" - cev2event "github.com/cloudevents/sdk-go/v2/event" - eclogger "github.com/kyma-project/eventing-manager/pkg/logger" + ceevent "github.com/cloudevents/sdk-go/v2/event" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/stretchr/testify/assert" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" @@ -32,7 +32,7 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/metrics/metricstest" "github.com/kyma-project/eventing-publisher-proxy/pkg/options" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) func Test_extractCloudEventFromRequest(t *testing.T) { @@ -40,7 +40,7 @@ func Test_extractCloudEventFromRequest(t *testing.T) { request *http.Request } type wants struct { - event *cev2event.Event + event *ceevent.Event errorAssertionFunc assert.ErrorAssertionFunc } tests := []struct { @@ -54,7 +54,7 @@ func Test_extractCloudEventFromRequest(t *testing.T) { args: args{ request: CreateValidStructuredRequestV1Alpha1(t), }, - wantType: fmt.Sprintf("sap.kyma.custom.%s", testingutils.CloudEventType), + wantType: fmt.Sprintf("sap.kyma.custom.%s", epptestingutils.CloudEventType), wants: wants{ event: CreateCloudEvent(t), errorAssertionFunc: assert.NoError, @@ -85,7 +85,7 @@ func Test_extractCloudEventFromRequest(t *testing.T) { args: args{ request: CreateValidBinaryRequestV1Alpha1(t), }, - wantType: fmt.Sprintf("sap.kyma.custom.%s", testingutils.CloudEventType), + wantType: fmt.Sprintf("sap.kyma.custom.%s", epptestingutils.CloudEventType), wants: wants{ event: CreateCloudEvent(t), errorAssertionFunc: assert.NoError, @@ -298,7 +298,7 @@ func TestHandler_publishCloudEvents_v1alpha1(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // given - logger, err := eclogger.New("text", "debug") + logger, err := emlogger.New("text", "debug") assert.NoError(t, err) h := &Handler{ @@ -389,7 +389,7 @@ func TestHandler_sendEventAndRecordMetrics(t *testing.T) { type args struct { ctx context.Context host string - event *cev2event.Event + event *ceevent.Event header http.Header } type wants struct { @@ -428,7 +428,7 @@ func TestHandler_sendEventAndRecordMetrics(t *testing.T) { ceEvent := CreateCloudEvent(t) ceEventWithOriginalEventType := ceEvent.Clone() - ceEventWithOriginalEventType.SetExtension(builder.OriginalTypeHeaderName, testingutils.CloudEventNameAndVersion) + ceEventWithOriginalEventType.SetExtension(builder.OriginalTypeHeaderName, epptestingutils.CloudEventNameAndVersion) tests := []struct { name string @@ -507,7 +507,7 @@ func TestHandler_sendEventAndRecordMetrics(t *testing.T) { args: args{ ctx: context.Background(), host: "foo", - event: &cev2event.Event{}, + event: &ceevent.Event{}, }, wants: wants{ result: nil, @@ -523,7 +523,7 @@ func TestHandler_sendEventAndRecordMetrics(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // given - logger, _ := eclogger.New("text", "debug") + logger, _ := emlogger.New("text", "debug") h := &Handler{ Sender: tt.fields.Sender, Defaulter: tt.fields.Defaulter, @@ -557,7 +557,7 @@ func TestHandler_sendEventAndRecordMetrics_TracingAndDefaults(t *testing.T) { latency := new(mocks.BucketsProvider) latency.On(bucketsFunc).Return(nil) latency.Test(t) - logger, _ := eclogger.New("text", "debug") + logger, _ := emlogger.New("text", "debug") h := &Handler{ Sender: stub, Defaulter: nil, @@ -586,15 +586,15 @@ func TestHandler_sendEventAndRecordMetrics_TracingAndDefaults(t *testing.T) { assert.Equal(t, expectedExtensions, stub.ReceivedEvent.Context.GetExtensions()) } -func CreateCloudEvent(t *testing.T) *cev2event.Event { - builder := testingutils.NewCloudEventBuilder( - testingutils.WithCloudEventType(testingutils.CloudEventTypeWithPrefix), +func CreateCloudEvent(t *testing.T) *ceevent.Event { + builder := epptestingutils.NewCloudEventBuilder( + epptestingutils.WithCloudEventType(epptestingutils.CloudEventTypeWithPrefix), ) payload, _ := builder.BuildStructured() - newEvent := cloudevents.NewEvent() + newEvent := ce.NewEvent() err := json.Unmarshal([]byte(payload), &newEvent) assert.NoError(t, err) - newEvent.SetType(testingutils.CloudEventTypeWithPrefix) + newEvent.SetType(epptestingutils.CloudEventTypeWithPrefix) err = newEvent.SetData("", map[string]any{"foo": "bar"}) assert.NoError(t, err) @@ -669,11 +669,11 @@ func CreateInvalidBinaryRequestV1Alpha1(t *testing.T) *http.Request { type GenericSenderStub struct { SleepDuration time.Duration Err sender.PublishError - ReceivedEvent *cev2event.Event + ReceivedEvent *ceevent.Event BackendURL string } -func (g *GenericSenderStub) Send(_ context.Context, event *cev2event.Event) sender.PublishError { +func (g *GenericSenderStub) Send(_ context.Context, event *ceevent.Event) sender.PublishError { g.ReceivedEvent = event time.Sleep(g.SleepDuration) return g.Err diff --git a/pkg/legacy/helpers.go b/pkg/legacy/helpers.go index a9e414c..f9a686b 100644 --- a/pkg/legacy/helpers.go +++ b/pkg/legacy/helpers.go @@ -6,7 +6,7 @@ import ( "net/http" "strings" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-publisher-proxy/internal" "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/api" @@ -59,7 +59,7 @@ func WriteJSONResponse(w http.ResponseWriter, resp *api.PublishEventResponses) { } // init the contexted logger - logger, _ := kymalogger.New("json", "error") + logger, _ := emlogger.New("json", "error") namedLogger := logger.WithContext().Named(legacyEventsName) namedLogger.Error("Received an empty response") diff --git a/pkg/legacy/legacy.go b/pkg/legacy/legacy.go index fd73186..f77c745 100644 --- a/pkg/legacy/legacy.go +++ b/pkg/legacy/legacy.go @@ -8,13 +8,13 @@ import ( "strings" "time" - cev2 "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/google/uuid" "github.com/pkg/errors" "github.com/kyma-project/eventing-publisher-proxy/internal" "github.com/kyma-project/eventing-publisher-proxy/pkg/application" - apiv1 "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/api" + eppapi "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/api" ) var ( @@ -28,10 +28,10 @@ const ( ) type RequestToCETransformer interface { - ExtractPublishRequestData(*http.Request) (*apiv1.PublishRequestData, *apiv1.PublishEventResponses, error) - TransformPublishRequestToCloudEvent(*apiv1.PublishRequestData) (*cev2.Event, error) - WriteLegacyRequestsToCE(http.ResponseWriter, *apiv1.PublishRequestData) (*cev2.Event, string) - WriteCEResponseAsLegacyResponse(http.ResponseWriter, int, *cev2.Event, string) + ExtractPublishRequestData(*http.Request) (*eppapi.PublishRequestData, *eppapi.PublishEventResponses, error) + TransformPublishRequestToCloudEvent(*eppapi.PublishRequestData) (*ceevent.Event, error) + WriteLegacyRequestsToCE(http.ResponseWriter, *eppapi.PublishRequestData) (*ceevent.Event, string) + WriteCEResponseAsLegacyResponse(http.ResponseWriter, int, *ceevent.Event, string) } type Transformer struct { @@ -53,7 +53,7 @@ func (t *Transformer) isApplicationListerEnabled() bool { } // CheckParameters validates the parameters in the request and sends error responses if found invalid. -func (t *Transformer) checkParameters(parameters *apiv1.PublishEventParametersV1) *apiv1.PublishEventResponses { +func (t *Transformer) checkParameters(parameters *eppapi.PublishEventParametersV1) *eppapi.PublishEventResponses { if parameters == nil { return ErrorResponseBadRequest(ErrorMessageBadPayload) } @@ -82,22 +82,22 @@ func (t *Transformer) checkParameters(parameters *apiv1.PublishEventParametersV1 return ErrorResponseMissingFieldData() } // OK - return &apiv1.PublishEventResponses{} + return &eppapi.PublishEventResponses{} } // ExtractPublishRequestData extracts the data for publishing event from the given legacy event request. -func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*apiv1.PublishRequestData, - *apiv1.PublishEventResponses, error) { +func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*eppapi.PublishRequestData, + *eppapi.PublishEventResponses, error) { // parse request body to PublishRequestV1 if request.Body == nil || request.ContentLength == 0 { resp := ErrorResponseBadRequest(ErrorMessageBadPayload) return nil, resp, errors.New(resp.Error.Message) } - parameters := &apiv1.PublishEventParametersV1{} + parameters := &eppapi.PublishEventParametersV1{} decoder := json.NewDecoder(request.Body) if err := decoder.Decode(¶meters.PublishrequestV1); err != nil { - var resp *apiv1.PublishEventResponses + var resp *eppapi.PublishEventResponses if err.Error() == requestBodyTooLargeErrorMessage { resp = ErrorResponseRequestBodyTooLarge(err.Error()) } else { @@ -113,7 +113,7 @@ func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*apiv1.P } appName := ParseApplicationNameFromPath(request.URL.Path) - publishRequestData := &apiv1.PublishRequestData{ + publishRequestData := &eppapi.PublishRequestData{ PublishEventParameters: parameters, ApplicationName: appName, URLPath: request.URL.Path, @@ -126,7 +126,7 @@ func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*apiv1.P // WriteLegacyRequestsToCE transforms the legacy event to cloudevent from the given request. // It also returns the original event-type without cleanup as the second return type. func (t *Transformer) WriteLegacyRequestsToCE(writer http.ResponseWriter, - publishData *apiv1.PublishRequestData) (*cev2.Event, string) { + publishData *eppapi.PublishRequestData) (*ceevent.Event, string) { uncleanedAppName := publishData.ApplicationName // clean the application name form non-alphanumeric characters @@ -156,11 +156,11 @@ func (t *Transformer) WriteLegacyRequestsToCE(writer http.ResponseWriter, } func (t *Transformer) WriteCEResponseAsLegacyResponse(writer http.ResponseWriter, statusCode int, - event *cev2.Event, msg string) { - response := &apiv1.PublishEventResponses{} + event *ceevent.Event, msg string) { + response := &eppapi.PublishEventResponses{} // Fail if !is2XXStatusCode(statusCode) { - response.Error = &apiv1.Error{ + response.Error = &eppapi.Error{ Status: statusCode, Message: msg, } @@ -169,18 +169,18 @@ func (t *Transformer) WriteCEResponseAsLegacyResponse(writer http.ResponseWriter } // Success - response.Ok = &apiv1.PublishResponse{EventID: event.ID()} + response.Ok = &eppapi.PublishResponse{EventID: event.ID()} WriteJSONResponse(writer, response) } // TransformPublishRequestToCloudEvent converts the given publish request to a CloudEvent with raw values. -func (t *Transformer) TransformPublishRequestToCloudEvent(publishRequestData *apiv1.PublishRequestData) (*cev2.Event, +func (t *Transformer) TransformPublishRequestToCloudEvent(publishRequestData *eppapi.PublishRequestData) (*ceevent.Event, error) { source := publishRequestData.ApplicationName publishRequest := publishRequestData.PublishEventParameters // instantiate a new cloudEvent object - event := cev2.New(cev2.CloudEventsVersionV1) + event := ceevent.New(ceevent.CloudEventsVersionV1) eventName := publishRequest.PublishrequestV1.EventType eventTypeVersion := publishRequest.PublishrequestV1.EventTypeVersion @@ -215,12 +215,12 @@ func (t *Transformer) TransformPublishRequestToCloudEvent(publishRequestData *ap // convertPublishRequestToCloudEvent converts the given publish request to a CloudEvent. func (t *Transformer) convertPublishRequestToCloudEvent(appName string, - publishRequest *apiv1.PublishEventParametersV1) (*cev2.Event, error) { + publishRequest *eppapi.PublishEventParametersV1) (*ceevent.Event, error) { if !application.IsCleanName(appName) { return nil, errors.New("application name should be cleaned from none-alphanumeric characters") } - event := cev2.New(cev2.CloudEventsVersionV1) + event := ceevent.New(ceevent.CloudEventsVersionV1) evTime, err := time.Parse(time.RFC3339, publishRequest.PublishrequestV1.EventTime) if err != nil { diff --git a/pkg/legacy/legacy_test.go b/pkg/legacy/legacy_test.go index dd1c887..74a6004 100644 --- a/pkg/legacy/legacy_test.go +++ b/pkg/legacy/legacy_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -17,9 +17,9 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/application" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/applicationtest" "github.com/kyma-project/eventing-publisher-proxy/pkg/application/fake" - legacyapi "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/api" + eppapi "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/api" "github.com/kyma-project/eventing-publisher-proxy/pkg/legacy/legacytest" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) const ( @@ -156,22 +156,22 @@ func applicationTypeLabel(label string) map[string]string { } func TestConvertPublishRequestToCloudEvent(t *testing.T) { - givenEventID := testingutils.EventID - givenApplicationName := testingutils.ApplicationName - givenEventTypePrefix := testingutils.Prefix + givenEventID := epptestingutils.EventID + givenApplicationName := epptestingutils.ApplicationName + givenEventTypePrefix := epptestingutils.Prefix givenTimeNow := time.Now().Format(time.RFC3339) - givenLegacyEventVersion := testingutils.EventVersion - givenPublishReqParams := &legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + givenLegacyEventVersion := epptestingutils.EventVersion + givenPublishReqParams := &eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventID: givenEventID, EventType: eventTypeMultiSegment, EventTime: givenTimeNow, EventTypeVersion: givenLegacyEventVersion, - Data: testingutils.EventData, + Data: epptestingutils.EventData, }, } - wantEventMeshNamespace := testingutils.MessagingNamespace + wantEventMeshNamespace := epptestingutils.MessagingNamespace wantEventID := givenEventID wantEventType := formatEventType(givenEventTypePrefix, givenApplicationName, eventTypeMultiSegmentCombined, givenLegacyEventVersion) @@ -202,8 +202,8 @@ func TestCombineEventTypeSegments(t *testing.T) { }{ { name: "event-type with two segments", - givenEventType: testingutils.EventName, - wantEventType: testingutils.EventName, + givenEventType: epptestingutils.EventName, + wantEventType: epptestingutils.EventName, }, { name: "event-type with more than two segments", @@ -273,8 +273,8 @@ func TestExtractPublishRequestData(t *testing.T) { testCases := []struct { name string givenLegacyRequestFunc func() (*http.Request, error) - wantPublishRequestData *legacyapi.PublishRequestData - wantErrorResponse *legacyapi.PublishEventResponses + wantPublishRequestData *eppapi.PublishRequestData + wantErrorResponse *eppapi.PublishEventResponses }{ { name: "should fail if request body is empty", @@ -295,9 +295,9 @@ func TestExtractPublishRequestData(t *testing.T) { givenLegacyRequestFunc: func() (*http.Request, error) { return legacytest.ValidLegacyRequest(givenVersion, givenApplication, givenEventName) }, - wantPublishRequestData: &legacyapi.PublishRequestData{ - PublishEventParameters: &legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + wantPublishRequestData: &eppapi.PublishRequestData{ + PublishEventParameters: &eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventType: "object.do", EventTypeVersion: "v1", EventTime: "2020-04-02T21:37:00Z", @@ -313,9 +313,9 @@ func TestExtractPublishRequestData(t *testing.T) { givenLegacyRequestFunc: func() (*http.Request, error) { return legacytest.ValidLegacyRequest(givenVersion, "no-app", givenEventName) }, - wantPublishRequestData: &legacyapi.PublishRequestData{ - PublishEventParameters: &legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + wantPublishRequestData: &eppapi.PublishRequestData{ + PublishEventParameters: &eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventType: "object.do", EventTypeVersion: "v1", EventTime: "2020-04-02T21:37:00Z", @@ -368,9 +368,9 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { testCases := []struct { name string - givenPublishEventParameters legacyapi.PublishEventParametersV1 - wantCloudEventFunc func() (cev2event.Event, error) - wantErrorResponse legacyapi.PublishEventResponses + givenPublishEventParameters eppapi.PublishEventParametersV1 + wantCloudEventFunc func() (ceevent.Event, error) + wantErrorResponse eppapi.PublishEventResponses wantError bool wantEventType string wantSource string @@ -379,9 +379,9 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { }{ { name: "should succeed if publish data is valid", - givenPublishEventParameters: legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ - EventID: testingutils.EventID, + givenPublishEventParameters: eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ + EventID: epptestingutils.EventID, EventType: givenEventName, EventTypeVersion: givenVersion, EventTime: "2020-04-02T21:37:00Z", @@ -389,15 +389,15 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { }, }, wantError: false, - wantEventID: testingutils.EventID, + wantEventID: epptestingutils.EventID, wantEventType: "object.do.v1", wantSource: givenApplication, wantData: `{"key":"value"}`, }, { name: "should set new event ID when not provided", - givenPublishEventParameters: legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + givenPublishEventParameters: eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventType: givenEventName, EventTypeVersion: givenVersion, EventTime: "2020-04-02T21:37:00Z", @@ -411,8 +411,8 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { }, { name: "should fail if event time is invalid", - givenPublishEventParameters: legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + givenPublishEventParameters: eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventType: givenEventName, EventTypeVersion: givenVersion, EventTime: "20dsadsa20-04-02T21:37:00Z", @@ -423,8 +423,8 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { }, { name: "should fail if event data is not json", - givenPublishEventParameters: legacyapi.PublishEventParametersV1{ - PublishrequestV1: legacyapi.PublishRequestV1{ + givenPublishEventParameters: eppapi.PublishEventParametersV1{ + PublishrequestV1: eppapi.PublishRequestV1{ EventType: givenEventName, EventTypeVersion: givenVersion, EventTime: "20dsadsa20-04-02T21:37:00Z", @@ -441,7 +441,7 @@ func TestTransformPublishRequestToCloudEvent(t *testing.T) { t.Parallel() // given - givenPublishRequestData := legacyapi.PublishRequestData{ + givenPublishRequestData := eppapi.PublishRequestData{ PublishEventParameters: &tc.givenPublishEventParameters, ApplicationName: givenApplication, } diff --git a/pkg/nats/connect_test.go b/pkg/nats/connect_test.go index 8e4617c..baff9ac 100644 --- a/pkg/nats/connect_test.go +++ b/pkg/nats/connect_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" - pkgnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" - publishertesting "github.com/kyma-project/eventing-publisher-proxy/testing" + eppnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) func TestConnect(t *testing.T) { @@ -37,7 +37,7 @@ func TestConnect(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { // given - natsServer := publishertesting.StartNATSServer() + natsServer := epptestingutils.StartNATSServer() assert.NotNil(t, natsServer) defer natsServer.Shutdown() @@ -45,10 +45,10 @@ func TestConnect(t *testing.T) { assert.NotEmpty(t, clientURL) // when - connection, err := pkgnats.Connect(clientURL, - pkgnats.WithRetryOnFailedConnect(tc.givenRetryOnFailedConnect), - pkgnats.WithMaxReconnects(tc.givenMaxReconnect), - pkgnats.WithReconnectWait(tc.givenReconnectWait), + connection, err := eppnats.Connect(clientURL, + eppnats.WithRetryOnFailedConnect(tc.givenRetryOnFailedConnect), + eppnats.WithMaxReconnects(tc.givenMaxReconnect), + eppnats.WithReconnectWait(tc.givenReconnectWait), ) assert.Nil(t, err) assert.NotNil(t, connection) diff --git a/pkg/oauth/client_test.go b/pkg/oauth/client_test.go index e3eb9f3..2b38e63 100644 --- a/pkg/oauth/client_test.go +++ b/pkg/oauth/client_test.go @@ -11,7 +11,7 @@ import ( "golang.org/x/oauth2" "github.com/kyma-project/eventing-publisher-proxy/pkg/env" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) func TestNewClient(t *testing.T) { @@ -88,13 +88,13 @@ func TestGetToken(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - mockServer := testingutils.NewMockServer(testingutils.WithExpiresIn(test.givenExpiresInSec)) + mockServer := epptestingutils.NewMockServer(epptestingutils.WithExpiresIn(test.givenExpiresInSec)) mockServer.Start(t, tokenEndpoint, eventsEndpoint, eventsHTTP400Endpoint) defer mockServer.Close() emsCEURL := fmt.Sprintf("%s%s", mockServer.URL(), eventsEndpoint) authURL := fmt.Sprintf("%s%s", mockServer.URL(), tokenEndpoint) - cfg := testingutils.NewEnvConfig(emsCEURL, authURL) + cfg := epptestingutils.NewEnvConfig(emsCEURL, authURL) client := NewClient(context.Background(), cfg) defer client.CloseIdleConnections() diff --git a/pkg/receiver/receiver.go b/pkg/receiver/receiver.go index f1ddd70..6f15e9d 100644 --- a/pkg/receiver/receiver.go +++ b/pkg/receiver/receiver.go @@ -9,7 +9,7 @@ import ( "go.opencensus.io/plugin/ochttp" - kymalogger "github.com/kyma-project/eventing-manager/pkg/logger" + emlogger "github.com/kyma-project/eventing-manager/pkg/logger" ) const ( @@ -35,7 +35,7 @@ func NewHTTPMessageReceiver(port int) *HTTPMessageReceiver { } // StartListen starts the HTTP message receiver and blocks until it receives a shutdown signal. -func (r *HTTPMessageReceiver) StartListen(ctx context.Context, handler http.Handler, logger *kymalogger.Logger) error { +func (r *HTTPMessageReceiver) StartListen(ctx context.Context, handler http.Handler, logger *emlogger.Logger) error { var err error if r.listener, err = net.Listen("tcp", fmt.Sprintf("%v:%d", r.Host, r.Port)); err != nil { return err diff --git a/pkg/receiver/receiver_test.go b/pkg/receiver/receiver_test.go index 8e1ddc5..2fefdaf 100644 --- a/pkg/receiver/receiver_test.go +++ b/pkg/receiver/receiver_test.go @@ -9,7 +9,7 @@ import ( "github.com/kyma-project/eventing-manager/pkg/logger" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) // a mocked http.Handler. @@ -20,7 +20,7 @@ func (h *testHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} var _ http.Handler = (*testHandler)(nil) func TestNewHttpMessageReceiver(t *testing.T) { - port := testingutils.GeneratePortOrDie() + port := epptestingutils.GeneratePortOrDie() r := NewHTTPMessageReceiver(port) if r.Port != port { t.Errorf("Port should be: %d is: %d", port, r.Port) diff --git a/pkg/sender/eventmesh/eventmesh.go b/pkg/sender/eventmesh/eventmesh.go index 9fe56e7..2353419 100644 --- a/pkg/sender/eventmesh/eventmesh.go +++ b/pkg/sender/eventmesh/eventmesh.go @@ -6,7 +6,7 @@ import ( "net/http" "github.com/cloudevents/sdk-go/v2/binding" - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/kyma-project/eventing-manager/pkg/logger" "go.uber.org/zap" @@ -50,7 +50,7 @@ func (s *Sender) Checker() *health.ConfigurableChecker { return &health.ConfigurableChecker{} } -func (s *Sender) Send(ctx context.Context, event *cev2event.Event) sender.PublishError { +func (s *Sender) Send(ctx context.Context, event *ceevent.Event) sender.PublishError { request, err := s.NewRequestWithTarget(ctx, s.Target) if err != nil { e := common.ErrInternalBackendError diff --git a/pkg/sender/eventmesh/eventmesh_test.go b/pkg/sender/eventmesh/eventmesh_test.go index 068a87a..3debacf 100644 --- a/pkg/sender/eventmesh/eventmesh_test.go +++ b/pkg/sender/eventmesh/eventmesh_test.go @@ -16,7 +16,7 @@ import ( "github.com/kyma-project/eventing-publisher-proxy/pkg/oauth" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender" "github.com/kyma-project/eventing-publisher-proxy/pkg/sender/common" - testing2 "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) const ( @@ -97,7 +97,7 @@ func TestSender_Send_Error(t *testing.T) { type args struct { // timeout is one easy way to trigger an error on sending timeout time.Duration - builder *testing2.CloudEventBuilder + builder *epptestingutils.CloudEventBuilder } var tests = []struct { name string @@ -113,7 +113,7 @@ func TestSender_Send_Error(t *testing.T) { }, args: args{ timeout: 1 * time.Millisecond, - builder: testing2.NewCloudEventBuilder(), + builder: epptestingutils.NewCloudEventBuilder(), }, want: nil, wantErr: true, @@ -146,7 +146,7 @@ func TestSender_Send(t *testing.T) { } type args struct { ctx context.Context - builder *testing2.CloudEventBuilder + builder *epptestingutils.CloudEventBuilder } var tests = []struct { name string @@ -162,7 +162,7 @@ func TestSender_Send(t *testing.T) { }, args: args{ ctx: context.Background(), - builder: testing2.NewCloudEventBuilder(), + builder: epptestingutils.NewCloudEventBuilder(), }, wantErr: common.BackendPublishError{ HTTPCode: 400, @@ -175,7 +175,7 @@ func TestSender_Send(t *testing.T) { }, args: args{ ctx: context.Background(), - builder: testing2.NewCloudEventBuilder(), + builder: epptestingutils.NewCloudEventBuilder(), }, wantErr: nil, }, diff --git a/pkg/sender/jetstream/jetstream_test.go b/pkg/sender/jetstream/jetstream_test.go index a6f608c..c50dc4e 100644 --- a/pkg/sender/jetstream/jetstream_test.go +++ b/pkg/sender/jetstream/jetstream_test.go @@ -17,12 +17,12 @@ import ( "github.com/cloudevents/sdk-go/v2/event" - cloudevents "github.com/cloudevents/sdk-go/v2" + ce "github.com/cloudevents/sdk-go/v2" "github.com/nats-io/nats-server/v2/server" "github.com/stretchr/testify/assert" "github.com/kyma-project/eventing-publisher-proxy/pkg/env" - testingutils "github.com/kyma-project/eventing-publisher-proxy/testing" + epptestingutils "github.com/kyma-project/eventing-publisher-proxy/testing" ) func TestJetStreamMessageSender(t *testing.T) { @@ -113,10 +113,10 @@ type TestEnvironment struct { // setupTestEnvironment sets up the resources and mocks required for testing. func setupTestEnvironment(t *testing.T) *TestEnvironment { - natsServer := testingutils.StartNATSServer() + natsServer := epptestingutils.StartNATSServer() require.NotNil(t, natsServer) - connection, err := testingutils.ConnectToNATSServer(natsServer.ClientURL()) + connection, err := epptestingutils.ConnectToNATSServer(natsServer.ClientURL()) require.NotNil(t, connection) require.NoError(t, err) @@ -146,12 +146,12 @@ func setupTestEnvironment(t *testing.T) *TestEnvironment { // createCloudEvent build a cloud event. func createCloudEvent(t *testing.T) *event.Event { - jsType := fmt.Sprintf("%s.%s", testingutils.StreamName, testingutils.CloudEventTypeWithPrefix) - builder := testingutils.NewCloudEventBuilder( - testingutils.WithCloudEventType(jsType), + jsType := fmt.Sprintf("%s.%s", epptestingutils.StreamName, epptestingutils.CloudEventTypeWithPrefix) + builder := epptestingutils.NewCloudEventBuilder( + epptestingutils.WithCloudEventType(jsType), ) payload, _ := builder.BuildStructured() - newEvent := cloudevents.NewEvent() + newEvent := ce.NewEvent() newEvent.SetType(jsType) err := json.Unmarshal([]byte(payload), &newEvent) assert.NoError(t, err) @@ -162,7 +162,7 @@ func createCloudEvent(t *testing.T) *event.Event { // getStreamConfig inits a testing stream config. func getStreamConfig(maxBytes int64) *natsgo.StreamConfig { return &natsgo.StreamConfig{ - Name: testingutils.StreamName, + Name: epptestingutils.StreamName, Subjects: []string{fmt.Sprintf("%s.>", env.JetStreamSubjectPrefix)}, Storage: natsgo.MemoryStorage, Retention: natsgo.InterestPolicy, @@ -176,7 +176,7 @@ func getConsumerConfig() *natsgo.ConsumerConfig { Durable: "test", DeliverPolicy: natsgo.DeliverAllPolicy, AckPolicy: natsgo.AckExplicitPolicy, - FilterSubject: fmt.Sprintf("%v.%v", env.JetStreamSubjectPrefix, testingutils.CloudEventTypeWithPrefix), + FilterSubject: fmt.Sprintf("%v.%v", env.JetStreamSubjectPrefix, epptestingutils.CloudEventTypeWithPrefix), } } @@ -199,10 +199,10 @@ func addConsumer(t *testing.T, connection *natsgo.Conn, sc *natsgo.StreamConfig, func CreateNATSJsConfig(url string) *env.NATSConfig { return &env.NATSConfig{ - JSStreamName: testingutils.StreamName, + JSStreamName: epptestingutils.StreamName, URL: url, ReconnectWait: time.Second, - EventTypePrefix: testingutils.OldEventTypePrefix, + EventTypePrefix: epptestingutils.OldEventTypePrefix, } } diff --git a/pkg/subscribed/helpers.go b/pkg/subscribed/helpers.go index c8b5f1e..3067283 100644 --- a/pkg/subscribed/helpers.go +++ b/pkg/subscribed/helpers.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - v1 "k8s.io/api/core/v1" + emeventingv2alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + kcorev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -13,31 +13,31 @@ import ( "k8s.io/client-go/dynamic/dynamicinformer" "k8s.io/client-go/rest" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + emeventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" "github.com/kyma-project/eventing-publisher-proxy/pkg/informers" ) func SubscriptionGVR() schema.GroupVersionResource { return schema.GroupVersionResource{ - Version: eventingv1alpha2.GroupVersion.Version, - Group: eventingv1alpha2.GroupVersion.Group, + Version: emeventingv2alpha1.GroupVersion.Version, + Group: emeventingv2alpha1.GroupVersion.Group, Resource: "subscriptions", } } func SubscriptionV1alpha1GVR() schema.GroupVersionResource { return schema.GroupVersionResource{ - Version: eventingv1alpha1.GroupVersion.Version, - Group: eventingv1alpha1.GroupVersion.Group, + Version: emeventingv1alpha1.GroupVersion.Version, + Group: emeventingv1alpha1.GroupVersion.Group, Resource: "subscriptions", } } // ConvertRuntimeObjToSubscriptionV1alpha1 converts a runtime.Object to a v1alpha1 version of Subscription object // by converting to unstructured in between. -func ConvertRuntimeObjToSubscriptionV1alpha1(sObj runtime.Object) (*eventingv1alpha1.Subscription, error) { - sub := &eventingv1alpha1.Subscription{} +func ConvertRuntimeObjToSubscriptionV1alpha1(sObj runtime.Object) (*emeventingv1alpha1.Subscription, error) { + sub := &emeventingv1alpha1.Subscription{} if subUnstructured, ok := sObj.(*unstructured.Unstructured); ok { err := runtime.DefaultUnstructuredConverter.FromUnstructured(subUnstructured.Object, sub) if err != nil { @@ -49,8 +49,8 @@ func ConvertRuntimeObjToSubscriptionV1alpha1(sObj runtime.Object) (*eventingv1al // ConvertRuntimeObjToSubscription converts a runtime.Object to a Subscription object // by converting to unstructured in between. -func ConvertRuntimeObjToSubscription(sObj runtime.Object) (*eventingv1alpha2.Subscription, error) { - sub := &eventingv1alpha2.Subscription{} +func ConvertRuntimeObjToSubscription(sObj runtime.Object) (*emeventingv2alpha1.Subscription, error) { + sub := &emeventingv2alpha1.Subscription{} if subUnstructured, ok := sObj.(*unstructured.Unstructured); ok { err := runtime.DefaultUnstructuredConverter.FromUnstructured(subUnstructured.Object, sub) if err != nil { @@ -65,7 +65,7 @@ func GenerateSubscriptionInfFactory(k8sConfig *rest.Config) dynamicinformer.Dyna subDynamicClient := dynamic.NewForConfigOrDie(k8sConfig) dFilteredSharedInfFactory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(subDynamicClient, informers.DefaultResyncPeriod, - v1.NamespaceAll, + kcorev1.NamespaceAll, nil, ) dFilteredSharedInfFactory.ForResource(SubscriptionGVR()) @@ -97,12 +97,12 @@ func AddUniqueEventsToResult(eventsSubSet []Event, uniqEvents map[Event]bool) ma // FilterEventTypeVersions returns a slice of Events: // if the event source matches the appName for typeMatching standard // if the . is present in the eventType for typeMatching exact. -func FilterEventTypeVersions(eventTypePrefix, appName string, subscription *eventingv1alpha2.Subscription) []Event { +func FilterEventTypeVersions(eventTypePrefix, appName string, subscription *emeventingv2alpha1.Subscription) []Event { events := make([]Event, 0) prefixAndAppName := fmt.Sprintf("%s.%s.", eventTypePrefix, appName) for _, eventType := range subscription.Spec.Types { - if subscription.Spec.TypeMatching == eventingv1alpha2.TypeMatchingExact { + if subscription.Spec.TypeMatching == emeventingv2alpha1.TypeMatchingExact { // in case of type matching exact, we have app name as a part of event type if strings.HasPrefix(eventType, prefixAndAppName) { eventTypeVersion := strings.ReplaceAll(eventType, prefixAndAppName, "") @@ -136,7 +136,7 @@ func buildEvent(eventTypeAndVersion string) Event { // E.g. sap.kyma.custom.varkes.order.created.v0 // 2. if the eventSource matches BEBNamespace name. func FilterEventTypeVersionsV1alpha1(eventTypePrefix, bebNs, appName string, - filters *eventingv1alpha1.BEBFilters) []Event { + filters *emeventingv1alpha1.BEBFilters) []Event { events := make([]Event, 0) if filters == nil { return events diff --git a/pkg/subscribed/helpers_test.go b/pkg/subscribed/helpers_test.go index bdf1a61..c9ea97e 100644 --- a/pkg/subscribed/helpers_test.go +++ b/pkg/subscribed/helpers_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + emeventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + emeventingv2alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) func TestFilterEventTypeVersions(t *testing.T) { @@ -13,19 +13,19 @@ func TestFilterEventTypeVersions(t *testing.T) { testCases := []struct { name string appName string - subscription *eventingv1alpha2.Subscription + subscription *emeventingv2alpha1.Subscription expectedEvents []Event }{ { name: "should return no events when there is no subscription", appName: "fooapp", - subscription: &eventingv1alpha2.Subscription{}, + subscription: &emeventingv2alpha1.Subscription{}, expectedEvents: make([]Event, 0), }, { name: "should return a slice of events when eventTypes are provided", appName: "foovarkes", - subscription: &eventingv1alpha2.Subscription{ - Spec: eventingv1alpha2.SubscriptionSpec{ + subscription: &emeventingv2alpha1.Subscription{ + Spec: emeventingv2alpha1.SubscriptionSpec{ Source: "foovarkes", Types: []string{ "order.created.v1", @@ -40,8 +40,8 @@ func TestFilterEventTypeVersions(t *testing.T) { }, { name: "should return no event if app name is different than subscription source", appName: "foovarkes", - subscription: &eventingv1alpha2.Subscription{ - Spec: eventingv1alpha2.SubscriptionSpec{ + subscription: &emeventingv2alpha1.Subscription{ + Spec: emeventingv2alpha1.SubscriptionSpec{ Source: "diff-source", Types: []string{ "order.created.v1", @@ -53,10 +53,10 @@ func TestFilterEventTypeVersions(t *testing.T) { }, { name: "should return event types if event type consists of eventType and appName for typeMaching exact", appName: "foovarkes", - subscription: &eventingv1alpha2.Subscription{ - Spec: eventingv1alpha2.SubscriptionSpec{ + subscription: &emeventingv2alpha1.Subscription{ + Spec: emeventingv2alpha1.SubscriptionSpec{ Source: "/default/sap.kyma/tunas-develop", - TypeMatching: eventingv1alpha2.TypeMatchingExact, + TypeMatching: emeventingv2alpha1.TypeMatchingExact, Types: []string{ "sap.kyma.custom.foovarkes.order.created.v1", "sap.kyma.custom.foovarkes.order.created.v2", @@ -70,10 +70,10 @@ func TestFilterEventTypeVersions(t *testing.T) { }, { name: "should return no event if app name is not part of external event types", appName: "foovarkes", - subscription: &eventingv1alpha2.Subscription{ - Spec: eventingv1alpha2.SubscriptionSpec{ + subscription: &emeventingv2alpha1.Subscription{ + Spec: emeventingv2alpha1.SubscriptionSpec{ Source: "/default/sap.kyma/tunas-develop", - TypeMatching: eventingv1alpha2.TypeMatchingExact, + TypeMatching: emeventingv2alpha1.TypeMatchingExact, Types: []string{ "sap.kyma.custom.difffoovarkes.order.created.v1", "sap.kyma.custom.difffoovarkes.order.created.v2", @@ -84,10 +84,10 @@ func TestFilterEventTypeVersions(t *testing.T) { }, { name: "should return event type only with 'sap.kyma.custom' prefix and appname", appName: "foovarkes", - subscription: &eventingv1alpha2.Subscription{ - Spec: eventingv1alpha2.SubscriptionSpec{ + subscription: &emeventingv2alpha1.Subscription{ + Spec: emeventingv2alpha1.SubscriptionSpec{ Source: "/default/sap.kyma/tunas-develop", - TypeMatching: eventingv1alpha2.TypeMatchingExact, + TypeMatching: emeventingv2alpha1.TypeMatchingExact, Types: []string{ "foo.prefix.custom.foovarkes.order.created.v1", "sap.kyma.custom.foovarkes.order.created.v2", @@ -158,7 +158,7 @@ func TestFilterEventTypeVersionsV1alpha1(t *testing.T) { appName string eventTypePrefix string bebNs string - filters *eventingv1alpha1.BEBFilters + filters *emeventingv1alpha1.BEBFilters expectedEvents []Event }{ { @@ -340,10 +340,10 @@ func TestAddUniqueEventsToResult(t *testing.T) { } } -type EventMeshFilterOption func(filter *eventingv1alpha1.BEBFilters) +type EventMeshFilterOption func(filter *emeventingv1alpha1.BEBFilters) -func NewEventMeshFilters(opts ...EventMeshFilterOption) *eventingv1alpha1.BEBFilters { - newFilters := &eventingv1alpha1.BEBFilters{} +func NewEventMeshFilters(opts ...EventMeshFilterOption) *emeventingv1alpha1.BEBFilters { + newFilters := &emeventingv1alpha1.BEBFilters{} for _, opt := range opts { opt(newFilters) } @@ -351,31 +351,31 @@ func NewEventMeshFilters(opts ...EventMeshFilterOption) *eventingv1alpha1.BEBFil return newFilters } -func WithOneEventMeshFilter(filters *eventingv1alpha1.BEBFilters) { +func WithOneEventMeshFilter(filters *emeventingv1alpha1.BEBFilters) { evSource := "/default/foo.kyma/kt1" evType := "foo.prefix.custom.foovarkes.order.created.v1" - filters.Filters = []*eventingv1alpha1.EventMeshFilter{ + filters.Filters = []*emeventingv1alpha1.EventMeshFilter{ NewEventMeshFilter(evSource, evType), } } -func WithMultipleEventMeshFiltersFromSameSource(filters *eventingv1alpha1.BEBFilters) { +func WithMultipleEventMeshFiltersFromSameSource(filters *emeventingv1alpha1.BEBFilters) { evSource := "/default/foo.kyma/kt1" evType := "foo.prefix.custom.foovarkes.order.created.v1" - filters.Filters = []*eventingv1alpha1.EventMeshFilter{ + filters.Filters = []*emeventingv1alpha1.EventMeshFilter{ NewEventMeshFilter(evSource, evType), NewEventMeshFilter(evSource, evType), NewEventMeshFilter(evSource, evType), } } -func WithMultipleEventMeshFiltersFromDiffSource(filters *eventingv1alpha1.BEBFilters) { +func WithMultipleEventMeshFiltersFromDiffSource(filters *emeventingv1alpha1.BEBFilters) { evSource1 := "foo-match" evSource2 := "/default/foo.different/kt1" evSource3 := "/default/foo.different2/kt1" evSource4 := "" evType := "foo.prefix.custom.foovarkes.order.created.v1" - filters.Filters = []*eventingv1alpha1.EventMeshFilter{ + filters.Filters = []*emeventingv1alpha1.EventMeshFilter{ NewEventMeshFilter(evSource1, evType), NewEventMeshFilter(evSource2, evType), NewEventMeshFilter(evSource3, evType), @@ -383,24 +383,24 @@ func WithMultipleEventMeshFiltersFromDiffSource(filters *eventingv1alpha1.BEBFil } } -func WithMultipleEventMeshFiltersFromDiffEventTypePrefix(filters *eventingv1alpha1.BEBFilters) { +func WithMultipleEventMeshFiltersFromDiffEventTypePrefix(filters *emeventingv1alpha1.BEBFilters) { evSource := "/default/foo.kyma/kt1" evType1 := "foo.prefix.custom.foovarkes.order.created.v1" evType2 := "foo.prefixdifferent.custom.foovarkes.order.created.v1" - filters.Filters = []*eventingv1alpha1.EventMeshFilter{ + filters.Filters = []*emeventingv1alpha1.EventMeshFilter{ NewEventMeshFilter(evSource, evType1), NewEventMeshFilter(evSource, evType2), NewEventMeshFilter(evSource, evType1), } } -func NewEventMeshFilter(evSource, evType string) *eventingv1alpha1.EventMeshFilter { - return &eventingv1alpha1.EventMeshFilter{ - EventSource: &eventingv1alpha1.Filter{ +func NewEventMeshFilter(evSource, evType string) *emeventingv1alpha1.EventMeshFilter { + return &emeventingv1alpha1.EventMeshFilter{ + EventSource: &emeventingv1alpha1.Filter{ Property: "source", Value: evSource, }, - EventType: &eventingv1alpha1.Filter{ + EventType: &emeventingv1alpha1.Filter{ Property: "type", Value: evType, }, diff --git a/pkg/tracing/helpers.go b/pkg/tracing/helpers.go index 2b38f6a..7391cd6 100644 --- a/pkg/tracing/helpers.go +++ b/pkg/tracing/helpers.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - cev2 "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/cloudevents/sdk-go/v2/extensions" ) @@ -23,7 +23,7 @@ const ( b3FlagsCEExtensionsKey = "b3flags" ) -func AddTracingContextToCEExtensions(reqHeaders http.Header, event *cev2.Event) { +func AddTracingContextToCEExtensions(reqHeaders http.Header, event *ceevent.Event) { traceParent := reqHeaders.Get(traceParentKey) if len(traceParent) > 0 { st := extensions.DistributedTracingExtension{ diff --git a/pkg/tracing/helpers_test.go b/pkg/tracing/helpers_test.go index c46cca2..aa018e9 100644 --- a/pkg/tracing/helpers_test.go +++ b/pkg/tracing/helpers_test.go @@ -4,7 +4,7 @@ import ( "net/http" "testing" - cev2event "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/onsi/gomega" ) @@ -62,7 +62,7 @@ func TestAddTracingContextToCEExtensions(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - event := cev2event.New() + event := ceevent.New() AddTracingContextToCEExtensions(tc.headers, &event) g.Expect(event.Extensions()).To(gomega.Equal(tc.expectedExtensions)) }) diff --git a/testing/fixtures.go b/testing/fixtures.go index ac97b3f..a43f90f 100644 --- a/testing/fixtures.go +++ b/testing/fixtures.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - cev2 "github.com/cloudevents/sdk-go/v2/event" + ceevent "github.com/cloudevents/sdk-go/v2/event" "github.com/stretchr/testify/assert" "github.com/kyma-project/eventing-publisher-proxy/internal" @@ -129,8 +129,8 @@ func (b *CloudEventBuilder) BuildStructured() (string, http.Header) { return payload, headers } -func (b *CloudEventBuilder) Build(t *testing.T) *cev2.Event { - e := cev2.New(b.specVersion) +func (b *CloudEventBuilder) Build(t *testing.T) *ceevent.Event { + e := ceevent.New(b.specVersion) assert.NoError(t, e.Context.SetID(b.id)) assert.NoError(t, e.Context.SetType(b.eventType)) assert.NoError(t, e.Context.SetSource(b.eventSource)) diff --git a/testing/nats.go b/testing/nats.go index bfcb937..4774881 100644 --- a/testing/nats.go +++ b/testing/nats.go @@ -7,7 +7,7 @@ import ( "github.com/kyma-project/eventing-manager/pkg/logger" - pkgnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" + eppnats "github.com/kyma-project/eventing-publisher-proxy/pkg/nats" "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats-server/v2/test" @@ -30,9 +30,9 @@ func StartNATSServer() *server.Server { } func ConnectToNATSServer(url string) (*nats.Conn, error) { - return pkgnats.Connect(url, - pkgnats.WithRetryOnFailedConnect(true), - pkgnats.WithMaxReconnects(maxReconnects), - pkgnats.WithReconnectWait(time.Second), + return eppnats.Connect(url, + eppnats.WithRetryOnFailedConnect(true), + eppnats.WithMaxReconnects(maxReconnects), + eppnats.WithReconnectWait(time.Second), ) } diff --git a/testing/utils.go b/testing/utils.go index 5296b13..a333f1d 100644 --- a/testing/utils.go +++ b/testing/utils.go @@ -9,7 +9,7 @@ import ( "strconv" "time" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + emeventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" ) // binary cloudevent headers. @@ -20,7 +20,7 @@ const ( CeSpecVersionHeader = "ce-specversion" ) -type SubscriptionOpt func(*eventingv1alpha1.Subscription) +type SubscriptionOpt func(*emeventingv1alpha1.Subscription) // GeneratePortOrDie generates a random 5 digit port or fail. func GeneratePortOrDie() int {