From 1d7797e11397e1a90d2e21da2928dd5eb4329041 Mon Sep 17 00:00:00 2001 From: "Kiss, Tibor" Date: Tue, 30 Jan 2024 11:14:44 +0100 Subject: [PATCH 1/2] Fix: gofumpt --- .github/workflows/lint-go.yml | 2 +- README.md | 2 +- pkg/application/clean.go | 6 ++---- pkg/cloudevents/builder/eventmesh.go | 3 ++- pkg/cloudevents/builder/generic.go | 5 +++-- pkg/cloudevents/eventtype/clean.go | 8 +++----- pkg/cloudevents/utils.go | 3 ++- pkg/handler/handler.go | 15 +++++++++----- pkg/informers/sync.go | 3 ++- pkg/legacy/legacy.go | 15 +++++++++----- pkg/metrics/collector.go | 6 ++++-- pkg/metrics/metricstest/metricstest.go | 6 +++--- pkg/metrics/server.go | 1 + pkg/oauth/client.go | 2 +- pkg/sender/eventmesh/eventmesh_test.go | 5 +++-- pkg/sender/helper.go | 3 +-- pkg/sender/jetstream/jetstream.go | 27 +++++++++++++++++--------- pkg/subscribed/helpers.go | 3 ++- pkg/subscribed/processor.go | 1 - 19 files changed, 69 insertions(+), 47 deletions(-) diff --git a/.github/workflows/lint-go.yml b/.github/workflows/lint-go.yml index 62e53b2..e2f989a 100644 --- a/.github/workflows/lint-go.yml +++ b/.github/workflows/lint-go.yml @@ -16,4 +16,4 @@ jobs: 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/bb304a7bc82577a23ed653a35592be97d5d02c41/config/lint/.golangci.yaml + lint-config-uri: https://raw.githubusercontent.com/kyma-project/eventing-tools/5a12f7707581ff98ed8cd299c6e19ac1287697ae/config/lint/.golangci.yaml diff --git a/README.md b/README.md index 53d72e3..0fea443 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ To run the E2E tests, refer to [Testing](docs/contributor/01-00-testing.md). ```sh make imports make fmt - make lint + make lint-fix ``` ### Build Container Images diff --git a/pkg/application/clean.go b/pkg/application/clean.go index caadf68..0d41075 100644 --- a/pkg/application/clean.go +++ b/pkg/application/clean.go @@ -12,10 +12,8 @@ const ( TypeLabel = "application-type" ) -var ( - // invalidApplicationNameSegment used to match and replace none-alphanumeric characters in the application name. - invalidApplicationNameSegment = regexp.MustCompile(`\W|_`) -) +// invalidApplicationNameSegment used to match and replace none-alphanumeric characters in the application name. +var invalidApplicationNameSegment = regexp.MustCompile(`\W|_`) // 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. diff --git a/pkg/cloudevents/builder/eventmesh.go b/pkg/cloudevents/builder/eventmesh.go index 440b91d..7c45048 100644 --- a/pkg/cloudevents/builder/eventmesh.go +++ b/pkg/cloudevents/builder/eventmesh.go @@ -12,7 +12,8 @@ import ( var _ CloudEventBuilder = &EventMeshBuilder{} func NewEventMeshBuilder(prefix string, eventMeshNamespace string, cleaner cleaner.Cleaner, - applicationLister *application.Lister, logger *logger.Logger) CloudEventBuilder { + applicationLister *application.Lister, logger *logger.Logger, +) CloudEventBuilder { genericBuilder := GenericBuilder{ typePrefix: prefix, applicationLister: applicationLister, diff --git a/pkg/cloudevents/builder/generic.go b/pkg/cloudevents/builder/generic.go index e28b22a..1273652 100644 --- a/pkg/cloudevents/builder/generic.go +++ b/pkg/cloudevents/builder/generic.go @@ -21,7 +21,8 @@ const ( ) func NewGenericBuilder(typePrefix string, cleaner cleaner.Cleaner, applicationLister *application.Lister, - logger *logger.Logger) CloudEventBuilder { + logger *logger.Logger, +) CloudEventBuilder { return &GenericBuilder{ typePrefix: typePrefix, applicationLister: applicationLister, @@ -80,7 +81,7 @@ func (gb *GenericBuilder) getFinalSubject(source, eventType string) string { // GetAppNameOrSource returns the application name if exists, otherwise returns source name. func (gb *GenericBuilder) GetAppNameOrSource(source string, namedLogger *zap.SugaredLogger) string { - var appName = source + appName := source if gb.isApplicationListerEnabled() { if appObj, err := gb.applicationLister.Get(source); err == nil && appObj != nil { appName = application.GetTypeOrName(appObj) diff --git a/pkg/cloudevents/eventtype/clean.go b/pkg/cloudevents/eventtype/clean.go index acce369..03ab007 100644 --- a/pkg/cloudevents/eventtype/clean.go +++ b/pkg/cloudevents/eventtype/clean.go @@ -10,11 +10,9 @@ import ( "github.com/kyma-project/eventing-manager/pkg/logger" ) -var ( - // invalidEventTypeSegment used to match and replace none-alphanumeric characters in the event-type segments - // as per SAP Event spec https://github.tools.sap/CentralEngineering/sap-event-specification#type. - invalidEventTypeSegment = regexp.MustCompile("[^a-zA-Z0-9.]") -) +// invalidEventTypeSegment used to match and replace none-alphanumeric characters in the event-type segments +// as per SAP Event spec https://github.tools.sap/CentralEngineering/sap-event-specification#type. +var invalidEventTypeSegment = regexp.MustCompile("[^a-zA-Z0-9.]") const ( // cleanerName used as the logger name. diff --git a/pkg/cloudevents/utils.go b/pkg/cloudevents/utils.go index 4ac2cee..5839094 100644 --- a/pkg/cloudevents/utils.go +++ b/pkg/cloudevents/utils.go @@ -15,7 +15,8 @@ func WriteRequestWithHeaders( message binding.Message, req *http.Request, headers http.Header, - transformers ...binding.Transformer) error { + transformers ...binding.Transformer, +) error { err := cehttp.WriteRequest(ctx, message, req, transformers...) if err != nil { return errors.Wrap(err, "failed to write Request") diff --git a/pkg/handler/handler.go b/pkg/handler/handler.go index ce98718..a7114c3 100644 --- a/pkg/handler/handler.go +++ b/pkg/handler/handler.go @@ -69,7 +69,8 @@ func New(receiver *receiver.HTTPMessageReceiver, sender sender.GenericSender, he requestTimeout time.Duration, legacyTransformer legacy.RequestToCETransformer, opts *options.Options, subscribedProcessor *subscribed.Processor, logger *logger.Logger, collector metrics.PublishingMetricsCollector, eventTypeCleaner eventtype.Cleaner, ceBuilder builder.CloudEventBuilder, oldEventTypePrefix string, - activeBackend env.ActiveBackend) *Handler { + activeBackend env.ActiveBackend, +) *Handler { return &Handler{ Name: "", Receiver: receiver, @@ -123,7 +124,8 @@ 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 *ceevent.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) @@ -142,7 +144,8 @@ 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) (*ceevent.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)) @@ -169,7 +172,8 @@ 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) (*ceevent.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") @@ -299,7 +303,8 @@ func extractCloudEventFromRequest(r *http.Request) (*ceevent.Event, error) { // sendEventAndRecordMetrics dispatches an Event and records metrics based on dispatch success. func (h *Handler) sendEventAndRecordMetrics(ctx context.Context, event *ceevent.Event, - host string, header http.Header) error { + host string, header http.Header, +) error { ctx, cancel := context.WithTimeout(ctx, h.RequestTimeout) defer cancel() h.applyDefaults(ctx, event) diff --git a/pkg/informers/sync.go b/pkg/informers/sync.go index a3db7ea..47f895a 100644 --- a/pkg/informers/sync.go +++ b/pkg/informers/sync.go @@ -18,7 +18,8 @@ type waitForCacheSyncFunc func(stopCh <-chan struct{}) map[schema.GroupVersionRe // WaitForCacheSyncOrDie waits for the cache to sync. If sync fails everything stops. func WaitForCacheSyncOrDie(ctx context.Context, dc dynamicinformer.DynamicSharedInformerFactory, - logger *logger.Logger) { + logger *logger.Logger, +) { dc.Start(ctx.Done()) ctx, cancel := context.WithTimeout(context.Background(), DefaultResyncPeriod) diff --git a/pkg/legacy/legacy.go b/pkg/legacy/legacy.go index 41e1286..8ada7e8 100644 --- a/pkg/legacy/legacy.go +++ b/pkg/legacy/legacy.go @@ -86,7 +86,8 @@ func (t *Transformer) checkParameters(parameters *eppapi.PublishEventParametersV // ExtractPublishRequestData extracts the data for publishing event from the given legacy event request. func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*eppapi.PublishRequestData, - *eppapi.PublishEventResponses, error) { + *eppapi.PublishEventResponses, error, +) { // parse request body to PublishRequestV1 if request.Body == nil || request.ContentLength == 0 { resp := ErrorResponseBadRequest(ErrorMessageBadPayload) @@ -125,7 +126,8 @@ func (t *Transformer) ExtractPublishRequestData(request *http.Request) (*eppapi. // 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 *eppapi.PublishRequestData) (*ceevent.Event, string) { + publishData *eppapi.PublishRequestData, +) (*ceevent.Event, string) { uncleanedAppName := publishData.ApplicationName // clean the application name form non-alphanumeric characters @@ -155,7 +157,8 @@ func (t *Transformer) WriteLegacyRequestsToCE(writer http.ResponseWriter, } func (t *Transformer) WriteCEResponseAsLegacyResponse(writer http.ResponseWriter, statusCode int, - event *ceevent.Event, msg string) { + event *ceevent.Event, msg string, +) { response := &eppapi.PublishEventResponses{} // Fail if !is2XXStatusCode(statusCode) { @@ -174,7 +177,8 @@ func (t *Transformer) WriteCEResponseAsLegacyResponse(writer http.ResponseWriter // TransformPublishRequestToCloudEvent converts the given publish request to a CloudEvent with raw values. func (t *Transformer) TransformPublishRequestToCloudEvent(publishRequestData *eppapi.PublishRequestData) (*ceevent.Event, - error) { + error, +) { source := publishRequestData.ApplicationName publishRequest := publishRequestData.PublishEventParameters @@ -214,7 +218,8 @@ func (t *Transformer) TransformPublishRequestToCloudEvent(publishRequestData *ep // convertPublishRequestToCloudEvent converts the given publish request to a CloudEvent. func (t *Transformer) convertPublishRequestToCloudEvent(appName string, - publishRequest *eppapi.PublishEventParametersV1) (*ceevent.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") } diff --git a/pkg/metrics/collector.go b/pkg/metrics/collector.go index 68e4a7f..e4685c8 100644 --- a/pkg/metrics/collector.go +++ b/pkg/metrics/collector.go @@ -98,9 +98,11 @@ func NewCollector(latency histogram.BucketsProvider) *Collector { prometheus.HistogramOpts{ Name: durationKey, Help: durationHelp, - Buckets: []float64{0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.050, 0.075, + Buckets: []float64{ + 0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.050, 0.075, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.7, 0.8, 0.9, - 1, 1.5, 2, 3, 5}, + 1, 1.5, 2, 3, 5, + }, }, []string{responseCodeLabel, methodLabel, pathLabel}, ), diff --git a/pkg/metrics/metricstest/metricstest.go b/pkg/metrics/metricstest/metricstest.go index cb074cc..f17504e 100644 --- a/pkg/metrics/metricstest/metricstest.go +++ b/pkg/metrics/metricstest/metricstest.go @@ -32,14 +32,14 @@ func ensureMetricCount(t *testing.T, collector metrics.PublishingMetricsCollecto // match the given metric output in TextExpositionFormat. // This is useful to compare metrics with their given labels. func EnsureMetricMatchesTextExpositionFormat(t *testing.T, collector metrics.PublishingMetricsCollector, - tef string, metricNames ...string) { + tef string, metricNames ...string, +) { if err := testutil.CollectAndCompare(collector, strings.NewReader(tef), metricNames...); err != nil { t.Fatalf("%v", err) } } -type PublishingMetricsCollectorStub struct { -} +type PublishingMetricsCollectorStub struct{} func (p PublishingMetricsCollectorStub) Describe(_ chan<- *prometheus.Desc) { } diff --git a/pkg/metrics/server.go b/pkg/metrics/server.go index 8c2b8ae..84b7ad0 100644 --- a/pkg/metrics/server.go +++ b/pkg/metrics/server.go @@ -57,6 +57,7 @@ func (s *Server) Stop() { s.namedLogger().Warnw("Failed to shutdown metrics server", "error", err) } } + func (s *Server) namedLogger() *zap.SugaredLogger { return s.logger.WithContext().Named(metricsServerLoggerName) } diff --git a/pkg/oauth/client.go b/pkg/oauth/client.go index 3f56fce..d08aeaf 100644 --- a/pkg/oauth/client.go +++ b/pkg/oauth/client.go @@ -18,7 +18,7 @@ func NewClient(ctx context.Context, cfg *env.EventMeshConfig) *http.Client { client := config.Client(ctx) // configure connection transport - var base = http.DefaultTransport.(*http.Transport).Clone() + base := http.DefaultTransport.(*http.Transport).Clone() cfg.ConfigureTransport(base) client.Transport.(*oauth2.Transport).Base = base diff --git a/pkg/sender/eventmesh/eventmesh_test.go b/pkg/sender/eventmesh/eventmesh_test.go index ebc9b26..49eadf5 100644 --- a/pkg/sender/eventmesh/eventmesh_test.go +++ b/pkg/sender/eventmesh/eventmesh_test.go @@ -99,7 +99,7 @@ func TestSender_Send_Error(t *testing.T) { timeout time.Duration builder *epptestingutils.CloudEventBuilder } - var tests = []struct { + tests := []struct { name string fields fields args args @@ -140,6 +140,7 @@ func TestSender_Send_Error(t *testing.T) { }) } } + func TestSender_Send(t *testing.T) { type fields struct { Target string @@ -148,7 +149,7 @@ func TestSender_Send(t *testing.T) { ctx context.Context builder *epptestingutils.CloudEventBuilder } - var tests = []struct { + tests := []struct { name string fields fields args args diff --git a/pkg/sender/helper.go b/pkg/sender/helper.go index 41399fc..b334765 100644 --- a/pkg/sender/helper.go +++ b/pkg/sender/helper.go @@ -6,8 +6,7 @@ import ( "github.com/prometheus/client_golang/prometheus" ) -type PublishingMetricsCollectorStub struct { -} +type PublishingMetricsCollectorStub struct{} func (p PublishingMetricsCollectorStub) Describe(chan<- *prometheus.Desc) { } diff --git a/pkg/sender/jetstream/jetstream.go b/pkg/sender/jetstream/jetstream.go index f274462..c1fcdf0 100644 --- a/pkg/sender/jetstream/jetstream.go +++ b/pkg/sender/jetstream/jetstream.go @@ -29,16 +29,24 @@ const ( ) // compile time check. -var _ sender.GenericSender = &Sender{} -var _ health.Checker = &Sender{} +var ( + _ sender.GenericSender = &Sender{} + _ health.Checker = &Sender{} +) var ( - ErrNotConnected = common.BackendPublishError{HTTPCode: http.StatusBadGateway, - Info: "no connection to NATS JetStream server"} - ErrCannotSendToStream = common.BackendPublishError{HTTPCode: http.StatusGatewayTimeout, - Info: "cannot send to stream"} - ErrNoSpaceLeftOnDevice = common.BackendPublishError{HTTPCode: http.StatusInsufficientStorage, - Info: "insufficient resources on target stream"} + ErrNotConnected = common.BackendPublishError{ + HTTPCode: http.StatusBadGateway, + Info: "no connection to NATS JetStream server", + } + ErrCannotSendToStream = common.BackendPublishError{ + HTTPCode: http.StatusGatewayTimeout, + Info: "cannot send to stream", + } + ErrNoSpaceLeftOnDevice = common.BackendPublishError{ + HTTPCode: http.StatusInsufficientStorage, + Info: "insufficient resources on target stream", + } ) // Sender is responsible for sending messages over HTTP. @@ -56,7 +64,8 @@ func (s *Sender) URL() string { // NewSender returns a new NewSender instance with the given NATS connection. func NewSender(ctx context.Context, connection *nats.Conn, envCfg *env.NATSConfig, opts *options.Options, - logger *logger.Logger) *Sender { + logger *logger.Logger, +) *Sender { return &Sender{ctx: ctx, connection: connection, envCfg: envCfg, opts: opts, logger: logger} } diff --git a/pkg/subscribed/helpers.go b/pkg/subscribed/helpers.go index e5057f6..76140c4 100644 --- a/pkg/subscribed/helpers.go +++ b/pkg/subscribed/helpers.go @@ -135,7 +135,8 @@ 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 *emeventingv1alpha1.BEBFilters) []Event { + filters *emeventingv1alpha1.BEBFilters, +) []Event { events := make([]Event, 0) if filters == nil { return events diff --git a/pkg/subscribed/processor.go b/pkg/subscribed/processor.go index ca9eefb..71fd658 100644 --- a/pkg/subscribed/processor.go +++ b/pkg/subscribed/processor.go @@ -35,7 +35,6 @@ func (p Processor) extractEventsFromSubscriptions( appName := legacy.ParseApplicationNameFromPath(request.URL.Path) for _, sObj := range subsList { sub, err := ConvertRuntimeObjToSubscription(sObj) - if err != nil { p.namedLogger().Errorw("Failed to convert a runtime obj to a Subscription", "error", err) continue From 543e42f984347807c081985b55f3d88976817ff2 Mon Sep 17 00:00:00 2001 From: "Kiss, Tibor" Date: Tue, 30 Jan 2024 15:35:06 +0100 Subject: [PATCH 2/2] New configuration --- .github/workflows/lint-go.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lint-go.yml b/.github/workflows/lint-go.yml index e2f989a..41e84f6 100644 --- a/.github/workflows/lint-go.yml +++ b/.github/workflows/lint-go.yml @@ -16,4 +16,4 @@ jobs: 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/5a12f7707581ff98ed8cd299c6e19ac1287697ae/config/lint/.golangci.yaml + lint-config-uri: https://raw.githubusercontent.com/kyma-project/eventing-tools/4bc0e923b67ddb0a028171d8beebc3cb4a211d69/config/lint/.golangci.yaml