repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/secure.go
app/router/secure.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package router import ( "github.com/harness/gitness/types" "github.com/unrolled/secure" ) // NewSecure returns a new secure.Secure middleware to enforce security best practices // for the user interface (not meant APIs). func NewSecure(config *types.Config) *secure.Secure { return secure.New( secure.Options{ AllowedHosts: config.Secure.AllowedHosts, HostsProxyHeaders: config.Secure.HostsProxyHeaders, SSLRedirect: config.Secure.SSLRedirect, SSLTemporaryRedirect: config.Secure.SSLTemporaryRedirect, SSLHost: config.Secure.SSLHost, SSLProxyHeaders: config.Secure.SSLProxyHeaders, STSSeconds: config.Secure.STSSeconds, STSIncludeSubdomains: config.Secure.STSIncludeSubdomains, STSPreload: config.Secure.STSPreload, ForceSTSHeader: config.Secure.ForceSTSHeader, FrameDeny: config.Secure.FrameDeny, ContentTypeNosniff: config.Secure.ContentTypeNosniff, BrowserXssFilter: config.Secure.BrowserXSSFilter, ContentSecurityPolicy: config.Secure.ContentSecurityPolicy, ReferrerPolicy: config.Secure.ReferrerPolicy, }, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/web.go
app/router/web.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package router import ( "net/http" middlewareweb "github.com/harness/gitness/app/api/middleware/web" "github.com/harness/gitness/app/api/openapi" "github.com/harness/gitness/app/api/render" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/web" "github.com/go-chi/chi/v5" "github.com/rs/zerolog/log" "github.com/swaggest/swgui" "github.com/swaggest/swgui/v5emb" "github.com/unrolled/secure" ) // NewWebHandler returns a new WebHandler. func NewWebHandler( authenticator authn.Authenticator, openapi openapi.Service, sec *secure.Secure, publicResourceCreationEnabled bool, uiSourceOverride string, ) http.Handler { // Use go-chi router for inner routing r := chi.NewRouter() // openapi endpoints // TODO: this should not be generated and marshaled on the fly every time? r.HandleFunc("/openapi.yaml", func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() spec := openapi.Generate() data, err := spec.MarshalYAML() if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to serialize openapi.yaml") render.InternalError(ctx, w) return } w.Header().Set("Content-Type", "application/yaml") w.WriteHeader(http.StatusOK) _, _ = w.Write(data) }) // swagger endpoints r.Group(func(r chi.Router) { r.Use(sec.Handler) swagger := v5emb.NewHandlerWithConfig(swgui.Config{ Title: "API Definition", SwaggerJSON: "/openapi.yaml", BasePath: "/swagger", // Available settings can be found here: // https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ SettingsUI: map[string]string{ "queryConfigEnabled": "false", // block code injection vulnerability "defaultModelsExpandDepth": "1", }, }) r.Handle("/swagger", swagger) r.Handle("/swagger/*", swagger) }) // serve all other routes from the embedded filesystem, // which in turn serves the user interface. r.With( sec.Handler, middlewareweb.PublicAccess(publicResourceCreationEnabled, authenticator), ).NotFound( web.Handler(uiSourceOverride), ) return r }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/web_router.go
app/router/web_router.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package router import ( "net/http" "github.com/harness/gitness/logging" ) type WebRouter struct { handler http.Handler } func NewWebRouter(handler http.Handler) *WebRouter { return &WebRouter{handler: handler} } func (r *WebRouter) Handle(w http.ResponseWriter, req *http.Request) { req = req.WithContext(logging.NewContext(req.Context(), WithLoggingRouter("web"))) r.handler.ServeHTTP(w, req) } func (r *WebRouter) IsEligibleTraffic(*http.Request) bool { // Everything else will be routed to web (or return 404) return true } func (r *WebRouter) Name() string { return "web" }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/router_test.go
app/router/router_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package router import "testing" // this unit test ensures routes that require authorization // return a 401 unauthorized if no token, or an invalid token // is provided. func TestTokenGate(t *testing.T) { t.Skip() } // this unit test ensures routes that require pipeline access // return a 403 forbidden if the user does not have acess // to the pipeline. func TestPipelineGate(t *testing.T) { t.Skip() } // this unit test ensures routes that require system access // return a 403 forbidden if the user does not have acess // to the pipeline. func TestSystemGate(t *testing.T) { t.Skip() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/api_router.go
app/router/api_router.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package router import ( "net/http" "strings" "github.com/harness/gitness/app/api/render" "github.com/harness/gitness/logging" "github.com/rs/zerolog/log" ) const APIMount = "/api" type APIRouter struct { handler http.Handler } func NewAPIRouter(handler http.Handler) *APIRouter { return &APIRouter{handler: handler} } func (r *APIRouter) Handle(w http.ResponseWriter, req *http.Request) { req = req.WithContext(logging.NewContext(req.Context(), WithLoggingRouter("api"))) // remove matched prefix to simplify API handlers if err := StripPrefix(APIMount, req); err != nil { //nolint:contextcheck log.Ctx(req.Context()).Err(err).Msgf("Failed striping of prefix for api request.") //nolint:contextcheck render.InternalError(req.Context(), w) return } r.handler.ServeHTTP(w, req) } func (r *APIRouter) IsEligibleTraffic(req *http.Request) bool { // All Rest API calls start with "/api/", and thus can be uniquely identified. p := req.URL.Path return strings.HasPrefix(p, APIMount+"/") } func (r *APIRouter) Name() string { return "api" }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/request/request.go
app/request/request.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package request import ( "fmt" "net/http" "net/url" ) // ReplacePrefix replaces the path of the request. // IMPORTANT: // - both prefix are unescaped for path, and used as is for RawPath! // - only called by top level handler!! func ReplacePrefix(r *http.Request, oldPrefix string, newPrefix string) error { /* * According to official documentation, we can change anything in the request but the body: * https://pkg.go.dev/net/http#Handler * * ASSUMPTION: * This is called by a top level handler (no router or middleware above it) * Therefore, we don't have to worry about getting any routing metadata out of sync. * * This is different to returning a shallow clone with updated URL, which is what * http.StripPrefix or earlier versions of request.WithContext are doing: * https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/net/http/server.go;l=2138 * https://cs.opensource.google/go/go/+/refs/tags/go1.18:src/net/http/request.go;l=355 * * http.StripPrefix initially changed the path only, but that was updated because of official recommendations: * https://github.com/golang/go/issues/18952 */ l := len(oldPrefix) if r.URL.RawPath != "" { if len(r.URL.RawPath) < l || r.URL.RawPath[0:l] != oldPrefix { return fmt.Errorf("raw path '%s' doesn't contain prefix '%s'", r.URL.RawPath, oldPrefix) } r.URL.RawPath = newPrefix + r.URL.RawPath[l:] r.URL.Path = url.PathEscape(r.URL.RawPath) } else { if len(r.URL.Path) < l || r.URL.Path[0:l] != oldPrefix { return fmt.Errorf("path '%s' doesn't contain prefix '%s'", r.URL.Path, oldPrefix) } r.URL.Path = newPrefix + r.URL.Path[l:] } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/request/request_test.go
app/request/request_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package request import ( "context" "net/http" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestReplacePrefix(t *testing.T) { tests := []struct { name string path string rawPath string oldPrefix string newPrefix string wantPath string wantRawPath string wantErr bool }{ { name: "simple path replacement", path: "/api/v1/repos", rawPath: "", oldPrefix: "/api", newPrefix: "/v2", wantPath: "/v2/v1/repos", wantRawPath: "", wantErr: false, }, { name: "empty old prefix", path: "/api/v1/repos", rawPath: "", oldPrefix: "", newPrefix: "/v2", wantPath: "/v2/api/v1/repos", wantRawPath: "", wantErr: false, }, { name: "empty new prefix", path: "/api/v1/repos", rawPath: "", oldPrefix: "/api", newPrefix: "", wantPath: "/v1/repos", wantRawPath: "", wantErr: false, }, { name: "full path replacement", path: "/api", rawPath: "", oldPrefix: "/api", newPrefix: "/v2", wantPath: "/v2", wantRawPath: "", wantErr: false, }, { name: "path with raw path", path: "/api/v1/repos", rawPath: "/api/v1/repos", oldPrefix: "/api", newPrefix: "/v2", wantPath: "%2Fv2%2Fv1%2Frepos", wantRawPath: "/v2/v1/repos", wantErr: false, }, { name: "path with encoded characters", path: "/api/v1/repos%20test", rawPath: "/api/v1/repos%20test", oldPrefix: "/api", newPrefix: "/v2", wantPath: "%2Fv2%2Fv1%2Frepos%2520test", wantRawPath: "/v2/v1/repos%20test", wantErr: false, }, { name: "prefix not found in path", path: "/v1/repos", rawPath: "", oldPrefix: "/api", newPrefix: "/v2", wantPath: "/v1/repos", wantRawPath: "", wantErr: true, }, { name: "prefix not found in raw path", path: "/api/v1/repos", rawPath: "/v1/repos", oldPrefix: "/api", newPrefix: "/v2", wantPath: "/api/v1/repos", wantRawPath: "/v1/repos", wantErr: true, }, { name: "prefix longer than path", path: "/api", rawPath: "", oldPrefix: "/api/v1", newPrefix: "/v2", wantPath: "/api", wantRawPath: "", wantErr: true, }, { name: "partial prefix match should fail", path: "/application/v1", rawPath: "", oldPrefix: "/api", newPrefix: "/v2", wantPath: "/application/v1", wantRawPath: "", wantErr: true, }, { name: "replace with longer prefix", path: "/api/v1", rawPath: "", oldPrefix: "/api", newPrefix: "/v2/api/new", wantPath: "/v2/api/new/v1", wantRawPath: "", wantErr: false, }, { name: "replace root path", path: "/", rawPath: "", oldPrefix: "/", newPrefix: "/v2", wantPath: "/v2", wantRawPath: "", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Create a new request with the test path req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example.com"+tt.path, nil) require.NoError(t, err) // Set raw path if provided if tt.rawPath != "" { req.URL.RawPath = tt.rawPath } // Call ReplacePrefix err = ReplacePrefix(req, tt.oldPrefix, tt.newPrefix) // Check error expectation if tt.wantErr { assert.Error(t, err) return } require.NoError(t, err) assert.Equal(t, tt.wantPath, req.URL.Path, "Path doesn't match") assert.Equal(t, tt.wantRawPath, req.URL.RawPath, "RawPath doesn't match") }) } } func TestReplacePrefix_PreservesOtherURLFields(t *testing.T) { // Create a request with various URL fields set req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example.com:8080/api/v1/repos?query=test#fragment", nil) require.NoError(t, err) originalScheme := req.URL.Scheme originalHost := req.URL.Host originalQuery := req.URL.RawQuery originalFragment := req.URL.Fragment // Replace the prefix err = ReplacePrefix(req, "/api", "/v2") require.NoError(t, err) // Verify other fields are preserved assert.Equal(t, originalScheme, req.URL.Scheme, "Scheme should be preserved") assert.Equal(t, originalHost, req.URL.Host, "Host should be preserved") assert.Equal(t, originalQuery, req.URL.RawQuery, "Query should be preserved") assert.Equal(t, originalFragment, req.URL.Fragment, "Fragment should be preserved") assert.Equal(t, "/v2/v1/repos", req.URL.Path, "Path should be updated") } func TestReplacePrefix_WithComplexURL(t *testing.T) { // Test with a complex URL containing special characters rawURL := "http://example.com/api/v1/repos/owner%2Frepo?branch=feature%2Ftest&limit=10" req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil) require.NoError(t, err) err = ReplacePrefix(req, "/api", "/v2") require.NoError(t, err) // The path should be updated (note: when RawPath is set, Path gets escaped) assert.Equal(t, "%2Fv2%2Fv1%2Frepos%2Fowner%252Frepo", req.URL.Path) // Query parameters should be preserved assert.Equal(t, "branch=feature%2Ftest&limit=10", req.URL.RawQuery) // Verify we can still parse query parameters values, err := url.ParseQuery(req.URL.RawQuery) require.NoError(t, err) assert.Equal(t, "feature/test", values.Get("branch")) assert.Equal(t, "10", values.Get("limit")) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/logger/zerolog.go
app/pipeline/logger/zerolog.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logger import ( "context" "fmt" "github.com/drone/runner-go/logger" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) // WithWrappedZerolog adds a wrapped copy of the zerolog logger to the context. func WithWrappedZerolog(ctx context.Context) context.Context { return logger.WithContext( ctx, &wrapZerolog{ inner: log.Ctx(ctx).With().Logger(), err: nil, }) } // WithUnwrappedZerolog adds an unwrapped copy of the zerolog logger to the context. func WithUnwrappedZerolog(ctx context.Context) context.Context { // try to get the logger from the wrapped zerologger if wrappedLogger, ok := logger.FromContext(ctx).(*wrapZerolog); ok { return wrappedLogger.inner.WithContext(ctx) } // if there's no logger, fall-back to global logger instance return log.Logger.WithContext(ctx) } // wrapZerolog wraps the zerolog logger to be used within drone packages. type wrapZerolog struct { inner zerolog.Logger err error } func (w *wrapZerolog) WithError(err error) logger.Logger { return &wrapZerolog{inner: w.inner, err: err} } func (w *wrapZerolog) WithField(key string, value any) logger.Logger { return &wrapZerolog{inner: w.inner.With().Str(key, fmt.Sprint(value)).Logger(), err: w.err} } func (w *wrapZerolog) Debug(args ...any) { w.inner.Debug().Err(w.err).Msg(fmt.Sprint(args...)) } func (w *wrapZerolog) Debugf(format string, args ...any) { w.inner.Debug().Err(w.err).Msgf(format, args...) } func (w *wrapZerolog) Debugln(args ...any) { w.inner.Debug().Err(w.err).Msg(fmt.Sprintln(args...)) } func (w *wrapZerolog) Error(args ...any) { w.inner.Error().Err(w.err).Msg(fmt.Sprint(args...)) } func (w *wrapZerolog) Errorf(format string, args ...any) { w.inner.Error().Err(w.err).Msgf(format, args...) } func (w *wrapZerolog) Errorln(args ...any) { w.inner.Error().Err(w.err).Msg(fmt.Sprintln(args...)) } func (w *wrapZerolog) Info(args ...any) { w.inner.Info().Err(w.err).Msg(fmt.Sprint(args...)) } func (w *wrapZerolog) Infof(format string, args ...any) { w.inner.Info().Err(w.err).Msgf(format, args...) } func (w *wrapZerolog) Infoln(args ...any) { w.inner.Info().Err(w.err).Msg(fmt.Sprintln(args...)) } func (w *wrapZerolog) Trace(args ...any) { w.inner.Trace().Err(w.err).Msg(fmt.Sprint(args...)) } func (w *wrapZerolog) Tracef(format string, args ...any) { w.inner.Trace().Err(w.err).Msgf(format, args...) } func (w *wrapZerolog) Traceln(args ...any) { w.inner.Trace().Err(w.err).Msg(fmt.Sprintln(args...)) } func (w *wrapZerolog) Warn(args ...any) { w.inner.Warn().Err(w.err).Msg(fmt.Sprint(args...)) } func (w *wrapZerolog) Warnf(format string, args ...any) { w.inner.Warn().Err(w.err).Msgf(format, args...) } func (w *wrapZerolog) Warnln(args ...any) { w.inner.Warn().Err(w.err).Msg(fmt.Sprintln(args...)) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/file/wire.go
app/pipeline/file/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "github.com/harness/gitness/git" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideService, ) // ProvideService provides a service which can read file contents // from a repository. func ProvideService(git git.Interface) Service { return newService(git) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/file/gitness.go
app/pipeline/file/gitness.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "fmt" "io" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/rs/zerolog/log" ) type service struct { git git.Interface } func newService(git git.Interface) Service { return &service{git: git} } func (f *service) Get( ctx context.Context, repo *types.Repository, path string, ref string, ) (*File, error) { readParams := git.ReadParams{ RepoUID: repo.GitUID, } treeNodeOutput, err := f.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: readParams, GitREF: ref, Path: path, IncludeLatestCommit: false, }) if err != nil { return nil, fmt.Errorf("failed to read tree node: %w", err) } // viewing Raw content is only supported for blob content if treeNodeOutput.Node.Type != git.TreeNodeTypeBlob { return nil, fmt.Errorf("path content is not of blob type: %s", treeNodeOutput.Node.Type) } blobReader, err := f.git.GetBlob(ctx, &git.GetBlobParams{ ReadParams: readParams, SHA: treeNodeOutput.Node.SHA, SizeLimit: 0, // no size limit, we stream whatever data there is }) if err != nil { return nil, fmt.Errorf("failed to read blob: %w", err) } defer func() { if err := blobReader.Content.Close(); err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader.") } }() buf, err := io.ReadAll(blobReader.Content) if err != nil { return nil, fmt.Errorf("could not read blob content from file: %w", err) } return &File{ Data: buf, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/file/service.go
app/pipeline/file/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "github.com/harness/gitness/types" ) type ( // File represents the raw file contents in the // version control system. File struct { Data []byte } // Service provides access to contents of files in // the SCM provider. Today, this is Harness but it should // be extendible to any SCM provider. // The plan is for all remote repos to be pointers inside Harness // so a repo entry would always exist. If this changes, the interface // can be updated. Service interface { // path is the path in the repo to read // ref is the git ref for the repository e.g. refs/heads/master Get(ctx context.Context, repo *types.Repository, path, ref string) (*File, error) } )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/wire.go
app/pipeline/manager/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( events "github.com/harness/gitness/app/events/pipeline" "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/livelog" "github.com/harness/gitness/types" "github.com/drone/runner-go/client" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideExecutionManager, ProvideExecutionClient, ) // ProvideExecutionManager provides an execution manager. func ProvideExecutionManager( config *types.Config, executionStore store.ExecutionStore, pipelineStore store.PipelineStore, urlProvider url.Provider, sseStreamer sse.Streamer, fileService file.Service, converterService converter.Service, logStore store.LogStore, logStream livelog.LogStream, checkStore store.CheckStore, repoStore store.RepoStore, scheduler scheduler.Scheduler, secretStore store.SecretStore, stageStore store.StageStore, stepStore store.StepStore, userStore store.PrincipalStore, publicAccess publicaccess.Service, reporter *events.Reporter, ) ExecutionManager { return New(config, executionStore, pipelineStore, urlProvider, sseStreamer, fileService, converterService, logStore, logStream, checkStore, repoStore, scheduler, secretStore, stageStore, stepStore, userStore, publicAccess, *reporter) } // ProvideExecutionClient provides a client implementation to interact with the execution manager. // We use an embedded client here. func ProvideExecutionClient( manager ExecutionManager, urlProvider url.Provider, config *types.Config, ) client.Client { return NewEmbeddedClient(manager, urlProvider, config) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/client.go
app/pipeline/manager/client.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "bytes" "context" "encoding/json" "github.com/harness/gitness/app/url" "github.com/harness/gitness/livelog" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/drone/drone-go/drone" "github.com/drone/runner-go/client" ) type embedded struct { config *types.Config urlProvider url.Provider manager ExecutionManager } var _ client.Client = (*embedded)(nil) func NewEmbeddedClient( manager ExecutionManager, urlProvider url.Provider, config *types.Config, ) client.Client { return &embedded{ config: config, urlProvider: urlProvider, manager: manager, } } // Join notifies the server the runner is joining the cluster. // Since the runner is embedded, this can just return nil. func (e *embedded) Join(_ context.Context, _ string) error { return nil } // Leave notifies the server the runner is leaving the cluster. // Since the runner is embedded, this can just return nil. func (e *embedded) Leave(_ context.Context, _ string) error { return nil } // Ping sends a ping message to the server to test connectivity. // Since the runner is embedded, this can just return nil. func (e *embedded) Ping(_ context.Context, _ string) error { return nil } // Request requests the next available build stage for execution. func (e *embedded) Request(ctx context.Context, args *client.Filter) (*drone.Stage, error) { request := &Request{ Kind: args.Kind, Type: args.Type, OS: args.OS, Arch: args.Arch, Variant: args.Variant, Kernel: args.Kernel, Labels: args.Labels, } stage, err := e.manager.Request(ctx, request) if err != nil { return nil, err } return ConvertToDroneStage(stage), nil } // Accept accepts the build stage for execution. func (e *embedded) Accept(ctx context.Context, s *drone.Stage) error { stage, err := e.manager.Accept(ctx, s.ID, s.Machine) if err != nil { return err } *s = *ConvertToDroneStage(stage) return err } // Detail gets the build stage details for execution. func (e *embedded) Detail(ctx context.Context, stage *drone.Stage) (*client.Context, error) { details, err := e.manager.Details(ctx, stage.ID) if err != nil { return nil, err } return &client.Context{ Build: ConvertToDroneBuild(details.Execution), Repo: ConvertToDroneRepo(details.Repo, details.RepoIsPublic), Stage: ConvertToDroneStage(details.Stage), Secrets: ConvertToDroneSecrets(details.Secrets), Config: ConvertToDroneFile(details.Config), Netrc: ConvertToDroneNetrc(details.Netrc), System: &drone.System{ Proto: e.urlProvider.GetAPIProto(ctx), Host: e.urlProvider.GetAPIHostname(ctx), }, }, nil } // Update updates the build stage. func (e *embedded) Update(ctx context.Context, stage *drone.Stage) error { var err error convertedStage := ConvertFromDroneStage(stage) status := enum.ParseCIStatus(stage.Status) if status == enum.CIStatusPending || status == enum.CIStatusRunning { err = e.manager.BeforeStage(ctx, convertedStage) } else { err = e.manager.AfterStage(ctx, convertedStage) } *stage = *ConvertToDroneStage(convertedStage) return err } // UpdateStep updates the build step. func (e *embedded) UpdateStep(ctx context.Context, step *drone.Step) error { var err error convertedStep := ConvertFromDroneStep(step) status := enum.ParseCIStatus(step.Status) if status == enum.CIStatusPending || status == enum.CIStatusRunning { err = e.manager.BeforeStep(ctx, convertedStep) } else { err = e.manager.AfterStep(ctx, convertedStep) } *step = *ConvertToDroneStep(convertedStep) return err } // Watch watches for build cancellation requests. func (e *embedded) Watch(ctx context.Context, executionID int64) (bool, error) { return e.manager.Watch(ctx, executionID) } // Batch batch writes logs to the streaming logs. func (e *embedded) Batch(ctx context.Context, step int64, lines []*drone.Line) error { for _, l := range lines { line := ConvertFromDroneLine(l) err := e.manager.Write(ctx, step, line) if err != nil { return err } } return nil } // Upload uploads the full logs to the server. func (e *embedded) Upload(ctx context.Context, step int64, l []*drone.Line) error { var buffer bytes.Buffer lines := []livelog.Line{} for _, line := range l { lines = append(lines, *ConvertFromDroneLine(line)) } out, err := json.Marshal(lines) if err != nil { return err } _, err = buffer.Write(out) if err != nil { return err } return e.manager.UploadLogs(ctx, step, &buffer) } // UploadCard uploads a card to drone server. func (e *embedded) UploadCard(_ context.Context, _ int64, _ *drone.CardInput) error { // Implement UploadCard logic here return nil // Replace with appropriate error handling and logic }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/convert.go
app/pipeline/manager/convert.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "time" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/livelog" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/drone/drone-go/drone" "github.com/drone/runner-go/client" ) func ConvertToDroneStage(stage *types.Stage) *drone.Stage { return &drone.Stage{ ID: stage.ID, BuildID: stage.ExecutionID, Number: int(stage.Number), Name: stage.Name, Kind: stage.Kind, Type: stage.Type, Status: string(stage.Status), Error: stage.Error, ErrIgnore: stage.ErrIgnore, ExitCode: stage.ExitCode, Machine: stage.Machine, OS: stage.OS, Arch: stage.Arch, Variant: stage.Variant, Kernel: stage.Kernel, Limit: stage.Limit, LimitRepo: stage.LimitRepo, Started: stage.Started / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Stopped: stage.Stopped / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Created: stage.Created / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Updated: stage.Updated / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Version: stage.Version, OnSuccess: stage.OnSuccess, OnFailure: stage.OnFailure, DependsOn: stage.DependsOn, Labels: stage.Labels, Steps: ConvertToDroneSteps(stage.Steps), } } func ConvertToDroneSteps(steps []*types.Step) []*drone.Step { droneSteps := make([]*drone.Step, len(steps)) for i, step := range steps { droneSteps[i] = ConvertToDroneStep(step) } return droneSteps } func ConvertToDroneStep(step *types.Step) *drone.Step { return &drone.Step{ ID: step.ID, StageID: step.StageID, Number: int(step.Number), Name: step.Name, Status: string(step.Status), Error: step.Error, ErrIgnore: step.ErrIgnore, ExitCode: step.ExitCode, Started: step.Started / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Stopped: step.Stopped / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Version: step.Version, DependsOn: step.DependsOn, Image: step.Image, Detached: step.Detached, Schema: step.Schema, } } func ConvertFromDroneStep(step *drone.Step) *types.Step { return &types.Step{ ID: step.ID, StageID: step.StageID, Number: int64(step.Number), Name: step.Name, Status: enum.ParseCIStatus(step.Status), Error: step.Error, ErrIgnore: step.ErrIgnore, ExitCode: step.ExitCode, Started: step.Started * 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Stopped: step.Stopped * 1e3, Version: step.Version, DependsOn: step.DependsOn, Image: step.Image, Detached: step.Detached, Schema: step.Schema, } } func ConvertFromDroneSteps(steps []*drone.Step) []*types.Step { typesSteps := make([]*types.Step, len(steps)) for i, step := range steps { typesSteps[i] = &types.Step{ ID: step.ID, StageID: step.StageID, Number: int64(step.Number), Name: step.Name, Status: enum.ParseCIStatus(step.Status), Error: step.Error, ErrIgnore: step.ErrIgnore, ExitCode: step.ExitCode, Started: step.Started * 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Stopped: step.Stopped * 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Version: step.Version, DependsOn: step.DependsOn, Image: step.Image, Detached: step.Detached, Schema: step.Schema, } } return typesSteps } func ConvertFromDroneStage(stage *drone.Stage) *types.Stage { return &types.Stage{ ID: stage.ID, ExecutionID: stage.BuildID, Number: int64(stage.Number), Name: stage.Name, Kind: stage.Kind, Type: stage.Type, Status: enum.ParseCIStatus(stage.Status), Error: stage.Error, ErrIgnore: stage.ErrIgnore, ExitCode: stage.ExitCode, Machine: stage.Machine, OS: stage.OS, Arch: stage.Arch, Variant: stage.Variant, Kernel: stage.Kernel, Limit: stage.Limit, LimitRepo: stage.LimitRepo, Started: stage.Started * 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Stopped: stage.Stopped * 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Version: stage.Version, OnSuccess: stage.OnSuccess, OnFailure: stage.OnFailure, DependsOn: stage.DependsOn, Labels: stage.Labels, Steps: ConvertFromDroneSteps(stage.Steps), } } func ConvertFromDroneLine(l *drone.Line) *livelog.Line { return &livelog.Line{ Number: l.Number, Message: l.Message, Timestamp: l.Timestamp, } } func ConvertToDroneBuild(execution *types.Execution) *drone.Build { return &drone.Build{ ID: execution.ID, RepoID: execution.RepoID, Trigger: execution.Trigger, Number: execution.Number, Parent: execution.Parent, Status: string(execution.Status), Error: execution.Error, Event: string(execution.Event), Action: string(execution.Action), Link: execution.Link, Timestamp: execution.Timestamp, Title: execution.Title, Message: execution.Message, Before: execution.Before, After: execution.After, Ref: execution.Ref, Fork: execution.Fork, Source: execution.Source, Target: execution.Target, Author: execution.Author, AuthorName: execution.AuthorName, AuthorEmail: execution.AuthorEmail, AuthorAvatar: execution.AuthorAvatar, Sender: execution.Sender, Params: execution.Params, Cron: execution.Cron, Deploy: execution.Deploy, DeployID: execution.DeployID, Debug: execution.Debug, Started: execution.Started / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Finished: execution.Finished / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Created: execution.Created / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Updated: execution.Updated / 1e3, // Drone uses Unix() timestamps whereas we use UnixMilli() Version: execution.Version, } } func ConvertToDroneRepo(repo *types.Repository, repoIsPublic bool) *drone.Repo { return &drone.Repo{ ID: repo.ID, Trusted: true, // as builds are running on user machines, the repo is marked trusted. UID: repo.Identifier, UserID: repo.CreatedBy, Namespace: repo.Path, Name: repo.Identifier, HTTPURL: repo.GitURL, Link: repo.GitURL, Private: !repoIsPublic, Created: repo.Created, Updated: repo.Updated, Version: repo.Version, Branch: repo.DefaultBranch, // TODO: We can get this from configuration once we start populating it. // If this is not set drone runner cancels the build. Timeout: int64((10 * time.Hour).Seconds()), } } func ConvertToDroneFile(file *file.File) *client.File { return &client.File{ Data: file.Data, } } func ConvertToDroneSecret(secret *types.Secret) *drone.Secret { return &drone.Secret{ Name: secret.Identifier, Data: secret.Data, } } func ConvertToDroneSecrets(secrets []*types.Secret) []*drone.Secret { ret := make([]*drone.Secret, len(secrets)) for i, s := range secrets { ret[i] = ConvertToDroneSecret(s) } return ret } func ConvertToDroneNetrc(netrc *Netrc) *drone.Netrc { if netrc == nil { return nil } return &drone.Netrc{ Machine: netrc.Machine, Login: netrc.Login, Password: netrc.Password, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/teardown.go
app/pipeline/manager/teardown.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "errors" "strings" "time" events "github.com/harness/gitness/app/events/pipeline" "github.com/harness/gitness/app/pipeline/checks" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/livelog" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/hashicorp/go-multierror" "github.com/rs/zerolog/log" ) type teardown struct { Executions store.ExecutionStore Checks store.CheckStore Pipelines store.PipelineStore SSEStreamer sse.Streamer Logs livelog.LogStream Scheduler scheduler.Scheduler Repos store.RepoStore Steps store.StepStore Stages store.StageStore Reporter events.Reporter } //nolint:gocognit // refactor if needed. func (t *teardown) do(ctx context.Context, stage *types.Stage) error { log := log.With(). Int64("stage.id", stage.ID). Logger() log.Debug().Msg("manager: stage is complete. teardown") execution, err := t.Executions.Find(noContext, stage.ExecutionID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find the execution") return err } log = log.With(). Int64("execution.number", execution.Number). Int64("execution.id", execution.ID). Int64("repo.id", execution.RepoID). Str("stage.status", string(stage.Status)). Logger() repo, err := t.Repos.Find(noContext, execution.RepoID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find the repository") return err } for _, step := range stage.Steps { if len(step.Error) > 500 { step.Error = step.Error[:500] } err := t.Steps.Update(noContext, step) //nolint:contextcheck if err != nil { log = log.With(). Str("step.name", step.Name). Int64("step.id", step.ID). Err(err). Logger() log.Error().Msg("manager: cannot persist the step") return err } } if len(stage.Error) > 500 { stage.Error = stage.Error[:500] } err = t.Stages.Update(noContext, stage) //nolint:contextcheck if err != nil { log.Error().Err(err). Msg("manager: cannot update the stage") return err } for _, step := range stage.Steps { err = t.Logs.Delete(noContext, step.ID) //nolint:contextcheck if err != nil && !errors.Is(err, livelog.ErrStreamNotFound) { log.Warn().Err(err).Msgf("failed to delete log stream for step %d", step.ID) } } stages, err := t.Stages.ListWithSteps(noContext, execution.ID) //nolint:contextcheck if err != nil { log.Warn().Err(err). Msg("manager: cannot get stages") return err } err = t.cancelDownstream(ctx, stages) if err != nil { log.Error().Err(err). Msg("manager: cannot cancel downstream builds") return err } err = t.scheduleDownstream(ctx, stages) if err != nil { log.Error().Err(err). Msg("manager: cannot schedule downstream builds") return err } if !isexecutionComplete(stages) { log.Warn().Err(err). Msg("manager: execution pending completion of additional stages") return nil } log.Info().Msg("manager: execution is finished, teardown") execution.Status = enum.CIStatusSuccess execution.Finished = time.Now().UnixMilli() for _, sibling := range stages { if sibling.Status == enum.CIStatusKilled { execution.Status = enum.CIStatusKilled break } if sibling.Status == enum.CIStatusFailure { execution.Status = enum.CIStatusFailure break } if sibling.Status == enum.CIStatusError { execution.Status = enum.CIStatusError break } } if execution.Started == 0 { execution.Started = execution.Finished } err = t.Executions.Update(noContext, execution) //nolint:contextcheck if errors.Is(err, gitness_store.ErrVersionConflict) { log.Warn().Err(err). Msg("manager: execution updated by another goroutine") return nil } if err != nil { log.Warn().Err(err). Msg("manager: cannot update the execution") return err } execution.Stages = stages t.SSEStreamer.Publish(noContext, repo.ParentID, enum.SSETypeExecutionCompleted, execution) //nolint:contextcheck // send pipeline execution status t.reportExecutionCompleted(ctx, execution) pipeline, err := t.Pipelines.Find(ctx, execution.PipelineID) if err != nil { log.Error().Err(err).Msg("manager: cannot find pipeline") return err } // try to write to the checks store - if not, log an error and continue err = checks.Write(ctx, t.Checks, execution, pipeline) if err != nil { log.Error().Err(err).Msg("manager: could not write to checks store") } return nil } // cancelDownstream is a helper function that tests for // downstream stages and cancels them based on the overall // pipeline state. // //nolint:gocognit // refactor if needed func (t *teardown) cancelDownstream( ctx context.Context, stages []*types.Stage, ) error { failed := false for _, s := range stages { // check pipeline state if s.Status.IsFailed() { failed = true } } var errs error for _, s := range stages { if s.Status != enum.CIStatusWaitingOnDeps { continue } var skip bool if failed && !s.OnFailure { skip = true } if !failed && !s.OnSuccess { skip = true } if !skip { continue } if !areDepsComplete(s, stages) { continue } log := log.With(). Int64("stage.id", s.ID). Bool("stage.on_success", s.OnSuccess). Bool("stage.on_failure", s.OnFailure). Bool("failed", failed). Str("stage.depends_on", strings.Join(s.DependsOn, ",")). Logger() log.Debug().Msg("manager: skipping step") s.Status = enum.CIStatusSkipped s.Started = time.Now().UnixMilli() s.Stopped = time.Now().UnixMilli() err := t.Stages.Update(noContext, s) //nolint:contextcheck if errors.Is(err, gitness_store.ErrVersionConflict) { rErr := t.resync(ctx, s) if rErr != nil { log.Warn().Err(rErr).Msg("failed to resync after version conflict") } continue } if err != nil { log.Error().Err(err). Msg("manager: cannot update stage status") errs = multierror.Append(errs, err) } } return errs } func isexecutionComplete(stages []*types.Stage) bool { for _, stage := range stages { if stage.Status == enum.CIStatusPending || stage.Status == enum.CIStatusRunning || stage.Status == enum.CIStatusWaitingOnDeps || stage.Status == enum.CIStatusDeclined || stage.Status == enum.CIStatusBlocked { return false } } return true } func areDepsComplete(stage *types.Stage, stages []*types.Stage) bool { deps := map[string]struct{}{} for _, dep := range stage.DependsOn { deps[dep] = struct{}{} } for _, sibling := range stages { if _, ok := deps[sibling.Name]; !ok { continue } if !sibling.Status.IsDone() { return false } } return true } // scheduleDownstream is a helper function that tests for // downstream stages and schedules stages if all dependencies // and execution requirements are met. func (t *teardown) scheduleDownstream( ctx context.Context, stages []*types.Stage, ) error { var errs error for _, sibling := range stages { if sibling.Status != enum.CIStatusWaitingOnDeps { continue } if len(sibling.DependsOn) == 0 { continue } // PROBLEM: isDep only checks the direct parent // i think .... // if isDep(stage, sibling) == false { // continue // } if !areDepsComplete(sibling, stages) { continue } // if isLastDep(stage, sibling, stages) == false { // continue // } log := log.With(). Int64("stage.id", sibling.ID). Str("stage.name", sibling.Name). Str("stage.depends_on", strings.Join(sibling.DependsOn, ",")). Logger() log.Debug().Msg("manager: schedule next stage") sibling.Status = enum.CIStatusPending err := t.Stages.Update(noContext, sibling) //nolint:contextcheck if errors.Is(err, gitness_store.ErrVersionConflict) { rErr := t.resync(ctx, sibling) if rErr != nil { log.Warn().Err(rErr).Msg("failed to resync after version conflict") } continue } if err != nil { log.Error().Err(err). Msg("manager: cannot update stage status") errs = multierror.Append(errs, err) } err = t.Scheduler.Schedule(noContext, sibling) //nolint:contextcheck if err != nil { log.Error().Err(err). Msg("manager: cannot schedule stage") errs = multierror.Append(errs, err) } } return errs } // resync updates the stage from the database. Note that it does // not update the Version field. This is by design. It prevents // the current go routine from updating a stage that has been // updated by another go routine. func (t *teardown) resync(ctx context.Context, stage *types.Stage) error { updated, err := t.Stages.Find(ctx, stage.ID) if err != nil { return err } stage.Status = updated.Status stage.Error = updated.Error stage.ExitCode = updated.ExitCode stage.Machine = updated.Machine stage.Started = updated.Started stage.Stopped = updated.Stopped return nil } func (t *teardown) reportExecutionCompleted(ctx context.Context, execution *types.Execution) { t.Reporter.Executed(ctx, &events.ExecutedPayload{ PipelineID: execution.PipelineID, RepoID: execution.RepoID, ExecutionNum: execution.Number, Status: execution.Status, }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/setup.go
app/pipeline/manager/setup.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "errors" "time" "github.com/harness/gitness/app/pipeline/checks" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type setup struct { Executions store.ExecutionStore Checks store.CheckStore SSEStreamer sse.Streamer Pipelines store.PipelineStore Repos store.RepoStore Steps store.StepStore Stages store.StageStore Users store.PrincipalStore } func (s *setup) do(ctx context.Context, stage *types.Stage) error { execution, err := s.Executions.Find(noContext, stage.ExecutionID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find the execution") return err } log := log.With(). Int64("execution.number", execution.Number). Int64("execution.id", execution.ID). Int64("stage.id", stage.ID). Int64("repo.id", execution.RepoID). Logger() repo, err := s.Repos.Find(noContext, execution.RepoID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find the repository") return err } if len(stage.Error) > 500 { stage.Error = stage.Error[:500] } err = s.Stages.Update(noContext, stage) //nolint:contextcheck if err != nil { log.Error().Err(err). Str("stage.status", string(stage.Status)). Msg("manager: cannot update the stage") return err } // TODO: create all the steps as part of a single transaction? for _, step := range stage.Steps { if len(step.Error) > 500 { step.Error = step.Error[:500] } err := s.Steps.Create(noContext, step) //nolint:contextcheck if err != nil { log.Error().Err(err). Str("stage.status", string(stage.Status)). Str("step.name", step.Name). Int64("step.id", step.ID). Msg("manager: cannot persist the step") return err } } _, err = s.updateExecution(noContext, execution) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot update the execution") return err } pipeline, err := s.Pipelines.Find(ctx, execution.PipelineID) if err != nil { log.Error().Err(err).Msg("manager: cannot find pipeline") return err } // try to write to the checks store - if not, log an error and continue err = checks.Write(ctx, s.Checks, execution, pipeline) if err != nil { log.Error().Err(err).Msg("manager: could not write to checks store") } stages, err := s.Stages.ListWithSteps(noContext, execution.ID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: could not list stages with steps") return err } execution.Stages = stages s.SSEStreamer.Publish(noContext, repo.ParentID, enum.SSETypeExecutionRunning, execution) //nolint:contextcheck return nil } // helper function that updates the execution status from pending to running. // This accounts for the fact that another agent may have already updated // the execution status, which may happen if two stages execute concurrently. func (s *setup) updateExecution(ctx context.Context, execution *types.Execution) (bool, error) { if execution.Status != enum.CIStatusPending { return false, nil } execution.Started = time.Now().UnixMilli() execution.Status = enum.CIStatusRunning err := s.Executions.Update(ctx, execution) if errors.Is(err, gitness_store.ErrVersionConflict) { return false, nil } if err != nil { return false, err } return true, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/updater.go
app/pipeline/manager/updater.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type updater struct { Executions store.ExecutionStore Repos store.RepoStore SSEStreamer sse.Streamer Steps store.StepStore Stages store.StageStore } func (u *updater) do(ctx context.Context, step *types.Step) error { log := log.Ctx(ctx).With(). Str("step.name", step.Name). Str("step.status", string(step.Status)). Int64("step.id", step.ID). Logger() if len(step.Error) > 500 { step.Error = step.Error[:500] } err := u.Steps.Update(noContext, step) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot update step") return err } stage, err := u.Stages.Find(noContext, step.StageID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find stage") return nil } execution, err := u.Executions.Find(noContext, stage.ExecutionID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find execution") return nil } repo, err := u.Repos.Find(noContext, execution.RepoID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find repo") return nil } stages, err := u.Stages.ListWithSteps(noContext, stage.ExecutionID) //nolint:contextcheck if err != nil { log.Error().Err(err).Msg("manager: cannot find stages") return nil } execution.Stages = stages u.SSEStreamer.Publish(noContext, repo.ParentID, enum.SSETypeExecutionUpdated, execution) //nolint:contextcheck return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/manager/manager.go
app/pipeline/manager/manager.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package manager import ( "context" "errors" "fmt" "io" "net/url" "time" "github.com/harness/gitness/app/bootstrap" events "github.com/harness/gitness/app/events/pipeline" "github.com/harness/gitness/app/jwt" "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/livelog" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( // pipelineJWTLifetime specifies the max lifetime of an ephemeral pipeline jwt token. pipelineJWTLifetime = 72 * time.Hour // pipelineJWTRole specifies the role of an ephemeral pipeline jwt token. pipelineJWTRole = enum.MembershipRoleContributor ) var noContext = context.Background() var _ ExecutionManager = (*Manager)(nil) type ( // Request provides filters when requesting a pending // build from the queue. This allows an agent, for example, // to request a build that matches its architecture and kernel. Request struct { Kind string `json:"kind"` Type string `json:"type"` OS string `json:"os"` Arch string `json:"arch"` Variant string `json:"variant"` Kernel string `json:"kernel"` Labels map[string]string `json:"labels,omitempty"` } // Config represents a pipeline config file. Config struct { Data string `json:"data"` Kind string `json:"kind"` } // Netrc contains login and initialization information used // by an automated login process. Netrc struct { Machine string `json:"machine"` Login string `json:"login"` Password string `json:"password"` } // ExecutionContext represents the minimum amount of information // required by the runner to execute a build. ExecutionContext struct { Repo *types.Repository `json:"repository"` RepoIsPublic bool `json:"repository_is_public,omitempty"` Execution *types.Execution `json:"build"` Stage *types.Stage `json:"stage"` Secrets []*types.Secret `json:"secrets"` Config *file.File `json:"config"` Netrc *Netrc `json:"netrc"` } // ExecutionManager encapsulates complex build operations and provides // a simplified interface for build runners. ExecutionManager interface { // Request requests the next available build stage for execution. Request(ctx context.Context, args *Request) (*types.Stage, error) // Watch watches for build cancellation requests. Watch(ctx context.Context, executionID int64) (bool, error) // Accept accepts the build stage for execution. Accept(ctx context.Context, stage int64, machine string) (*types.Stage, error) // Write writes a line to the build logs. Write(ctx context.Context, step int64, line *livelog.Line) error // Details returns details about stage. Details(ctx context.Context, stageID int64) (*ExecutionContext, error) // UploadLogs uploads the full logs. UploadLogs(ctx context.Context, step int64, r io.Reader) error // BeforeStep signals the build step is about to start. BeforeStep(ctx context.Context, step *types.Step) error // AfterStep signals the build step is complete. AfterStep(ctx context.Context, step *types.Step) error // BeforeStage signals the build stage is about to start. BeforeStage(ctx context.Context, stage *types.Stage) error // AfterStage signals the build stage is complete. AfterStage(ctx context.Context, stage *types.Stage) error } ) // Manager provides a simplified interface to the build runner so that it // can more easily interact with the server. type Manager struct { Executions store.ExecutionStore Config *types.Config FileService file.Service ConverterService converter.Service Pipelines store.PipelineStore urlProvider urlprovider.Provider Checks store.CheckStore // Converter store.ConvertService SSEStreamer sse.Streamer // Globals store.GlobalSecretStore Logs store.LogStore Logz livelog.LogStream // Netrcs store.NetrcService Repos store.RepoStore Scheduler scheduler.Scheduler Secrets store.SecretStore // Status store.StatusService Stages store.StageStore Steps store.StepStore // System *store.System Users store.PrincipalStore // Webhook store.WebhookSender publicAccess publicaccess.Service // events reporter reporter events.Reporter } func New( config *types.Config, executionStore store.ExecutionStore, pipelineStore store.PipelineStore, urlProvider urlprovider.Provider, sseStreamer sse.Streamer, fileService file.Service, converterService converter.Service, logStore store.LogStore, logStream livelog.LogStream, checkStore store.CheckStore, repoStore store.RepoStore, scheduler scheduler.Scheduler, secretStore store.SecretStore, stageStore store.StageStore, stepStore store.StepStore, userStore store.PrincipalStore, publicAccess publicaccess.Service, reporter events.Reporter, ) *Manager { return &Manager{ Config: config, Executions: executionStore, Pipelines: pipelineStore, urlProvider: urlProvider, SSEStreamer: sseStreamer, FileService: fileService, ConverterService: converterService, Logs: logStore, Logz: logStream, Checks: checkStore, Repos: repoStore, Scheduler: scheduler, Secrets: secretStore, Stages: stageStore, Steps: stepStore, Users: userStore, publicAccess: publicAccess, reporter: reporter, } } // Request requests the next available build stage for execution. func (m *Manager) Request(ctx context.Context, args *Request) (*types.Stage, error) { log := log.With(). Str("kind", args.Kind). Str("type", args.Type). Str("os", args.OS). Str("arch", args.Arch). Str("kernel", args.Kernel). Str("variant", args.Variant). Logger() log.Debug().Msg("manager: request queue item") stage, err := m.Scheduler.Request(ctx, scheduler.Filter{ Kind: args.Kind, Type: args.Type, OS: args.OS, Arch: args.Arch, Kernel: args.Kernel, Variant: args.Variant, Labels: args.Labels, }) if err != nil && ctx.Err() != nil { log.Debug().Err(err).Msg("manager: context canceled") return nil, err } if err != nil { log.Warn().Err(err).Msg("manager: request queue item error") return nil, err } return stage, nil } // Accept accepts the build stage for execution. It is possible for multiple // agents to pull the same stage from the queue. func (m *Manager) Accept(_ context.Context, id int64, machine string) (*types.Stage, error) { log := log.With(). Int64("stage-id", id). Str("machine", machine). Logger() log.Debug().Msg("manager: accept stage") stage, err := m.Stages.Find(noContext, id) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot find stage") return nil, err } if stage.Machine != "" { log.Debug().Msg("manager: stage already assigned. abort.") return nil, fmt.Errorf("stage already assigned, abort") } stage.Machine = machine stage.Status = enum.CIStatusPending err = m.Stages.Update(noContext, stage) //nolint:contextcheck switch { case errors.Is(err, gitness_store.ErrVersionConflict): log.Debug().Err(err).Msg("manager: stage processed by another agent") case err != nil: log.Debug().Err(err).Msg("manager: cannot update stage") default: log.Info().Msg("manager: stage accepted") } return stage, err } // Write writes a line to the build logs. func (m *Manager) Write(ctx context.Context, step int64, line *livelog.Line) error { err := m.Logz.Write(ctx, step, line) if err != nil { log.Warn().Int64("step-id", step).Err(err).Msg("manager: cannot write to log stream") return err } return nil } // UploadLogs uploads the full logs. func (m *Manager) UploadLogs(ctx context.Context, step int64, r io.Reader) error { err := m.Logs.Create(ctx, step, r) if err != nil { log.Error().Err(err).Int64("step-id", step).Msg("manager: cannot upload complete logs") return err } return nil } // Details provides details about the stage. func (m *Manager) Details(ctx context.Context, stageID int64) (*ExecutionContext, error) { log := log.With().Ctx(ctx). Int64("stage-id", stageID). Logger() log.Debug().Msg("manager: fetching stage details") //nolint:contextcheck stage, err := m.Stages.Find(noContext, stageID) if err != nil { log.Warn().Err(err).Msg("manager: cannot find stage") return nil, err } execution, err := m.Executions.Find(noContext, stage.ExecutionID) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot find build") return nil, err } pipeline, err := m.Pipelines.Find(noContext, execution.PipelineID) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot find pipeline") return nil, err } repo, err := m.Repos.Find(noContext, execution.RepoID) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot find repo") return nil, err } // Backfill clone URL repo.GitURL = m.urlProvider.GenerateContainerGITCloneURL(ctx, repo.Path) //nolint:contextcheck stages, err := m.Stages.List(noContext, stage.ExecutionID) if err != nil { log.Warn().Err(err).Msg("manager: cannot list stages") return nil, err } execution.Stages = stages log = log.With(). Int64("build", execution.Number). Str("repo", repo.GetGitUID()). Logger() // TODO: Currently we fetch all the secrets from the same space. // This logic can be updated when needed. secrets, err := m.Secrets.ListAll(noContext, repo.ParentID) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot list secrets") return nil, err } // Fetch contents of YAML from the execution ref at the pipeline config path. file, err := m.FileService.Get(noContext, repo, pipeline.ConfigPath, execution.After) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot fetch file") return nil, err } // Get public access settings of the repo //nolint:contextcheck repoIsPublic, err := m.publicAccess.Get(noContext, enum.PublicResourceTypeRepo, repo.Path) if err != nil { log.Warn().Err(err).Msg("manager: cannot check if repo is public") return nil, err } // Convert file contents in case templates are being used. args := &converter.ConvertArgs{ Repo: repo, Pipeline: pipeline, Execution: execution, File: file, RepoIsPublic: repoIsPublic, } file, err = m.ConverterService.Convert(noContext, args) //nolint:contextcheck if err != nil { log.Warn().Err(err).Msg("manager: cannot convert template contents") return nil, err } netrc, err := m.createNetrc(repo) if err != nil { log.Warn().Err(err).Msg("manager: failed to create netrc") return nil, err } return &ExecutionContext{ Repo: repo, RepoIsPublic: repoIsPublic, Execution: execution, Stage: stage, Secrets: secrets, Config: file, Netrc: netrc, }, nil } func (m *Manager) createNetrc(repo *types.Repository) (*Netrc, error) { pipelinePrincipal := bootstrap.NewPipelineServiceSession().Principal jwt, err := jwt.GenerateWithMembership( pipelinePrincipal.ID, repo.ParentID, pipelineJWTRole, pipelineJWTLifetime, pipelinePrincipal.Salt, ) if err != nil { return nil, fmt.Errorf("failed to create jwt: %w", err) } cloneURL, err := url.Parse(repo.GitURL) if err != nil { return nil, fmt.Errorf("failed to parse clone url '%s': %w", cloneURL, err) } return &Netrc{ Machine: cloneURL.Hostname(), Login: pipelinePrincipal.UID, Password: jwt, }, nil } // Before signals the build step is about to start. func (m *Manager) BeforeStep(_ context.Context, step *types.Step) error { log := log.With(). Str("step.status", string(step.Status)). Str("step.name", step.Name). Int64("step.id", step.ID). Logger() log.Debug().Msg("manager: updating step status") //nolint:contextcheck err := m.Logz.Create(noContext, step.ID) if err != nil { log.Warn().Err(err).Msg("manager: cannot create log stream") return err } updater := &updater{ Executions: m.Executions, SSEStreamer: m.SSEStreamer, Repos: m.Repos, Steps: m.Steps, Stages: m.Stages, } //nolint:contextcheck return updater.do(noContext, step) } // After signals the build step is complete. func (m *Manager) AfterStep(_ context.Context, step *types.Step) error { log := log.With(). Str("step.status", string(step.Status)). Str("step.name", step.Name). Int64("step.id", step.ID). Logger() log.Debug().Msg("manager: updating step status") var retErr error updater := &updater{ Executions: m.Executions, SSEStreamer: m.SSEStreamer, Repos: m.Repos, Steps: m.Steps, Stages: m.Stages, } //nolint:contextcheck if err := updater.do(noContext, step); err != nil { retErr = err log.Warn().Err(err).Msg("manager: cannot update step") } //nolint:contextcheck if err := m.Logz.Delete(noContext, step.ID); err != nil && !errors.Is(err, livelog.ErrStreamNotFound) { log.Warn().Err(err).Msg("manager: cannot teardown log stream") } return retErr } // BeforeAll signals the build stage is about to start. func (m *Manager) BeforeStage(_ context.Context, stage *types.Stage) error { s := &setup{ Executions: m.Executions, Checks: m.Checks, Pipelines: m.Pipelines, SSEStreamer: m.SSEStreamer, Repos: m.Repos, Steps: m.Steps, Stages: m.Stages, Users: m.Users, } //nolint:contextcheck return s.do(noContext, stage) } // AfterAll signals the build stage is complete. func (m *Manager) AfterStage(_ context.Context, stage *types.Stage) error { t := &teardown{ Executions: m.Executions, Pipelines: m.Pipelines, Checks: m.Checks, SSEStreamer: m.SSEStreamer, Logs: m.Logz, Repos: m.Repos, Scheduler: m.Scheduler, Steps: m.Steps, Stages: m.Stages, Reporter: m.reporter, } return t.do(noContext, stage) //nolint:contextcheck } // Watch watches for build cancellation requests. func (m *Manager) Watch(ctx context.Context, executionID int64) (bool, error) { ok, err := m.Scheduler.Cancelled(ctx, executionID) // we expect a context cancel error here which // indicates a polling timeout. The subscribing // client should look for the context cancel error // and resume polling. if err != nil { return ok, err } // // TODO: we should be able to return // // immediately if Cancelled returns true. This requires // // some more testing but would avoid the extra database // // call. // if ok { // return ok, err // } // if no error is returned we should check // the database to see if the build is complete. If // complete, return true. execution, err := m.Executions.Find(ctx, executionID) if err != nil { log := log.With(). Int64("execution.id", executionID). Logger() log.Warn().Msg("manager: cannot find build") return ok, fmt.Errorf("could not find build for cancellation: %w", err) } return execution.Status.IsDone(), nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/scheduler/wire.go
app/pipeline/scheduler/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scheduler import ( "github.com/harness/gitness/app/store" "github.com/harness/gitness/lock" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideScheduler, ) // ProvideScheduler provides a scheduler which can be used to schedule and request builds. func ProvideScheduler( stageStore store.StageStore, lock lock.MutexManager, ) (Scheduler, error) { return newScheduler(stageStore, lock) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/scheduler/canceler.go
app/pipeline/scheduler/canceler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scheduler import ( "context" "sync" "time" ) type canceler struct { sync.Mutex subscribers map[chan struct{}]int64 cancelled map[int64]time.Time } func newCanceler() *canceler { return &canceler{ subscribers: make(map[chan struct{}]int64), cancelled: make(map[int64]time.Time), } } func (c *canceler) Cancel(_ context.Context, id int64) error { c.Lock() defer c.Unlock() c.cancelled[id] = time.Now().Add(time.Minute * 5) for subscriber, build := range c.subscribers { if id == build { close(subscriber) } } c.collect() return nil } func (c *canceler) Cancelled(ctx context.Context, id int64) (bool, error) { subscriber := make(chan struct{}) c.Lock() c.subscribers[subscriber] = id c.Unlock() defer func() { c.Lock() delete(c.subscribers, subscriber) c.Unlock() }() for { select { case <-ctx.Done(): return false, ctx.Err() case <-time.After(time.Minute): c.Lock() _, ok := c.cancelled[id] c.Unlock() if ok { return true, nil } case <-subscriber: return true, nil } } } func (c *canceler) collect() { // the list of cancelled builds is stored with a ttl, and // is not removed until the ttl is reached. This provides // adequate window for clients with connectivity issues to // reconnect and receive notification of cancel events. now := time.Now() for build, timestamp := range c.cancelled { if now.After(timestamp) { delete(c.cancelled, build) } } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/scheduler/scheduler.go
app/pipeline/scheduler/scheduler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scheduler import ( "context" "github.com/harness/gitness/app/store" "github.com/harness/gitness/lock" "github.com/harness/gitness/types" ) // Filter provides filter criteria to limit stages requested // from the scheduler. type Filter struct { Kind string Type string OS string Arch string Kernel string Variant string Labels map[string]string } // Scheduler schedules Build stages for execution. type Scheduler interface { // Schedule schedules the stage for execution. Schedule(ctx context.Context, stage *types.Stage) error // Request requests the next stage scheduled for execution. Request(ctx context.Context, filter Filter) (*types.Stage, error) // Cancel cancels scheduled or running jobs associated // with the parent build ID. Cancel(context.Context, int64) error // Cancelled blocks and listens for a cancellation event and // returns true if the build has been cancelled. Cancelled(context.Context, int64) (bool, error) } type scheduler struct { *queue *canceler } // newScheduler provides an instance of a scheduler with cancel abilities. func newScheduler(stageStore store.StageStore, lock lock.MutexManager) (Scheduler, error) { q, err := newQueue(stageStore, lock) if err != nil { return nil, err } return scheduler{ q, newCanceler(), }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/scheduler/queue.go
app/pipeline/scheduler/queue.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scheduler import ( "context" "sync" "time" "github.com/harness/gitness/app/store" "github.com/harness/gitness/lock" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type queue struct { sync.Mutex globMx lock.Mutex ready chan struct{} paused bool interval time.Duration store store.StageStore workers map[*worker]struct{} ctx context.Context } // newQueue returns a new Queue backed by the build datastore. func newQueue(store store.StageStore, lock lock.MutexManager) (*queue, error) { const lockKey = "build_queue" mx, err := lock.NewMutex(lockKey) if err != nil { return nil, err } q := &queue{ store: store, globMx: mx, ready: make(chan struct{}, 1), workers: map[*worker]struct{}{}, interval: time.Minute, ctx: context.Background(), } go func() { if err := q.start(); err != nil { log.Err(err).Msg("queue start failed") } }() return q, nil } func (q *queue) Schedule(_ context.Context, _ *types.Stage) error { select { case q.ready <- struct{}{}: default: } return nil } func (q *queue) Pause(_ context.Context) error { q.Lock() q.paused = true q.Unlock() return nil } func (q *queue) Request(ctx context.Context, params Filter) (*types.Stage, error) { w := &worker{ kind: params.Kind, typ: params.Type, os: params.OS, arch: params.Arch, kernel: params.Kernel, variant: params.Variant, labels: params.Labels, channel: make(chan *types.Stage), done: ctx.Done(), } q.Lock() q.workers[w] = struct{}{} q.Unlock() select { case q.ready <- struct{}{}: default: } select { case <-ctx.Done(): return nil, ctx.Err() case b := <-w.channel: return b, nil } } //nolint:gocognit // refactor if needed. func (q *queue) signal(ctx context.Context) error { if err := q.globMx.Lock(ctx); err != nil { return err } defer func() { if err := q.globMx.Unlock(ctx); err != nil { log.Ctx(ctx).Err(err).Msg("failed to release global lock after signaling") } }() q.Lock() count := len(q.workers) pause := q.paused q.Unlock() if pause { return nil } if count == 0 { return nil } items, err := q.store.ListIncomplete(ctx) if err != nil { return err } q.Lock() defer q.Unlock() for _, item := range items { if item.Status == enum.CIStatusRunning { continue } if item.Machine != "" { continue } // if the stage defines concurrency limits we // need to make sure those limits are not exceeded // before proceeding. if !withinLimits(item, items) { continue } // if the system defines concurrency limits // per repository we need to make sure those limits // are not exceeded before proceeding. if shouldThrottle(item, items, item.LimitRepo) { continue } loop: for w := range q.workers { // the worker must match the resource kind and type if !matchResource(w.kind, w.typ, item.Kind, item.Type) { continue } if w.os != "" || w.arch != "" || w.variant != "" || w.kernel != "" { // the worker is platform-specific. check to ensure // the queue item matches the worker platform. if w.os != item.OS { continue } if w.arch != item.Arch { continue } // if the pipeline defines a variant it must match // the worker variant (e.g. arm6, arm7, etc). if item.Variant != "" && item.Variant != w.variant { continue } // if the pipeline defines a kernel version it must match // the worker kernel version (e.g. 1709, 1803). if item.Kernel != "" && item.Kernel != w.kernel { continue } } if len(item.Labels) > 0 || len(w.labels) > 0 { if !checkLabels(item.Labels, w.labels) { continue } } select { case w.channel <- item: case <-w.done: } delete(q.workers, w) break loop } } return nil } func (q *queue) start() error { for { select { case <-q.ctx.Done(): return q.ctx.Err() case <-q.ready: if err := q.signal(q.ctx); err != nil { // don't return, only log error log.Ctx(q.ctx).Err(err).Msg("failed to signal on ready") } case <-time.After(q.interval): if err := q.signal(q.ctx); err != nil { // don't return, only log error log.Ctx(q.ctx).Err(err).Msg("failed to signal on interval") } } } } type worker struct { kind string typ string os string arch string kernel string variant string labels map[string]string channel chan *types.Stage done <-chan struct{} } func checkLabels(a, b map[string]string) bool { if len(a) != len(b) { return false } for k, v := range a { if w, ok := b[k]; !ok || v != w { return false } } return true } func withinLimits(stage *types.Stage, siblings []*types.Stage) bool { if stage.Limit == 0 { return true } count := 0 for _, sibling := range siblings { if sibling.RepoID != stage.RepoID { continue } if sibling.ID == stage.ID { continue } if sibling.Name != stage.Name { continue } if sibling.ID < stage.ID || sibling.Status == enum.CIStatusRunning { count++ } } return count < stage.Limit } func shouldThrottle(stage *types.Stage, siblings []*types.Stage, limit int) bool { // if no throttle limit is defined (default) then // return false to indicate no throttling is needed. if limit == 0 { return false } // if the repository is running it is too late // to skip and we can exit if stage.Status == enum.CIStatusRunning { return false } count := 0 // loop through running stages to count number of // running stages for the parent repository. for _, sibling := range siblings { // ignore stages from other repository. if sibling.RepoID != stage.RepoID { continue } // ignore this stage and stages that were // scheduled after this stage. if sibling.ID >= stage.ID { continue } count++ } // if the count of running stages exceeds the // throttle limit return true. return count >= limit } // matchResource is a helper function that returns. func matchResource(kinda, typea, kindb, typeb string) bool { if kinda == "" { kinda = "pipeline" } if kindb == "" { kindb = "pipeline" } if typea == "" { typea = "docker" } if typeb == "" { typeb = "docker" } return kinda == kindb && typea == typeb }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/resolver/wire.go
app/pipeline/resolver/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resolver import ( "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideResolver, ) // ProvideResolver provides a resolver which can resolve templates and plugins. func ProvideResolver( config *types.Config, pluginStore store.PluginStore, templateStore store.TemplateStore, executionStore store.ExecutionStore, repoStore store.RepoStore, ) *Manager { return NewManager(config, pluginStore, templateStore, executionStore, repoStore) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/resolver/resolve.go
app/pipeline/resolver/resolve.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resolver import ( "context" "fmt" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types/enum" v1yaml "github.com/drone/spec/dist/go" "github.com/drone/spec/dist/go/parse" ) // Resolve returns a resolve function which resolves plugins and templates. // It searches for plugins globally and for templates in the same space and substitutes // them in the pipeline yaml. func Resolve( ctx context.Context, pluginStore store.PluginStore, templateStore store.TemplateStore, spaceID int64, ) func(name, kind, typ, version string) (*v1yaml.Config, error) { return func(name, kind, typ, version string) (*v1yaml.Config, error) { k, err := enum.ParseResolverKind(kind) if err != nil { return nil, err } t, err := enum.ParseResolverType(typ) if err != nil { return nil, err } if k == enum.ResolverKindPlugin && t != enum.ResolverTypeStep { return nil, fmt.Errorf("only step level plugins are currently supported") } if k == enum.ResolverKindPlugin { plugin, err := pluginStore.Find(ctx, name, version) if err != nil { return nil, fmt.Errorf("could not lookup plugin: %w", err) } // Convert plugin to v1yaml spec config, err := parse.ParseString(plugin.Spec) if err != nil { return nil, fmt.Errorf("could not unmarshal plugin to v1yaml spec: %w", err) } return config, nil } // Search for templates in the space template, err := templateStore.FindByIdentifierAndType(ctx, spaceID, name, t) if err != nil { return nil, fmt.Errorf("could not find template: %w", err) } // Try to parse the template into v1 yaml config, err := parse.ParseString(template.Data) if err != nil { return nil, fmt.Errorf("could not unmarshal template to v1yaml spec: %w", err) } return config, nil } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/resolver/manager.go
app/pipeline/resolver/manager.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resolver import ( "archive/zip" "bytes" "context" "fmt" "io" "net/http" "os" "path/filepath" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" v1yaml "github.com/drone/spec/dist/go" "github.com/drone/spec/dist/go/parse" "github.com/rs/zerolog/log" ) // Lookup returns a resource by name, kind and type. It also sends in the // execution ID. type LookupFunc func(name, kind, typ, version string, id int64) (*v1yaml.Config, error) type Manager struct { config *types.Config pluginStore store.PluginStore templateStore store.TemplateStore executionStore store.ExecutionStore repoStore store.RepoStore } func NewManager( config *types.Config, pluginStore store.PluginStore, templateStore store.TemplateStore, executionStore store.ExecutionStore, repoStore store.RepoStore, ) *Manager { return &Manager{ config: config, pluginStore: pluginStore, templateStore: templateStore, executionStore: executionStore, repoStore: repoStore, } } // GetLookupFn returns a lookup function for plugins and templates which can be used in the resolver // passed to the drone runner. // //nolint:gocognit func (m *Manager) GetLookupFn() LookupFunc { noContext := context.Background() return func(name, kind, typ, version string, executionID int64) (*v1yaml.Config, error) { // Find space ID corresponding to the executionID execution, err := m.executionStore.Find(noContext, executionID) if err != nil { return nil, fmt.Errorf("could not find relevant execution: %w", err) } // Find the repo so we know in which space templates should be searched repo, err := m.repoStore.Find(noContext, execution.RepoID) if err != nil { return nil, fmt.Errorf("could not find relevant repo: %w", err) } f := Resolve(noContext, m.pluginStore, m.templateStore, repo.ParentID) return f(name, kind, typ, version) } } // Populate fetches plugins information from an external source or a local zip // and populates in the DB. func (m *Manager) Populate(ctx context.Context) error { pluginsURL := m.config.CI.PluginsZipURL if pluginsURL == "" { return fmt.Errorf("plugins url not provided to read schemas from") } var zipFile *zip.ReadCloser if _, err := os.Stat(pluginsURL); err != nil { // local path doesn't exist - must be a remote link // Download zip file locally f, err := os.CreateTemp(os.TempDir(), "plugins.zip") if err != nil { return fmt.Errorf("could not create temp file: %w", err) } defer os.Remove(f.Name()) err = downloadZip(ctx, pluginsURL, f.Name()) if err != nil { return fmt.Errorf("could not download remote zip: %w", err) } pluginsURL = f.Name() } // open up a zip reader for the file zipFile, err := zip.OpenReader(pluginsURL) if err != nil { return fmt.Errorf("could not open zip for reading: %w", err) } defer zipFile.Close() // upsert any new plugins. err = m.traverseAndUpsertPlugins(ctx, zipFile) if err != nil { return fmt.Errorf("could not upsert plugins: %w", err) } return nil } // downloadZip is a helper function that downloads a zip from a URL and // writes it to a path in the local filesystem. // //nolint:gosec // URL is coming from environment variable (user configured it) func downloadZip(ctx context.Context, pluginURL, path string) error { request, err := http.NewRequestWithContext(ctx, http.MethodGet, pluginURL, nil) if err != nil { return fmt.Errorf("failed to create request: %w", err) } response, err := http.DefaultClient.Do(request) if err != nil { return fmt.Errorf("could not get zip from url: %w", err) } // ensure the body is closed after we read (independent of status code or error) if response != nil && response.Body != nil { // Use function to satisfy the linter which complains about unhandled errors otherwise defer func() { _ = response.Body.Close() }() } // Create the file on the local FS. If it exists, it will be truncated. output, err := os.Create(path) if err != nil { return fmt.Errorf("could not create output file: %w", err) } defer output.Close() // Copy the zip output to the file. _, err = io.Copy(output, response.Body) if err != nil { return fmt.Errorf("could not copy response body output to file: %w", err) } return nil } // traverseAndUpsertPlugins traverses through the zip and upserts plugins into the database // if they are not present. // //nolint:gocognit // refactor if needed. func (m *Manager) traverseAndUpsertPlugins(ctx context.Context, rc *zip.ReadCloser) error { plugins, err := m.pluginStore.ListAll(ctx) if err != nil { return fmt.Errorf("could not list plugins: %w", err) } // Put the plugins in a map so we don't have to perform frequent DB queries. pluginMap := map[string]*types.Plugin{} for _, p := range plugins { pluginMap[p.Identifier] = p } cnt := 0 for _, file := range rc.File { matched, err := filepath.Match("**/plugins/*/*.yaml", file.Name) if err != nil { // only returns BadPattern error which shouldn't happen return fmt.Errorf("could not glob pattern: %w", err) } if !matched { continue } fc, err := file.Open() if err != nil { log.Warn().Err(err).Str("name", file.Name).Msg("could not open file") continue } defer fc.Close() var buf bytes.Buffer _, err = io.Copy(&buf, fc) //nolint:gosec // plugin source is configured via environment variables by user if err != nil { log.Warn().Err(err).Str("name", file.Name).Msg("could not read file contents") continue } // schema should be a valid config - if not log an error and continue. config, err := parse.ParseBytes(buf.Bytes()) if err != nil { log.Warn().Err(err).Str("name", file.Name).Msg("could not parse schema into valid config") continue } var desc string switch vv := config.Spec.(type) { case *v1yaml.PluginStep: desc = vv.Description case *v1yaml.PluginStage: desc = vv.Description default: log.Warn().Str("name", file.Name).Msg("schema did not match a valid plugin schema") continue } plugin := &types.Plugin{ Description: desc, Identifier: config.Name, Type: config.Type, Spec: buf.String(), } // Try to read the logo if it exists in the same directory dir := filepath.Dir(file.Name) logoFile := filepath.Join(dir, "logo.svg") if lf, err := rc.Open(logoFile); err == nil { // if we can open the logo file var lbuf bytes.Buffer _, err = io.Copy(&lbuf, lf) if err != nil { log.Warn().Err(err).Str("name", file.Name).Msg("could not copy logo file") } else { plugin.Logo = lbuf.String() } } // If plugin already exists in the database, skip upsert if p, ok := pluginMap[plugin.Identifier]; ok { if p.Matches(plugin) { continue } } // If plugin name exists with a different spec, call update - otherwise call create. // TODO: Once we start using versions, we can think of whether we want to // keep different schemas for each version in the database. For now, we will // simply overwrite the existing version with the new version. if _, ok := pluginMap[plugin.Identifier]; ok { err = m.pluginStore.Update(ctx, plugin) if err != nil { log.Warn().Str("name", file.Name).Err(err).Msg("could not update plugin") continue } log.Info().Str("name", file.Name).Msg("detected changes: updated existing plugin entry") } else { err = m.pluginStore.Create(ctx, plugin) if err != nil { log.Warn().Str("name", file.Name).Err(err).Msg("could not create plugin in DB") continue } cnt++ } } log.Info().Msgf("added %d new entries to plugins", cnt) return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/runner/wire.go
app/pipeline/runner/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package runner import ( "github.com/harness/gitness/app/pipeline/resolver" "github.com/harness/gitness/types" runtime2 "github.com/drone-runners/drone-runner-docker/engine2/runtime" runnerclient "github.com/drone/runner-go/client" "github.com/drone/runner-go/poller" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideExecutionRunner, ProvideExecutionPoller, ) // ProvideExecutionRunner provides an execution runner. func ProvideExecutionRunner( config *types.Config, client runnerclient.Client, resolver *resolver.Manager, ) (*runtime2.Runner, error) { return NewExecutionRunner(config, client, resolver) } // ProvideExecutionPoller provides a poller which can poll the manager // for new builds and execute them. func ProvideExecutionPoller( runner *runtime2.Runner, client runnerclient.Client, ) *poller.Poller { return NewExecutionPoller(runner, client) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/runner/runner.go
app/pipeline/runner/runner.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package runner import ( goruntime "runtime" "github.com/harness/gitness/app/pipeline/resolver" "github.com/harness/gitness/types" dockerclient "github.com/docker/docker/client" "github.com/drone-runners/drone-runner-docker/engine" "github.com/drone-runners/drone-runner-docker/engine/compiler" "github.com/drone-runners/drone-runner-docker/engine/linter" "github.com/drone-runners/drone-runner-docker/engine/resource" compiler2 "github.com/drone-runners/drone-runner-docker/engine2/compiler" engine2 "github.com/drone-runners/drone-runner-docker/engine2/engine" runtime2 "github.com/drone-runners/drone-runner-docker/engine2/runtime" "github.com/drone/drone-go/drone" runnerclient "github.com/drone/runner-go/client" "github.com/drone/runner-go/environ/provider" "github.com/drone/runner-go/pipeline/reporter/history" "github.com/drone/runner-go/pipeline/reporter/remote" "github.com/drone/runner-go/pipeline/runtime" "github.com/drone/runner-go/pipeline/uploader" "github.com/drone/runner-go/registry" "github.com/drone/runner-go/secret" ) // Privileged provides a list of plugins that execute // with privileged capabilities in order to run Docker // in Docker. var Privileged = []string{ "plugins/docker", "plugins/acr", "plugins/ecr", "plugins/gcr", "plugins/heroku", } // dockerOpts returns back the options to be overridden from docker options set // in the environment. If values are specified in Harness, they get preference. func dockerOpts(config *types.Config) []dockerclient.Opt { var overrides []dockerclient.Opt if config.Docker.Host != "" { overrides = append(overrides, dockerclient.WithHost(config.Docker.Host)) } if config.Docker.APIVersion != "" { overrides = append(overrides, dockerclient.WithVersion(config.Docker.APIVersion)) } return overrides } func NewExecutionRunner( config *types.Config, client runnerclient.Client, resolver *resolver.Manager, ) (*runtime2.Runner, error) { // For linux/windows, containers need to have extra hosts set in order to interact with // Harness. For docker desktop for mac, this is built in and not needed. extraHosts := []string{} if goruntime.GOOS != "darwin" { extraHosts = []string{"host.docker.internal:host-gateway"} } compiler := &compiler.Compiler{ Environ: provider.Static(map[string]string{}), Registry: registry.Static([]*drone.Registry{}), Secret: secret.Encrypted(), ExtraHosts: extraHosts, Privileged: Privileged, Networks: config.CI.ContainerNetworks, } remote := remote.New(client) upload := uploader.New(client) tracer := history.New(remote) engine, err := engine.NewEnv(engine.Opts{}, dockerOpts(config)...) if err != nil { return nil, err } exec := runtime.NewExecer(tracer, remote, upload, engine, int64(config.CI.ParallelWorkers)) legacyRunner := &runtime.Runner{ Machine: config.InstanceID, Client: client, Reporter: tracer, Lookup: resource.Lookup, Lint: linter.New().Lint, Compiler: compiler, Exec: exec.Exec, } engine2, err := engine2.NewEnv(engine2.Opts{}, dockerOpts(config)...) if err != nil { return nil, err } exec2 := runtime2.NewExecer(tracer, remote, upload, engine2, int64(config.CI.ParallelWorkers)) compiler2 := &compiler2.CompilerImpl{ Environ: provider.Static(map[string]string{}), Registry: registry.Static([]*drone.Registry{}), Secret: secret.Encrypted(), ExtraHosts: extraHosts, Privileged: Privileged, Networks: config.CI.ContainerNetworks, } runner := &runtime2.Runner{ Machine: config.InstanceID, Client: client, Resolver: resolver.GetLookupFn(), Reporter: tracer, Compiler: compiler2, Exec: exec2.Exec, LegacyRunner: legacyRunner, } return runner, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/runner/poller.go
app/pipeline/runner/poller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package runner import ( "context" "fmt" "runtime/debug" "github.com/harness/gitness/app/pipeline/logger" "github.com/drone-runners/drone-runner-docker/engine/resource" runtime2 "github.com/drone-runners/drone-runner-docker/engine2/runtime" "github.com/drone/drone-go/drone" runnerclient "github.com/drone/runner-go/client" "github.com/drone/runner-go/poller" "github.com/rs/zerolog/log" ) func NewExecutionPoller( runner *runtime2.Runner, client runnerclient.Client, ) *poller.Poller { runWithRecovery := func(ctx context.Context, stage *drone.Stage) (err error) { ctx = logger.WithUnwrappedZerolog(ctx) defer func() { if r := recover(); r != nil { err = fmt.Errorf("panic received: %s", debug.Stack()) } // the caller of this method (poller.Poller) discards the error - log it here if err != nil { log.Ctx(ctx).Error().Err(err).Msgf("An error occurred while calling runner.Run in Poller") } }() return runner.Run(ctx, stage) } return &poller.Poller{ Client: client, Dispatch: runWithRecovery, Filter: &runnerclient.Filter{ Kind: resource.Kind, Type: resource.Type, // TODO: Check if other parameters are needed. }, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/wire.go
app/pipeline/converter/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package converter import ( "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/services/publicaccess" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideService, ) // ProvideService provides a service which can convert templates. func ProvideService(fileService file.Service, publicAccess publicaccess.Service) Service { return newConverter(fileService, publicAccess) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/service.go
app/pipeline/converter/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package converter import ( "context" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/types" ) type ( // ConvertArgs represents a request to the pipeline // conversion service. ConvertArgs struct { Repo *types.Repository `json:"repository,omitempty"` RepoIsPublic bool `json:"repo_is_public,omitempty"` Pipeline *types.Pipeline `json:"pipeline,omitempty"` Execution *types.Execution `json:"execution,omitempty"` File *file.File `json:"config,omitempty"` } // Service converts a file which is in starlark/jsonnet form by looking // at the extension and calling the appropriate parser. Service interface { Convert(ctx context.Context, args *ConvertArgs) (*file.File, error) } )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/converter.go
app/pipeline/converter/converter.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package converter import ( "context" "strings" "github.com/harness/gitness/app/pipeline/converter/jsonnet" "github.com/harness/gitness/app/pipeline/converter/starlark" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/types/enum" ) const ( jsonnetImportLimit = 1000 starlarkStepLimit = 50000 starlarkSizeLimit = 1000000 ) type converter struct { fileService file.Service publicAccess publicaccess.Service } func newConverter(fileService file.Service, publicAccess publicaccess.Service) Service { return &converter{ fileService: fileService, publicAccess: publicAccess, } } func (c *converter) Convert(ctx context.Context, args *ConvertArgs) (*file.File, error) { path := args.Pipeline.ConfigPath // get public access visibility of the repo repoIsPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, args.Repo.Path) if err != nil { return nil, err } if isJSONNet(path) { str, err := jsonnet.Parse( args.Repo, repoIsPublic, args.Pipeline, args.Execution, args.File, c.fileService, jsonnetImportLimit, ) if err != nil { return nil, err } return &file.File{Data: []byte(str)}, nil } else if isStarlark(path) { str, err := starlark.Parse( args.Repo, repoIsPublic, args.Pipeline, args.Execution, args.File, starlarkStepLimit, starlarkSizeLimit, ) if err != nil { return nil, err } return &file.File{Data: []byte(str)}, nil } return args.File, nil } func isJSONNet(path string) bool { return strings.HasSuffix(path, ".drone.jsonnet") } func isStarlark(path string) bool { return strings.HasSuffix(path, ".drone.script") || strings.HasSuffix(path, ".drone.star") || strings.HasSuffix(path, ".drone.starlark") }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/jsonnet/jsonnet.go
app/pipeline/converter/jsonnet/jsonnet.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jsonnet import ( "bytes" "context" "errors" "fmt" "path" "strconv" "strings" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/types" "github.com/google/go-jsonnet" ) const repo = "repo." const build = "build." const param = "param." var noContext = context.Background() type importer struct { repo *types.Repository execution *types.Execution // jsonnet does not cache file imports and may request // the same file multiple times. We cache the files to // duplicate API calls. cache map[string]jsonnet.Contents // limit the number of outbound requests. github limits // the number of api requests per hour, so we should // make sure that a single build does not abuse the api // by importing dozens of files. limit int // counts the number of outbound requests. if the count // exceeds the limit, the importer will return errors. count int fileService file.Service } func (i *importer) Import(importedFrom, importedPath string) (contents jsonnet.Contents, foundAt string, err error) { if i.cache == nil { i.cache = map[string]jsonnet.Contents{} } // the import is relative to the imported from path. the // imported path must resolve to a filepath relative to // the root of the repository. importedPath = path.Join( path.Dir(importedFrom), importedPath, ) if strings.HasPrefix(importedFrom, "../") { err = fmt.Errorf("jsonnet: cannot resolve import: %s", importedPath) return contents, foundAt, err } // if the contents exist in the cache, return the // cached item. var ok bool if contents, ok = i.cache[importedPath]; ok { return contents, importedPath, nil } defer func() { i.count++ }() // if the import limit is exceeded log an error message. if i.limit > 0 && i.count >= i.limit { return contents, foundAt, errors.New("jsonnet: import limit exceeded") } find, err := i.fileService.Get(noContext, i.repo, importedPath, i.execution.Ref) if err != nil { return contents, foundAt, err } i.cache[importedPath] = jsonnet.MakeContents(string(find.Data)) return i.cache[importedPath], importedPath, err } func Parse( repo *types.Repository, repoIsPublic bool, pipeline *types.Pipeline, execution *types.Execution, file *file.File, fileService file.Service, limit int, ) (string, error) { vm := jsonnet.MakeVM() vm.MaxStack = 500 vm.StringOutput = false vm.ErrorFormatter.SetMaxStackTraceSize(20) if fileService != nil && limit > 0 { vm.Importer( &importer{ repo: repo, execution: execution, limit: limit, fileService: fileService, }, ) } // map execution/repo/pipeline parameters if execution != nil { mapBuild(execution, vm) } if repo != nil { mapRepo(repo, pipeline, vm, repoIsPublic) } jsonnetFile := file jsonnetFileName := pipeline.ConfigPath // convert the jsonnet file to yaml buf := new(bytes.Buffer) docs, err := vm.EvaluateAnonymousSnippetStream(jsonnetFileName, string(jsonnetFile.Data)) if err != nil { doc, err2 := vm.EvaluateAnonymousSnippet(jsonnetFileName, string(jsonnetFile.Data)) if err2 != nil { return "", err } docs = append(docs, doc) } // the jsonnet vm returns a stream of yaml documents // that need to be combined into a single yaml file. for _, doc := range docs { buf.WriteString("---") buf.WriteString("\n") buf.WriteString(doc) } return buf.String(), nil } // mapBuild populates build variables available to jsonnet templates. // Since we want to maintain compatibility with drone, the older format // needs to be maintained (even if the variables do not exist in Harness). func mapBuild(v *types.Execution, vm *jsonnet.VM) { vm.ExtVar(build+"event", string(v.Event)) vm.ExtVar(build+"action", string(v.Action)) vm.ExtVar(build+"environment", v.Deploy) vm.ExtVar(build+"link", v.Link) vm.ExtVar(build+"branch", v.Target) vm.ExtVar(build+"source", v.Source) vm.ExtVar(build+"before", v.Before) vm.ExtVar(build+"after", v.After) vm.ExtVar(build+"target", v.Target) vm.ExtVar(build+"ref", v.Ref) vm.ExtVar(build+"commit", v.After) vm.ExtVar(build+"ref", v.Ref) vm.ExtVar(build+"title", v.Title) vm.ExtVar(build+"message", v.Message) vm.ExtVar(build+"source_repo", v.Fork) vm.ExtVar(build+"author_login", v.Author) vm.ExtVar(build+"author_name", v.AuthorName) vm.ExtVar(build+"author_email", v.AuthorEmail) vm.ExtVar(build+"author_avatar", v.AuthorAvatar) vm.ExtVar(build+"sender", v.Sender) fromMap(v.Params, vm) } // mapBuild populates repo level variables available to jsonnet templates. // Since we want to maintain compatibility with drone 2.x, the older format // needs to be maintained (even if the variables do not exist in Harness). func mapRepo(v *types.Repository, p *types.Pipeline, vm *jsonnet.VM, publicRepo bool) { namespace := v.Path idx := strings.LastIndex(v.Path, "/") if idx != -1 { namespace = v.Path[:idx] } // TODO [CODE-1363]: remove after identifier migration. vm.ExtVar(repo+"uid", v.Identifier) vm.ExtVar(repo+"identifier", v.Identifier) vm.ExtVar(repo+"name", v.Identifier) vm.ExtVar(repo+"namespace", namespace) vm.ExtVar(repo+"slug", v.Path) vm.ExtVar(repo+"git_http_url", v.GitURL) vm.ExtVar(repo+"git_ssh_url", v.GitURL) vm.ExtVar(repo+"link", v.GitURL) vm.ExtVar(repo+"branch", v.DefaultBranch) vm.ExtVar(repo+"config", p.ConfigPath) vm.ExtVar(repo+"private", strconv.FormatBool(!publicRepo)) vm.ExtVar(repo+"visibility", "internal") vm.ExtVar(repo+"active", strconv.FormatBool(true)) vm.ExtVar(repo+"trusted", strconv.FormatBool(true)) vm.ExtVar(repo+"protected", strconv.FormatBool(false)) vm.ExtVar(repo+"ignore_forks", strconv.FormatBool(false)) vm.ExtVar(repo+"ignore_pull_requests", strconv.FormatBool(false)) } func fromMap(m map[string]string, vm *jsonnet.VM) { for k, v := range m { vm.ExtVar(build+param+k, v) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/starlark/write.go
app/pipeline/converter/starlark/write.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package starlark import ( "encoding/json" "fmt" "io" "go.starlark.net/starlark" ) type writer interface { io.Writer io.ByteWriter io.StringWriter } //nolint:gocognit,cyclop func write(out writer, v starlark.Value) error { if marshaler, ok := v.(json.Marshaler); ok { jsonData, err := marshaler.MarshalJSON() if err != nil { return err } if _, err = out.Write(jsonData); err != nil { return err } return nil } switch v := v.(type) { case starlark.NoneType: if _, err := out.WriteString("null"); err != nil { return err } case starlark.Bool: fmt.Fprintf(out, "%t", v) case starlark.Int: if _, err := out.WriteString(v.String()); err != nil { return err } case starlark.Float: fmt.Fprintf(out, "%g", v) case starlark.String: s := string(v) if isQuoteSafe(s) { fmt.Fprintf(out, "%q", s) } else { data, err := json.Marshal(s) if err != nil { return err } if _, err = out.Write(data); err != nil { return err } } case starlark.Indexable: if err := out.WriteByte('['); err != nil { return err } for i, n := 0, starlark.Len(v); i < n; i++ { if i > 0 { if _, err := out.WriteString(", "); err != nil { return err } } if err := write(out, v.Index(i)); err != nil { return err } } if err := out.WriteByte(']'); err != nil { return err } case *starlark.Dict: if err := out.WriteByte('{'); err != nil { return err } for i, itemPair := range v.Items() { key := itemPair[0] value := itemPair[1] if i > 0 { if _, err := out.WriteString(", "); err != nil { return err } } if err := write(out, key); err != nil { return err } if _, err := out.WriteString(": "); err != nil { return err } if err := write(out, value); err != nil { return err } } if err := out.WriteByte('}'); err != nil { return err } default: return fmt.Errorf("value %s (type `%s') can't be converted to JSON", v.String(), v.Type()) } return nil } func isQuoteSafe(s string) bool { for _, r := range s { if r < 0x20 || r >= 0x10000 { return false } } return true }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/starlark/args.go
app/pipeline/converter/starlark/args.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package starlark import ( "strings" "github.com/harness/gitness/types" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" ) func createArgs( repo *types.Repository, pipeline *types.Pipeline, execution *types.Execution, repoIsPublic bool, ) []starlark.Value { args := []starlark.Value{ starlarkstruct.FromStringDict( starlark.String("context"), starlark.StringDict{ "repo": starlarkstruct.FromStringDict(starlark.String("repo"), fromRepo(repo, pipeline, repoIsPublic)), "build": starlarkstruct.FromStringDict(starlark.String("build"), fromBuild(execution)), }, ), } return args } func fromBuild(v *types.Execution) starlark.StringDict { return starlark.StringDict{ "event": starlark.String(v.Event), "action": starlark.String(v.Action), "cron": starlark.String(v.Cron), "link": starlark.String(v.Link), "branch": starlark.String(v.Target), "source": starlark.String(v.Source), "before": starlark.String(v.Before), "after": starlark.String(v.After), "target": starlark.String(v.Target), "ref": starlark.String(v.Ref), "commit": starlark.String(v.After), "title": starlark.String(v.Title), "message": starlark.String(v.Message), "source_repo": starlark.String(v.Fork), "author_login": starlark.String(v.Author), "author_name": starlark.String(v.AuthorName), "author_email": starlark.String(v.AuthorEmail), "author_avatar": starlark.String(v.AuthorAvatar), "sender": starlark.String(v.Sender), "debug": starlark.Bool(v.Debug), "params": fromMap(v.Params), } } func fromRepo(v *types.Repository, p *types.Pipeline, publicRepo bool) starlark.StringDict { namespace := v.Path idx := strings.LastIndex(v.Path, "/") if idx != -1 { namespace = v.Path[:idx] } return starlark.StringDict{ // TODO [CODE-1363]: remove after identifier migration? "uid": starlark.String(v.Identifier), "identifier": starlark.String(v.Identifier), "name": starlark.String(v.Identifier), "namespace": starlark.String(namespace), "slug": starlark.String(v.Path), "git_http_url": starlark.String(v.GitURL), "git_ssh_url": starlark.String(v.GitURL), "link": starlark.String(v.GitURL), "branch": starlark.String(v.DefaultBranch), "config": starlark.String(p.ConfigPath), "private": !starlark.Bool(publicRepo), "visibility": starlark.String("internal"), "active": starlark.Bool(true), "trusted": starlark.Bool(true), "protected": starlark.Bool(false), "ignore_forks": starlark.Bool(false), "ignore_pull_requests": starlark.Bool(false), } } func fromMap(m map[string]string) *starlark.Dict { dict := new(starlark.Dict) for k, v := range m { //nolint: errcheck dict.SetKey( starlark.String(k), starlark.String(v), ) } return dict }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/converter/starlark/starlark.go
app/pipeline/converter/starlark/starlark.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package starlark import ( "bytes" "errors" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/types" "github.com/sirupsen/logrus" "go.starlark.net/starlark" ) const ( separator = "---" newline = "\n" ) // default limit for generated configuration file size. const defaultSizeLimit = 1000000 var ( // ErrMainMissing indicates the starlark script is missing // the main method. ErrMainMissing = errors.New("starlark: missing main function") // ErrMainInvalid indicates the starlark script defines a // global variable named main, however, it is not callable. ErrMainInvalid = errors.New("starlark: main must be a function") // ErrMainReturn indicates the starlark script's main method // returns an invalid or unexpected type. ErrMainReturn = errors.New("starlark: main returns an invalid type") // ErrMaximumSize indicates the starlark script generated a // file that exceeds the maximum allowed file size. ErrMaximumSize = errors.New("starlark: maximum file size exceeded") // ErrCannotLoad indicates the starlark script is attempting to // load an external file which is currently restricted. ErrCannotLoad = errors.New("starlark: cannot load external scripts") ) func Parse( repo *types.Repository, repoIsPublic bool, pipeline *types.Pipeline, execution *types.Execution, file *file.File, stepLimit uint64, sizeLimit uint64, ) (string, error) { thread := &starlark.Thread{ Name: "drone", Load: noLoad, Print: func(_ *starlark.Thread, msg string) { logrus.WithFields(logrus.Fields{ "namespace": repo.Path, // TODO: update to just be the space "name": repo.Identifier, }).Traceln(msg) }, } starlarkFile := file.Data starlarkFileName := pipeline.ConfigPath globals, err := starlark.ExecFile(thread, starlarkFileName, starlarkFile, nil) if err != nil { return "", err } // find the main method in the starlark script and // cast to a callable type. If not callable the script // is invalid. mainVal, ok := globals["main"] if !ok { return "", ErrMainMissing } main, ok := mainVal.(starlark.Callable) if !ok { return "", ErrMainInvalid } // create the input args and invoke the main method // using the input args. args := createArgs(repo, pipeline, execution, repoIsPublic) // set the maximum number of operations in the script. this // mitigates long running scripts. if stepLimit == 0 { stepLimit = 50000 } thread.SetMaxExecutionSteps(stepLimit) // execute the main method in the script. mainVal, err = starlark.Call(thread, main, args, nil) if err != nil { return "", err } buf := new(bytes.Buffer) switch v := mainVal.(type) { case *starlark.List: for i := 0; i < v.Len(); i++ { item := v.Index(i) buf.WriteString(separator) buf.WriteString(newline) if err := write(buf, item); err != nil { return "", err } buf.WriteString(newline) } case *starlark.Dict: if err := write(buf, v); err != nil { return "", err } default: return "", ErrMainReturn } if sizeLimit == 0 { sizeLimit = defaultSizeLimit } // this is a temporary workaround until we // implement a LimitWriter. if b := buf.Bytes(); uint64(len(b)) > sizeLimit { return "", ErrMaximumSize } return buf.String(), nil } func noLoad(_ *starlark.Thread, _ string) (starlark.StringDict, error) { return nil, ErrCannotLoad }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/canceler/wire.go
app/pipeline/canceler/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package canceler import ( "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideCanceler, ) // ProvideExecutionManager provides an execution manager. func ProvideCanceler( executionStore store.ExecutionStore, sseStreamer sse.Streamer, repoStore store.RepoStore, scheduler scheduler.Scheduler, stageStore store.StageStore, stepStore store.StepStore) Canceler { return New(executionStore, sseStreamer, repoStore, scheduler, stageStore, stepStore) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/canceler/canceler.go
app/pipeline/canceler/canceler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package canceler import ( "context" "fmt" "time" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) type service struct { executionStore store.ExecutionStore sseStreamer sse.Streamer repoStore store.RepoStore scheduler scheduler.Scheduler stageStore store.StageStore stepStore store.StepStore } // Canceler cancels a build. type Canceler interface { // Cancel cancels the provided execution. Cancel(ctx context.Context, repo *types.RepositoryCore, execution *types.Execution) error } // New returns a cancellation service that encapsulates // all cancellation operations. func New( executionStore store.ExecutionStore, sseStreamer sse.Streamer, repoStore store.RepoStore, scheduler scheduler.Scheduler, stageStore store.StageStore, stepStore store.StepStore, ) Canceler { return &service{ executionStore: executionStore, sseStreamer: sseStreamer, repoStore: repoStore, scheduler: scheduler, stageStore: stageStore, stepStore: stepStore, } } //nolint:gocognit // refactor if needed. func (s *service) Cancel(ctx context.Context, repo *types.RepositoryCore, execution *types.Execution) error { log := log.With(). Int64("execution.id", execution.ID). Str("execution.status", string(execution.Status)). Str("execution.Ref", execution.Ref). Logger() // do not cancel the build if the build status is // complete. only cancel the build if the status is // running or pending. if execution.Status != enum.CIStatusPending && execution.Status != enum.CIStatusRunning { return nil } // update the build status to killed. if the update fails // due to an optimistic lock error it means the build has // already started, and should now be ignored. now := time.Now().UnixMilli() execution.Status = enum.CIStatusKilled execution.Finished = now if execution.Started == 0 { execution.Started = now } err := s.executionStore.Update(ctx, execution) if err != nil { return fmt.Errorf("could not update execution status to canceled: %w", err) } stages, err := s.stageStore.ListWithSteps(ctx, execution.ID) if err != nil { return fmt.Errorf("could not list stages with steps: %w", err) } // update the status of all steps to indicate they // were killed or skipped. for _, stage := range stages { if stage.Status.IsDone() { continue } if stage.Started != 0 { stage.Status = enum.CIStatusKilled } else { stage.Status = enum.CIStatusSkipped stage.Started = now } stage.Stopped = now err := s.stageStore.Update(ctx, stage) if err != nil { log.Debug().Err(err). Int64("stage.number", stage.Number). Msg("canceler: cannot update stage status") } // update the status of all steps to indicate they // were killed or skipped. for _, step := range stage.Steps { if step.Status.IsDone() { continue } if step.Started != 0 { step.Status = enum.CIStatusKilled } else { step.Status = enum.CIStatusSkipped step.Started = now } step.Stopped = now step.ExitCode = 130 err := s.stepStore.Update(ctx, step) if err != nil { log.Debug().Err(err). Int64("stage.number", stage.Number). Int64("step.number", step.Number). Msg("canceler: cannot update step status") } } } execution.Stages = stages log.Info().Msg("canceler: successfully cancelled build") s.sseStreamer.Publish(ctx, repo.ParentID, enum.SSETypeExecutionCanceled, execution) return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/commit/wire.go
app/pipeline/commit/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package commit import ( "github.com/harness/gitness/git" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideService, ) // ProvideService provides a service which can fetch commit // information about a repository. func ProvideService(git git.Interface) Service { return newService(git) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/commit/gitness.go
app/pipeline/commit/gitness.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package commit import ( "context" "github.com/harness/gitness/app/api/controller" "github.com/harness/gitness/git" "github.com/harness/gitness/types" ) type service struct { git git.Interface } func newService(git git.Interface) Service { return &service{git: git} } // FindRef finds information about a commit in Harness for the git ref. // This is using the branch only as the ref at the moment, can be changed // when needed to take any ref (like sha, tag). func (f *service) FindRef( ctx context.Context, repo *types.RepositoryCore, branch string, ) (*types.Commit, error) { readParams := git.ReadParams{ RepoUID: repo.GitUID, } branchOutput, err := f.git.GetBranch(ctx, &git.GetBranchParams{ ReadParams: readParams, BranchName: branch, }) if err != nil { return nil, err } // convert the RPC commit output to a types.Commit. return controller.MapCommit(branchOutput.Branch.Commit), nil } // FindCommit finds information about a commit in Harness for the git SHA. func (f *service) FindCommit( ctx context.Context, repo *types.RepositoryCore, rawSHA string, ) (*types.Commit, error) { readParams := git.ReadParams{ RepoUID: repo.GitUID, } commitOutput, err := f.git.GetCommit(ctx, &git.GetCommitParams{ ReadParams: readParams, Revision: rawSHA, }) if err != nil { return nil, err } // convert the RPC commit output to a types.Commit. return controller.MapCommit(&commitOutput.Commit), nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/commit/service.go
app/pipeline/commit/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package commit import ( "context" "github.com/harness/gitness/types" ) type ( // Service provides access to commit information via // the SCM provider. Today, this is Harness but it can // be extendible to any SCM provider. Service interface { // ref is the ref to fetch the commit from, eg refs/heads/master FindRef(ctx context.Context, repo *types.RepositoryCore, ref string) (*types.Commit, error) // FindCommit returns information about a commit in a repo. FindCommit(ctx context.Context, repo *types.RepositoryCore, sha string) (*types.Commit, error) } )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/checks/write.go
app/pipeline/checks/write.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package checks import ( "context" "encoding/json" "fmt" "time" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // Write is a util function which writes execution and pipeline state to the // check store. func Write( ctx context.Context, checkStore store.CheckStore, execution *types.Execution, pipeline *types.Pipeline, ) error { payload := types.CheckPayloadInternal{ Number: execution.Number, RepoID: execution.RepoID, PipelineID: execution.PipelineID, } data, err := json.Marshal(payload) if err != nil { return fmt.Errorf("could not marshal check payload: %w", err) } now := time.Now().UnixMilli() summary := pipeline.Description if summary == "" { summary = pipeline.Identifier } check := &types.Check{ RepoID: execution.RepoID, Identifier: pipeline.Identifier, Summary: summary, Created: now, Updated: now, CreatedBy: execution.CreatedBy, Status: execution.Status.ConvertToCheckStatus(), CommitSHA: execution.After, Metadata: []byte("{}"), Payload: types.CheckPayload{ Version: "1", Kind: enum.CheckPayloadKindPipeline, Data: data, }, } err = checkStore.Upsert(ctx, check) if err != nil { return fmt.Errorf("could not upsert to check store: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/wire.go
app/pipeline/triggerer/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package triggerer import ( "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideTriggerer, ) // ProvideTriggerer provides a triggerer which can execute builds. func ProvideTriggerer( executionStore store.ExecutionStore, checkStore store.CheckStore, stageStore store.StageStore, tx dbtx.Transactor, pipelineStore store.PipelineStore, fileService file.Service, converterService converter.Service, scheduler scheduler.Scheduler, repoStore store.RepoStore, urlProvider url.Provider, templateStore store.TemplateStore, pluginStore store.PluginStore, publicAccess publicaccess.Service, ) Triggerer { return New(executionStore, checkStore, stageStore, pipelineStore, tx, repoStore, urlProvider, scheduler, fileService, converterService, templateStore, pluginStore, publicAccess) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/trigger.go
app/pipeline/triggerer/trigger.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package triggerer import ( "context" "fmt" "regexp" "runtime/debug" "time" "github.com/harness/gitness/app/pipeline/checks" "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/manager" "github.com/harness/gitness/app/pipeline/resolver" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/pipeline/triggerer/dag" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/drone-runners/drone-runner-docker/engine2/inputs" "github.com/drone-runners/drone-runner-docker/engine2/script" "github.com/drone/drone-yaml/yaml" "github.com/drone/drone-yaml/yaml/linter" v1yaml "github.com/drone/spec/dist/go" "github.com/drone/spec/dist/go/parse/normalize" specresolver "github.com/drone/spec/dist/go/parse/resolver" "github.com/rs/zerolog/log" ) var _ Triggerer = (*triggerer)(nil) // Hook represents the payload of a post-commit hook. type Hook struct { Parent int64 `json:"parent"` Trigger string `json:"trigger"` TriggeredBy int64 `json:"triggered_by"` Action enum.TriggerAction `json:"action"` Link string `json:"link"` Timestamp int64 `json:"timestamp"` Title string `json:"title"` Message string `json:"message"` Before string `json:"before"` After string `json:"after"` Ref string `json:"ref"` Fork string `json:"fork"` Source string `json:"source"` Target string `json:"target"` AuthorLogin string `json:"author_login"` AuthorName string `json:"author_name"` AuthorEmail string `json:"author_email"` AuthorAvatar string `json:"author_avatar"` Debug bool `json:"debug"` Cron string `json:"cron"` Sender string `json:"sender"` Params map[string]string `json:"params"` } // Triggerer is responsible for triggering a Execution from an // incoming hook (could be manual or webhook). If an execution is skipped a nil value is // returned. type Triggerer interface { Trigger(ctx context.Context, pipeline *types.Pipeline, hook *Hook) (*types.Execution, error) } type triggerer struct { executionStore store.ExecutionStore checkStore store.CheckStore stageStore store.StageStore tx dbtx.Transactor pipelineStore store.PipelineStore fileService file.Service converterService converter.Service urlProvider url.Provider scheduler scheduler.Scheduler repoStore store.RepoStore templateStore store.TemplateStore pluginStore store.PluginStore publicAccess publicaccess.Service } func New( executionStore store.ExecutionStore, checkStore store.CheckStore, stageStore store.StageStore, pipelineStore store.PipelineStore, tx dbtx.Transactor, repoStore store.RepoStore, urlProvider url.Provider, scheduler scheduler.Scheduler, fileService file.Service, converterService converter.Service, templateStore store.TemplateStore, pluginStore store.PluginStore, publicAccess publicaccess.Service, ) Triggerer { return &triggerer{ executionStore: executionStore, checkStore: checkStore, stageStore: stageStore, scheduler: scheduler, urlProvider: urlProvider, tx: tx, pipelineStore: pipelineStore, fileService: fileService, converterService: converterService, repoStore: repoStore, templateStore: templateStore, pluginStore: pluginStore, publicAccess: publicAccess, } } //nolint:gocognit,gocyclo,cyclop //TODO: Refactor @Vistaar func (t *triggerer) Trigger( ctx context.Context, pipeline *types.Pipeline, base *Hook, ) (*types.Execution, error) { log := log.With(). Int64("pipeline.id", pipeline.ID). Str("trigger.ref", base.Ref). Str("trigger.commit", base.After). Logger() log.Debug().Msg("trigger: received") defer func() { // taking the paranoid approach to recover from // a panic that should absolutely never happen. if r := recover(); r != nil { log.Error().Msgf("runner: unexpected panic: %s", r) debug.PrintStack() } }() event := base.Action.GetTriggerEvent() repo, err := t.repoStore.Find(ctx, pipeline.RepoID) if err != nil { log.Error().Err(err).Msg("could not find repo") return nil, err } repoIsPublic, err := t.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return nil, fmt.Errorf("could not check if repo is public: %w", err) } file, err := t.fileService.Get(ctx, repo, pipeline.ConfigPath, base.After) if err != nil { log.Error().Err(err).Msg("trigger: could not find yaml") return nil, err } now := time.Now().UnixMilli() execution := &types.Execution{ RepoID: repo.ID, PipelineID: pipeline.ID, Trigger: base.Trigger, CreatedBy: base.TriggeredBy, Parent: base.Parent, Status: enum.CIStatusPending, Event: event, Action: base.Action, Link: base.Link, // Timestamp: base.Timestamp, Title: trunc(base.Title, 2000), Message: trunc(base.Message, 2000), Before: base.Before, After: base.After, Ref: base.Ref, Fork: base.Fork, Source: base.Source, Target: base.Target, Author: base.AuthorLogin, AuthorName: base.AuthorName, AuthorEmail: base.AuthorEmail, AuthorAvatar: base.AuthorAvatar, Params: base.Params, Debug: base.Debug, Sender: base.Sender, Cron: base.Cron, Created: now, Updated: now, } // For drone, follow the existing path of calculating dependencies, creating a DAG, // and creating stages accordingly. For V1 YAML - for now we can just parse the stages // and create them sequentially. stages := []*types.Stage{} //nolint:nestif // refactor if needed if !isV1Yaml(file.Data) { // Convert from jsonnet/starlark to drone yaml args := &converter.ConvertArgs{ Repo: repo, Pipeline: pipeline, Execution: execution, File: file, RepoIsPublic: repoIsPublic, } file, err = t.converterService.Convert(ctx, args) if err != nil { log.Warn().Err(err).Msg("trigger: cannot convert from template") return t.createExecutionWithError(ctx, pipeline, base, err.Error()) } manifest, err := yaml.ParseString(string(file.Data)) if err != nil { log.Warn().Err(err).Msg("trigger: cannot parse yaml") return t.createExecutionWithError(ctx, pipeline, base, err.Error()) } err = linter.Manifest(manifest, true) if err != nil { log.Warn().Err(err).Msg("trigger: yaml linting error") return t.createExecutionWithError(ctx, pipeline, base, err.Error()) } var matched []*yaml.Pipeline var dag = dag.New() for _, document := range manifest.Resources { pipeline, ok := document.(*yaml.Pipeline) if !ok { continue } // TODO add repo // TODO add instance // TODO add target // TODO add ref name := pipeline.Name if name == "" { name = "default" } node := dag.Add(name, pipeline.DependsOn...) node.Skip = true switch { case skipBranch(pipeline, base.Target): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match branch") case skipEvent(pipeline, string(event)): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match event") case skipAction(pipeline, string(base.Action)): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match action") case skipRef(pipeline, base.Ref): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match ref") case skipRepo(pipeline, repo.Path): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match repo") case skipCron(pipeline, base.Cron): log.Info().Str("pipeline", name).Msg("trigger: skipping pipeline, does not match cron job") default: matched = append(matched, pipeline) node.Skip = false } } if dag.DetectCycles() { return t.createExecutionWithError(ctx, pipeline, base, "Error: Dependency cycle detected in Pipeline") } if len(matched) == 0 { log.Info().Msg("trigger: skipping execution, no matching pipelines") //nolint:nilnil // on purpose return nil, nil } for i, match := range matched { onSuccess := match.Trigger.Status.Match(string(enum.CIStatusSuccess)) onFailure := match.Trigger.Status.Match(string(enum.CIStatusFailure)) if len(match.Trigger.Status.Include)+len(match.Trigger.Status.Exclude) == 0 { onFailure = false } stage := &types.Stage{ RepoID: repo.ID, Number: int64(i + 1), Name: match.Name, Kind: match.Kind, Type: match.Type, OS: match.Platform.OS, Arch: match.Platform.Arch, Variant: match.Platform.Variant, Kernel: match.Platform.Version, Limit: match.Concurrency.Limit, Status: enum.CIStatusWaitingOnDeps, DependsOn: match.DependsOn, OnSuccess: onSuccess, OnFailure: onFailure, Labels: match.Node, Created: now, Updated: now, } if stage.Kind == "pipeline" && stage.Type == "" { stage.Type = "docker" } if stage.OS == "" { stage.OS = "linux" } if stage.Arch == "" { stage.Arch = "amd64" } if stage.Name == "" { stage.Name = "default" } if len(stage.DependsOn) == 0 { stage.Status = enum.CIStatusPending } stages = append(stages, stage) } for _, stage := range stages { // here we re-work the dependencies for the stage to // account for the fact that some steps may be skipped // and may otherwise break the dependency chain. stage.DependsOn = dag.Dependencies(stage.Name) // if the stage is pending dependencies, but those // dependencies are skipped, the stage can be executed // immediately. if stage.Status == enum.CIStatusWaitingOnDeps && len(stage.DependsOn) == 0 { stage.Status = enum.CIStatusPending } } } else { stages, err = parseV1Stages( ctx, file.Data, repo, execution, t.templateStore, t.pluginStore, t.publicAccess) if err != nil { return nil, fmt.Errorf("could not parse v1 YAML into stages: %w", err) } } // Increment pipeline number using optimistic locking. pipeline, err = t.pipelineStore.IncrementSeqNum(ctx, pipeline) if err != nil { log.Error().Err(err).Msg("trigger: cannot increment execution sequence number") return nil, err } // TODO: this can be made better. We are setting this later since otherwise any parsing failure // would lead to an incremented pipeline sequence number. execution.Number = pipeline.Seq execution.Params = combine(execution.Params, Envs(ctx, repo, pipeline, t.urlProvider)) err = t.createExecutionWithStages(ctx, execution, stages) if err != nil { log.Error().Err(err).Msg("trigger: cannot create execution") return nil, err } // try to write to check store. log on failure but don't error out the execution err = checks.Write(ctx, t.checkStore, execution, pipeline) if err != nil { log.Error().Err(err).Msg("trigger: could not write to check store") } for _, stage := range stages { if stage.Status != enum.CIStatusPending { continue } err = t.scheduler.Schedule(ctx, stage) if err != nil { log.Error().Err(err).Msg("trigger: cannot enqueue execution") return nil, err } } return execution, nil } func trunc(s string, i int) string { runes := []rune(s) if len(runes) > i { return string(runes[:i]) } return s } // parseV1Stages tries to parse the yaml into a list of stages and returns an error // if we are unable to do so or the yaml contains something unexpected. // Currently, all the stages will be executed one after the other on completion. // Once we have depends on in v1, this will be changed to use the DAG. // //nolint:gocognit // refactor if needed. func parseV1Stages( ctx context.Context, data []byte, repo *types.Repository, execution *types.Execution, templateStore store.TemplateStore, pluginStore store.PluginStore, publicAccess publicaccess.Service, ) ([]*types.Stage, error) { stages := []*types.Stage{} // For V1 YAML, just go through the YAML and create stages serially for now config, err := v1yaml.ParseBytes(data) if err != nil { return nil, fmt.Errorf("could not parse v1 yaml: %w", err) } // Normalize the config to make sure stage names and step names are unique err = normalize.Normalize(config) if err != nil { return nil, fmt.Errorf("could not normalize v1 yaml: %w", err) } if config.Kind != "pipeline" { return nil, fmt.Errorf("cannot support non-pipeline kinds in v1 at the moment: %w", err) } // get repo public access repoIsPublic, err := publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) if err != nil { return nil, fmt.Errorf("could not check repo public access: %w", err) } inputParams := map[string]any{} inputParams["repo"] = inputs.Repo(manager.ConvertToDroneRepo(repo, repoIsPublic)) inputParams["build"] = inputs.Build(manager.ConvertToDroneBuild(execution)) var prevStage string // expand stage level templates and plugins lookupFunc := func(name, kind, typ, version string) (*v1yaml.Config, error) { f := resolver.Resolve(ctx, pluginStore, templateStore, repo.ParentID) return f(name, kind, typ, version) } if err := specresolver.Resolve(config, lookupFunc); err != nil { return nil, fmt.Errorf("could not resolve yaml plugins/templates: %w", err) } switch v := config.Spec.(type) { case *v1yaml.Pipeline: // Expand expressions in strings and matrices script.ExpandConfig(config, inputParams) for idx, stage := range v.Stages { // Only parse CI stages for now switch stage.Spec.(type) { case *v1yaml.StageCI: now := time.Now().UnixMilli() var onSuccess, onFailure bool onSuccess = true if stage.When != nil { if when := stage.When.Eval; when != "" { // TODO: pass in params for resolution onSuccess, onFailure, err = script.EvalWhen(when, inputParams) if err != nil { return nil, fmt.Errorf("could not resolve when condition for stage: %w", err) } } } dependsOn := []string{} if prevStage != "" { dependsOn = append(dependsOn, prevStage) } status := enum.CIStatusWaitingOnDeps // If the stage has no dependencies, it can be picked up for execution. if len(dependsOn) == 0 { status = enum.CIStatusPending } temp := &types.Stage{ RepoID: repo.ID, Number: int64(idx + 1), Name: stage.Id, // for v1, ID is the unique identifier per stage Created: now, Updated: now, Status: status, OnSuccess: onSuccess, OnFailure: onFailure, DependsOn: dependsOn, } prevStage = temp.Name stages = append(stages, temp) default: return nil, fmt.Errorf("only CI and template stages are supported in v1 at the moment") } } default: return nil, fmt.Errorf("unknown yaml: %w", err) } return stages, nil } // Checks whether YAML is V1 Yaml or drone Yaml. func isV1Yaml(data []byte) bool { // if we are dealing with the legacy drone yaml, use // the legacy drone engine. return regexp.MustCompilePOSIX(`^spec:`).Match(data) } // createExecutionWithStages writes an execution along with its stages in a single transaction. func (t *triggerer) createExecutionWithStages( ctx context.Context, execution *types.Execution, stages []*types.Stage, ) error { return t.tx.WithTx(ctx, func(ctx context.Context) error { err := t.executionStore.Create(ctx, execution) if err != nil { return err } for _, stage := range stages { stage.ExecutionID = execution.ID err := t.stageStore.Create(ctx, stage) if err != nil { return err } } return nil }) } // createExecutionWithError creates an execution with an error message. func (t *triggerer) createExecutionWithError( ctx context.Context, pipeline *types.Pipeline, base *Hook, message string, ) (*types.Execution, error) { log := log.With(). Int64("pipeline.id", pipeline.ID). Str("trigger.ref", base.Ref). Str("trigger.commit", base.After). Logger() pipeline, err := t.pipelineStore.IncrementSeqNum(ctx, pipeline) if err != nil { return nil, err } now := time.Now().UnixMilli() execution := &types.Execution{ RepoID: pipeline.RepoID, PipelineID: pipeline.ID, Number: pipeline.Seq, Parent: base.Parent, Status: enum.CIStatusError, Error: message, Event: base.Action.GetTriggerEvent(), Action: base.Action, Link: base.Link, Title: base.Title, Message: base.Message, CreatedBy: base.TriggeredBy, Before: base.Before, After: base.After, Ref: base.Ref, Fork: base.Fork, Source: base.Source, Target: base.Target, Author: base.AuthorLogin, AuthorName: base.AuthorName, AuthorEmail: base.AuthorEmail, AuthorAvatar: base.AuthorAvatar, Debug: base.Debug, Sender: base.Sender, Created: now, Updated: now, Started: now, Finished: now, } err = t.executionStore.Create(ctx, execution) if err != nil { log.Error().Err(err).Msg("trigger: cannot create execution error") return nil, err } // try to write to check store, log on failure err = checks.Write(ctx, t.checkStore, execution, pipeline) if err != nil { log.Error().Err(err).Msg("trigger: failed to update check") } return execution, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/env.go
app/pipeline/triggerer/env.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package triggerer import ( "context" "github.com/harness/gitness/app/url" "github.com/harness/gitness/types" "golang.org/x/exp/maps" ) // combine is a helper function that combines one or more maps of // environment variables into a single map. func combine(env ...map[string]string) map[string]string { c := map[string]string{} for _, e := range env { maps.Copy(c, e) } return c } func Envs( ctx context.Context, repo *types.Repository, pipeline *types.Pipeline, urlProvider url.Provider, ) map[string]string { return map[string]string{ "DRONE_BUILD_LINK": urlProvider.GenerateUIBuildURL(ctx, repo.Path, pipeline.Identifier, pipeline.Seq), } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/skip.go
app/pipeline/triggerer/skip.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package triggerer import ( "github.com/drone/drone-yaml/yaml" ) func skipBranch(document *yaml.Pipeline, branch string) bool { return !document.Trigger.Branch.Match(branch) } func skipRef(document *yaml.Pipeline, ref string) bool { return !document.Trigger.Ref.Match(ref) } func skipEvent(document *yaml.Pipeline, event string) bool { return !document.Trigger.Event.Match(event) } func skipAction(document *yaml.Pipeline, action string) bool { return !document.Trigger.Action.Match(action) } func skipRepo(document *yaml.Pipeline, repo string) bool { return !document.Trigger.Repo.Match(repo) } func skipCron(document *yaml.Pipeline, cron string) bool { return !document.Trigger.Cron.Match(cron) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/dag/dag.go
app/pipeline/triggerer/dag/dag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dag // Dag is a directed acyclic graph. type Dag struct { graph map[string]*Vertex } // Vertex is a vertex in the graph. type Vertex struct { Name string Skip bool graph []string } // New creates a new directed acyclic graph (dag) that can // determinate if a stage has dependencies. func New() *Dag { return &Dag{ graph: make(map[string]*Vertex), } } // Add establishes a dependency between two vertices in the graph. func (d *Dag) Add(from string, to ...string) *Vertex { vertex := new(Vertex) vertex.Name = from vertex.Skip = false vertex.graph = to d.graph[from] = vertex return vertex } // Get returns the vertex from the graph. func (d *Dag) Get(name string) (*Vertex, bool) { vertex, ok := d.graph[name] return vertex, ok } // Dependencies returns the direct dependencies accounting for // skipped dependencies. func (d *Dag) Dependencies(name string) []string { vertex := d.graph[name] return d.dependencies(vertex) } // Ancestors returns the ancestors of the vertex. func (d *Dag) Ancestors(name string) []*Vertex { vertex := d.graph[name] return d.ancestors(vertex) } // DetectCycles returns true if cycles are detected in the graph. func (d *Dag) DetectCycles() bool { visited := make(map[string]bool) recStack := make(map[string]bool) for vertex := range d.graph { if !visited[vertex] { if d.detectCycles(vertex, visited, recStack) { return true } } } return false } // helper function returns the list of ancestors for the vertex. func (d *Dag) ancestors(parent *Vertex) []*Vertex { if parent == nil { return nil } var combined []*Vertex for _, name := range parent.graph { vertex, found := d.graph[name] if !found { continue } if !vertex.Skip { combined = append(combined, vertex) } combined = append(combined, d.ancestors(vertex)...) } return combined } // helper function returns the list of dependencies for the, // vertex taking into account skipped dependencies. func (d *Dag) dependencies(parent *Vertex) []string { if parent == nil { return nil } var combined []string for _, name := range parent.graph { vertex, found := d.graph[name] if !found { continue } if vertex.Skip { // if the vertex is skipped we should move up the // graph and check direct ancestors. combined = append(combined, d.dependencies(vertex)...) } else { combined = append(combined, vertex.Name) } } return combined } // helper function returns true if the vertex is cyclical. func (d *Dag) detectCycles(name string, visited, recStack map[string]bool) bool { visited[name] = true recStack[name] = true vertex, ok := d.graph[name] if !ok { return false } for _, v := range vertex.graph { // only check cycles on a vertex one time if !visited[v] { if d.detectCycles(v, visited, recStack) { return true } // if we've visited this vertex in this recursion // stack, then we have a cycle } else if recStack[v] { return true } } recStack[name] = false return false }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pipeline/triggerer/dag/dag_test.go
app/pipeline/triggerer/dag/dag_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dag import ( "reflect" "testing" ) func TestDag(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend") dag.Add("notify", "backend", "frontend") if dag.DetectCycles() { t.Errorf("cycles detected") } dag = New() dag.Add("notify", "backend", "frontend") if dag.DetectCycles() { t.Errorf("cycles detected") } dag = New() dag.Add("backend", "frontend") dag.Add("frontend", "backend") dag.Add("notify", "backend", "frontend") if dag.DetectCycles() == false { t.Errorf("Expect cycles detected") } dag = New() dag.Add("backend", "backend") dag.Add("frontend", "backend") dag.Add("notify", "backend", "frontend") if dag.DetectCycles() == false { t.Errorf("Expect cycles detected") } dag = New() dag.Add("backend") dag.Add("frontend") dag.Add("notify", "backend", "frontend", "notify") if dag.DetectCycles() == false { t.Errorf("Expect cycles detected") } } func TestAncestors(t *testing.T) { dag := New() v := dag.Add("backend") dag.Add("frontend", "backend") dag.Add("notify", "frontend") ancestors := dag.Ancestors("frontend") if got, want := len(ancestors), 1; got != want { t.Errorf("Want %d ancestors, got %d", want, got) } if ancestors[0] != v { t.Errorf("Unexpected ancestor") } if v := dag.Ancestors("backend"); len(v) != 0 { t.Errorf("Expect vertexes with no dependencies has zero ancestors") } } func TestAncestors_Skipped(t *testing.T) { dag := New() dag.Add("backend").Skip = true dag.Add("frontend", "backend").Skip = true dag.Add("notify", "frontend") if v := dag.Ancestors("frontend"); len(v) != 0 { t.Errorf("Expect skipped vertexes excluded") } if v := dag.Ancestors("notify"); len(v) != 0 { t.Errorf("Expect skipped vertexes excluded") } } func TestAncestors_NotFound(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend", "backend") dag.Add("notify", "frontend") if dag.DetectCycles() { t.Errorf("cycles detected") } if v := dag.Ancestors("does-not-exist"); len(v) != 0 { t.Errorf("Expect vertex not found does not panic") } } func TestAncestors_Malformed(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend", "does-not-exist") dag.Add("notify", "frontend") if dag.DetectCycles() { t.Errorf("cycles detected") } if v := dag.Ancestors("frontend"); len(v) != 0 { t.Errorf("Expect invalid dependency does not panic") } } func TestAncestors_Complex(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend") dag.Add("publish", "backend", "frontend") dag.Add("deploy", "publish") last := dag.Add("notify", "deploy") if dag.DetectCycles() { t.Errorf("cycles detected") } ancestors := dag.Ancestors("notify") if got, want := len(ancestors), 4; got != want { t.Errorf("Want %d ancestors, got %d", want, got) return } for _, ancestor := range ancestors { if ancestor == last { t.Errorf("Unexpected ancestor") } } v, _ := dag.Get("publish") v.Skip = true ancestors = dag.Ancestors("notify") if got, want := len(ancestors), 3; got != want { t.Errorf("Want %d ancestors, got %d", want, got) return } } func TestDependencies(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend") dag.Add("publish", "backend", "frontend") if deps := dag.Dependencies("backend"); len(deps) != 0 { t.Errorf("Expect zero dependencies") } if deps := dag.Dependencies("frontend"); len(deps) != 0 { t.Errorf("Expect zero dependencies") } got, want := dag.Dependencies("publish"), []string{"backend", "frontend"} if !reflect.DeepEqual(got, want) { t.Errorf("Unexpected dependencies, got %v", got) } } func TestDependencies_Skipped(t *testing.T) { dag := New() dag.Add("backend") dag.Add("frontend").Skip = true dag.Add("publish", "backend", "frontend") if deps := dag.Dependencies("backend"); len(deps) != 0 { t.Errorf("Expect zero dependencies") } if deps := dag.Dependencies("frontend"); len(deps) != 0 { t.Errorf("Expect zero dependencies") } got, want := dag.Dependencies("publish"), []string{"backend"} if !reflect.DeepEqual(got, want) { t.Errorf("Unexpected dependencies, got %v", got) } } func TestDependencies_Complex(t *testing.T) { dag := New() dag.Add("clone") dag.Add("backend") dag.Add("frontend", "backend").Skip = true dag.Add("publish", "frontend", "clone") dag.Add("notify", "publish") if deps := dag.Dependencies("clone"); len(deps) != 0 { t.Errorf("Expect zero dependencies for clone") } if deps := dag.Dependencies("backend"); len(deps) != 0 { t.Errorf("Expect zero dependencies for backend") } got, want := dag.Dependencies("frontend"), []string{"backend"} if !reflect.DeepEqual(got, want) { t.Errorf("Unexpected dependencies for frontend, got %v", got) } got, want = dag.Dependencies("publish"), []string{"backend", "clone"} if !reflect.DeepEqual(got, want) { t.Errorf("Unexpected dependencies for publish, got %v", got) } got, want = dag.Dependencies("notify"), []string{"publish"} if !reflect.DeepEqual(got, want) { t.Errorf("Unexpected dependencies for notify, got %v", got) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/stream.go
stream/stream.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "context" "errors" "fmt" "time" ) var ( ErrAlreadyStarted = errors.New("consumer already started") defaultConfig = ConsumerConfig{ Concurrency: 2, DefaultHandlerConfig: HandlerConfig{ idleTimeout: 1 * time.Minute, maxRetries: 2, }, } ) // ConsumerConfig defines the configuration of a consumer containing externally exposed values // that can be configured using the available ConsumerOptions. type ConsumerConfig struct { // Concurrency specifies the number of worker go routines executing stream handlers. Concurrency int // DefaultHandlerConfig is the default config used for stream handlers. DefaultHandlerConfig HandlerConfig } // HandlerConfig defines the configuration for a single stream handler containing externally exposed values // that can be configured using the available HandlerOptions. type HandlerConfig struct { // idleTimeout specifies the maximum duration a message stays read but unacknowledged // before it can be claimed by others. idleTimeout time.Duration // maxRetries specifies the max number a stream message is retried. maxRetries int } // HandlerFunc defines the signature of a function handling stream messages. type HandlerFunc func(ctx context.Context, messageID string, payload map[string]any) error // handler defines a handler of a single stream. type handler struct { handle HandlerFunc config HandlerConfig } // message is used internally for passing stream messages via channels. type message struct { streamID string id string values map[string]any } // transposeStreamID transposes the provided streamID based on the namespace. func transposeStreamID(namespace string, streamID string) string { return fmt.Sprintf("%s:%s", namespace, streamID) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/redis_consumer.go
stream/redis_consumer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "context" "errors" "fmt" "net" "runtime/debug" "strings" "sync" "time" "github.com/go-redis/redis/v8" ) // RedisConsumer provides functionality to process Redis streams as part of a consumer group. type RedisConsumer struct { rdb redis.UniversalClient // namespace specifies the namespace of the keys - any stream key will be prefixed with it namespace string // groupName specifies the name of the consumer group. groupName string // consumerName specifies the name of the consumer. consumerName string // Config is the generic consumer configuration. Config ConsumerConfig // streams is a map of all registered streams and their handlers. streams map[string]handler isStarted bool messageQueue chan message errorCh chan error infoCh chan string } // NewRedisConsumer creates new Redis stream consumer. Streams are read with XREADGROUP. // It returns channels of info messages and errors. The caller should not block on these channels for too long. // These channels are provided mainly for logging. func NewRedisConsumer(rdb redis.UniversalClient, namespace string, groupName string, consumerName string) (*RedisConsumer, error) { if groupName == "" { return nil, errors.New("groupName can't be empty") } if consumerName == "" { return nil, errors.New("consumerName can't be empty") } const queueCapacity = 500 const errorChCapacity = 64 const infoChCapacity = 64 return &RedisConsumer{ rdb: rdb, namespace: namespace, groupName: groupName, consumerName: consumerName, streams: map[string]handler{}, Config: defaultConfig, isStarted: false, messageQueue: make(chan message, queueCapacity), errorCh: make(chan error, errorChCapacity), infoCh: make(chan string, infoChCapacity), }, nil } func (c *RedisConsumer) Configure(opts ...ConsumerOption) { if c.isStarted { return } for _, opt := range opts { opt.apply(&c.Config) } } func (c *RedisConsumer) Register(streamID string, fn HandlerFunc, opts ...HandlerOption) error { if c.isStarted { return ErrAlreadyStarted } if streamID == "" { return errors.New("streamID can't be empty") } if fn == nil { return errors.New("fn can't be empty") } // transpose streamID to key namespace - no need to keep inner streamID transposedStreamID := transposeStreamID(c.namespace, streamID) if _, ok := c.streams[transposedStreamID]; ok { return fmt.Errorf("consumer is already registered for '%s' (redis stream '%s')", streamID, transposedStreamID) } // create final config for handler config := c.Config.DefaultHandlerConfig for _, opt := range opts { opt.apply(&config) } c.streams[transposedStreamID] = handler{ handle: fn, config: config, } return nil } func (c *RedisConsumer) Start(ctx context.Context) error { if c.isStarted { return ErrAlreadyStarted } if len(c.streams) == 0 { return errors.New("no streams registered") } var err error // Check if Redis is accessible, fail if it's not. err = c.rdb.Ping(ctx).Err() if err != nil && !errors.Is(err, redis.Nil) { return fmt.Errorf("failed to ping redis server: %w", err) } // Create consumer group for all streams, creates streams if they don't exist. err = c.createGroupForAllStreams(ctx) if err != nil { return err } // mark as started before starting go routines (can't error out from here) c.isStarted = true wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() c.removeStaleConsumers(ctx, time.Hour) // launch redis reader, it will finish when the ctx is done c.reader(ctx) }() wg.Add(1) go func() { defer wg.Done() // launch redis message reclaimer, it will finish when the ctx is done. // IMPORTANT: Keep reclaim interval small for now to support faster retries => higher load on redis! // TODO: Make retries local by default with opt-in cross-instance retries. // https://harness.atlassian.net/browse/SCM-83 const reclaimInterval = 10 * time.Second c.reclaimer(ctx, reclaimInterval) }() for i := 0; i < c.Config.Concurrency; i++ { wg.Add(1) go func() { defer wg.Done() // launch redis message consumer, it will finish when the ctx is done c.consumer(ctx) }() } go func() { // wait for all go routines to complete wg.Wait() // close all channels close(c.messageQueue) close(c.errorCh) close(c.infoCh) }() return nil } // reader method reads a Redis stream with XREADGROUP command to retrieve messages. // The messages are then sent to a go channel passed as parameter for processing. // If the stream already contains unassigned messages, those we'll be returned. // Otherwise XREADGROUP blocks until either a new message arrives or block timeout happens. // The method terminates when the provided context finishes. // //nolint:funlen,gocognit // refactor if needed func (c *RedisConsumer) reader(ctx context.Context) { delays := []time.Duration{1 * time.Millisecond, 5 * time.Second, 15 * time.Second, 30 * time.Second, time.Minute} consecutiveFailures := 0 // pre-generate streams argument for XReadGroup // NOTE: for the first call ever we want to get the history of the consumer (to allow for seamless restarts) // ASSUMPTION: only one consumer with a given groupName+consumerName is running at a time scanHistory := true streamLen := len(c.streams) streamsArg := make([]string, 2*streamLen) i := 0 for streamID := range c.streams { streamsArg[i] = streamID streamsArg[streamLen+i] = "0" i++ } for { var delay time.Duration if consecutiveFailures < len(delays) { delay = delays[consecutiveFailures] } else { delay = delays[len(delays)-1] } readTimer := time.NewTimer(delay) select { case <-ctx.Done(): readTimer.Stop() return case <-readTimer.C: const count = 100 resReadStream, err := c.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{ Group: c.groupName, Consumer: c.consumerName, Streams: streamsArg, Count: count, Block: 5 * time.Minute, }).Result() // if context is canceled, continue and next iteration will exit cleanly if errors.Is(err, context.Canceled) { continue } // network timeout - log it and retry var errNet net.Error if ok := errors.As(err, &errNet); ok && errNet.Timeout() { c.pushError(fmt.Errorf("encountered network failure: %w", errNet)) consecutiveFailures++ continue } // group doesn't exist anymore - recreate it if err != nil && strings.HasPrefix(err.Error(), "NOGROUP") { cErr := c.createGroupForAllStreams(ctx) if cErr != nil { c.pushError(fmt.Errorf("failed to re-create group for at least one stream: %w", err)) consecutiveFailures++ } else { c.pushInfo(fmt.Sprintf("re-created group for all streams where it got removed, original error: %s", err)) consecutiveFailures = 0 } continue } // any other error we handle generically if err != nil && !errors.Is(err, redis.Nil) { consecutiveFailures++ c.pushError(fmt.Errorf("failed to read redis streams %v (consecutive fails: %d): %w", streamsArg, consecutiveFailures, err)) continue } // check if we are done with scanning the history of all streams if scanHistory { scanHistory = false // Getting history always returns all streams in the same order as queried // (even a stream that doesn't have any history left, in that case redis returns an empty slice) // Thus, we can use a simple incrementing index to get the streamArg for a stream in the response x := 0 for _, stream := range resReadStream { // If the stream had messages in the history, continue scanning after the latest read message. if len(stream.Messages) > 0 { scanHistory = true streamsArg[streamLen+x] = stream.Messages[len(stream.Messages)-1].ID c.pushInfo(fmt.Sprintf( "stream %q had %d more messages in the history (delivered but no yet acked),"+ "continuing scanning after %q", stream.Stream, len(stream.Messages), streamsArg[streamLen+x], )) } x++ } if !scanHistory { c.pushInfo("completed scan of history") // Update stream args to read latest messages for all streams for j := range streamLen { streamsArg[streamLen+j] = ">" } continue } } // reset fail count consecutiveFailures = 0 // if no messages were read we can skip iteration if len(resReadStream) == 0 { continue } // retrieve all messages across all streams and put them into the message queue for _, stream := range resReadStream { for _, m := range stream.Messages { c.messageQueue <- message{ streamID: stream.Stream, id: m.ID, values: m.Values, } } } } } } // reclaimer periodically inspects pending messages with XPENDING command. // If a message sits longer than processingTimeout, we attempt to reclaim the message for this consumer // and enqueue it for processing. // //nolint:funlen,gocognit // refactor if needed func (c *RedisConsumer) reclaimer(ctx context.Context, reclaimInterval time.Duration) { reclaimTimer := time.NewTimer(reclaimInterval) defer func() { reclaimTimer.Stop() }() const ( baseCount = 16 maxCount = 1024 ) // the minimum message ID which we are querying for. // redis treats "-" as smaller than any valid message ID start := "-" // the maximum message ID which we are querying for. // redis treats "+" as bigger than any valid message ID end := "+" count := baseCount for { select { case <-ctx.Done(): return case <-reclaimTimer.C: for streamID, handler := range c.streams { resPending, errPending := c.rdb.XPendingExt(ctx, &redis.XPendingExtArgs{ Stream: streamID, Group: c.groupName, Start: start, End: end, Idle: handler.config.idleTimeout, Count: int64(count), }).Result() if errPending != nil && !errors.Is(errPending, redis.Nil) { c.pushError(fmt.Errorf("failed to fetch pending messages: %w", errPending)) continue } if len(resPending) == 0 { continue } // It's safe to change start of the requested range for the next iteration to oldest message. start = resPending[0].ID for _, resMessage := range resPending { if resMessage.RetryCount > int64(handler.config.maxRetries) { // Retry count gets increased after every XCLAIM. // Large retry count might mean there is something wrong with the message, so we'll XACK it. // WARNING this will discard the message! errAck := c.rdb.XAck(ctx, streamID, c.groupName, resMessage.ID).Err() if errAck != nil { c.pushError(fmt.Errorf( "failed to force acknowledge (discard) message '%s' (Retries: %d) in stream '%s': %w", resMessage.ID, resMessage.RetryCount, streamID, errAck)) } else { retryCount := resMessage.RetryCount - 1 // redis is counting this execution as retry c.pushError(fmt.Errorf( "force acknowledged (discarded) message '%s' (Retries: %d) in stream '%s'", resMessage.ID, retryCount, streamID)) } continue } // Otherwise, claim the message so we can retry it. claimedMessages, errClaim := c.rdb.XClaim(ctx, &redis.XClaimArgs{ Stream: streamID, Group: c.groupName, Consumer: c.consumerName, MinIdle: handler.config.idleTimeout, Messages: []string{resMessage.ID}, }).Result() if errors.Is(errClaim, redis.Nil) { // Receiving redis.Nil here means the message is removed from the stream (because of MAXLEN). // The only option is to acknowledge it with XACK. errAck := c.rdb.XAck(ctx, streamID, c.groupName, resMessage.ID).Err() if errAck != nil { c.pushError(fmt.Errorf("failed to acknowledge failed message '%s' in stream '%s': %w", resMessage.ID, streamID, errAck)) } else { c.pushInfo(fmt.Sprintf("acknowledged failed message '%s' in stream '%s'", resMessage.ID, streamID)) } continue } if errClaim != nil { // This can happen if two consumers try to claim the same message at once. // One would succeed and the other will get an error. c.pushError(fmt.Errorf("failed to claim message '%s' in stream '%s': %w", resMessage.ID, streamID, errClaim)) continue } // This is not expected to happen (message will be retried or eventually discarded) if len(claimedMessages) == 0 { c.pushError(fmt.Errorf( "no error when claiming message '%s' in stream '%s', but redis returned no message", resMessage.ID, streamID)) continue } // we claimed only one message id so there is only one message in the slice claimedMessage := claimedMessages[0] c.messageQueue <- message{ streamID: streamID, id: claimedMessage.ID, values: claimedMessage.Values, } } // If number of messages that we got is equal to the number that we requested // it means that there's a lot for processing, so we'll increase number of messages // that we'll pull in the next iteration. if len(resPending) == count { count *= 2 if count > maxCount { count = maxCount } } else { count = baseCount } } reclaimTimer.Reset(reclaimInterval) } } } // consumer method consumes messages coming from Redis. The method terminates when messageQueue channel closes. func (c *RedisConsumer) consumer(ctx context.Context) { for { select { case <-ctx.Done(): return case m := <-c.messageQueue: if m.id == "" { // id should never be empty, if it is then the channel is closed return } handler, ok := c.streams[m.streamID] if !ok { // we don't want to ack the message // maybe someone else can claim and process it (worst case it expires) c.pushError(fmt.Errorf("received message '%s' in stream '%s' that doesn't belong to us, skip", m.id, m.streamID)) continue } err := func() (err error) { // Ensure that handlers don't cause panic. defer func() { if r := recover(); r != nil { c.pushError(fmt.Errorf("PANIC when processing message '%s' in stream '%s':\n%s", m.id, m.streamID, debug.Stack())) } }() return handler.handle(ctx, m.id, m.values) }() if err != nil { c.pushError(fmt.Errorf("failed to process message '%s' in stream '%s': %w", m.id, m.streamID, err)) continue } err = c.rdb.XAck(ctx, m.streamID, c.groupName, m.id).Err() if err != nil { c.pushError(fmt.Errorf("failed to acknowledge message '%s' in stream '%s': %w", m.id, m.streamID, err)) continue } } } } func (c *RedisConsumer) removeStaleConsumers(ctx context.Context, maxAge time.Duration) { for streamID := range c.streams { // Fetch all consumers for this stream and group. resConsumers, err := c.rdb.XInfoConsumers(ctx, streamID, c.groupName).Result() if err != nil { c.pushError(fmt.Errorf("failed to read consumers for stream '%s': %w", streamID, err)) return } // Delete old consumers, but only if they don't have pending messages. for _, resConsumer := range resConsumers { age := time.Duration(resConsumer.Idle) * time.Millisecond if resConsumer.Pending > 0 || age < maxAge { continue } err = c.rdb.XGroupDelConsumer(ctx, streamID, c.groupName, resConsumer.Name).Err() if err != nil { c.pushError(fmt.Errorf( "failed to remove stale consumer '%s' from group '%s' (age '%s') for stream '%s': %w", resConsumer.Name, c.groupName, age, streamID, err)) continue } c.pushInfo(fmt.Sprintf("removed stale consumer '%s' from group '%s' (age '%s') for stream '%s'", resConsumer.Name, c.groupName, age, streamID)) } } } func (c *RedisConsumer) pushError(err error) { select { case c.errorCh <- err: default: } } func (c *RedisConsumer) pushInfo(s string) { select { case c.infoCh <- s: default: } } func (c *RedisConsumer) Errors() <-chan error { return c.errorCh } func (c *RedisConsumer) Infos() <-chan string { return c.infoCh } func (c *RedisConsumer) createGroupForAllStreams(ctx context.Context) error { for streamID := range c.streams { err := createGroup(ctx, c.rdb, streamID, c.groupName) if err != nil { return err } } return nil } func createGroup(ctx context.Context, rdb redis.UniversalClient, streamID string, groupName string) error { // Creates a new consumer group that starts receiving messages from now on. // Existing messges in the queue are ignored (we don't want to overload a group with old messages) // For more details of the XGROUPCREATE api see https://redis.io/commands/xgroup-create/ err := rdb.XGroupCreateMkStream(ctx, streamID, groupName, "$").Err() if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") { return fmt.Errorf("failed to create consumer group '%s' for stream '%s': %w", groupName, streamID, err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/memory_broker.go
stream/memory_broker.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "fmt" "sync" "sync/atomic" "github.com/hashicorp/go-multierror" gonanoid "github.com/matoous/go-nanoid" ) const ( idPrefixUIDAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789" idPrefixUIDLength = 8 ) // MemoryBroker is a very basic in memory broker implementation that supports multiple streams and consumer groups. type MemoryBroker struct { // idPrefix is a random prefix the memory broker is seeded with to avoid overlaps with previous runs! idPrefix string // latestID is used to generate unique, sequentially increasing message IDs latestID uint64 // queueSize is the max size of the queues before enqueing is blocking queueSize int64 mx sync.RWMutex // messageQueues contains all streams requested for a specific group // messageQueues[streamID][groupName]: queue of messages for a specific stream and group messageQueues map[string]map[string]chan message } func NewMemoryBroker(queueSize int64) (*MemoryBroker, error) { idPrefix, err := gonanoid.Generate(idPrefixUIDAlphabet, idPrefixUIDLength) if err != nil { return nil, fmt.Errorf("failed to generate random prefix for in-memory event IDs: %w", err) } return &MemoryBroker{ idPrefix: idPrefix, latestID: 0, queueSize: queueSize, mx: sync.RWMutex{}, messageQueues: make(map[string]map[string]chan message), }, err } // enqueue enqueues a message to a stream. // NOTE: messages are only send to existing groups - groups created after completion won't get the message. // NOTE: if any of the groups' message queues is full, an aggregated error is returned. // However, the error is only returned after attempting to send the message to all groups. func (b *MemoryBroker) enqueue(streamID string, m message) (string, error) { // similar to redis, only populate the ID if's empty or requested explicitly if m.id == "" || m.id == "*" { id := atomic.AddUint64(&b.latestID, 1) m.id = fmt.Sprintf("%s-%d", b.idPrefix, id) } // the lock is for reading from the messageQueues map // NOTE: this method isn't blocking anywhere so we should be safe from deadlocking // NOTE: might be possible to optimize (potentially not even required), but okay for initial local solution. b.mx.RLock() defer b.mx.RUnlock() // get all group queues for the stream - no lock needed as it's read-only queues, ok := b.messageQueues[streamID] if !ok { // if there are no groups - discard message return "", nil } // we have to queue up the message to ALL EXISTING groups of a stream var errs error for groupName, queue := range queues { select { case queue <- m: continue default: errs = multierror.Append(errs, fmt.Errorf("queue for group '%s' is full", groupName)) } } return m.id, errs } // messages returns a read-only stream that can be used to receive messages of a stream under a specific group. // If no such stream exists yet, a new one is created, otherwise, the existing one is returned. func (b *MemoryBroker) messages(streamID string, groupName string) <-chan message { // the lock is for writing in the messageQueues map b.mx.Lock() defer b.mx.Unlock() groups, ok := b.messageQueues[streamID] if !ok { groups = make(map[string]chan message) b.messageQueues[streamID] = groups } groupQueue, ok := groups[groupName] if !ok { groupQueue = make(chan message, b.queueSize) groups[groupName] = groupQueue } return groupQueue }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/redis_producer.go
stream/redis_producer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "context" "fmt" "github.com/go-redis/redis/v8" ) type RedisProducer struct { rdb redis.UniversalClient // namespace defines the namespace of the stream keys - any stream key will be prefixed with it. namespace string // maxStreamLength defines the maximum number of entries in each stream (ring buffer). maxStreamLength int64 // approxMaxStreamLength specifies whether the maxStreamLength should be approximated. // NOTE: enabling approximation of stream length can lead to performance improvements. approxMaxStreamLength bool } func NewRedisProducer(rdb redis.UniversalClient, namespace string, maxStreamLength int64, approxMaxStreamLength bool) *RedisProducer { return &RedisProducer{ rdb: rdb, namespace: namespace, maxStreamLength: maxStreamLength, approxMaxStreamLength: approxMaxStreamLength, } } // Send sends information to the Redis stream. // Returns the message ID in case of success. func (p *RedisProducer) Send(ctx context.Context, streamID string, payload map[string]any) (string, error) { // ensure we transpose streamID using the key namespace transposedStreamID := transposeStreamID(p.namespace, streamID) // send message to stream - will create the stream if it doesn't exist yet // NOTE: response is the message ID (See https://redis.io/commands/xadd/) args := &redis.XAddArgs{ Stream: transposedStreamID, Values: payload, MaxLen: p.maxStreamLength, Approx: p.approxMaxStreamLength, ID: "*", // let redis create message ID } msgID, err := p.rdb.XAdd(ctx, args).Result() if err != nil { return "", fmt.Errorf("failed to write to stream '%s' (redis stream '%s'). Error: %w", streamID, transposedStreamID, err) } return msgID, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/options_test.go
stream/options_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "testing" "time" ) func TestWithConcurrency(t *testing.T) { t.Run("valid concurrency", func(t *testing.T) { config := &ConsumerConfig{} opt := WithConcurrency(10) opt.apply(config) if config.Concurrency != 10 { t.Errorf("expected concurrency 10, got %d", config.Concurrency) } }) t.Run("minimum valid concurrency", func(t *testing.T) { config := &ConsumerConfig{} opt := WithConcurrency(1) opt.apply(config) if config.Concurrency != 1 { t.Errorf("expected concurrency 1, got %d", config.Concurrency) } }) t.Run("maximum valid concurrency", func(t *testing.T) { config := &ConsumerConfig{} opt := WithConcurrency(MaxConcurrency) opt.apply(config) if config.Concurrency != MaxConcurrency { t.Errorf("expected concurrency %d, got %d", MaxConcurrency, config.Concurrency) } }) t.Run("zero concurrency panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for zero concurrency") } }() WithConcurrency(0) }) t.Run("negative concurrency panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for negative concurrency") } }() WithConcurrency(-1) }) t.Run("concurrency above max panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for concurrency above max") } }() WithConcurrency(MaxConcurrency + 1) }) } func TestWithMaxRetries(t *testing.T) { t.Run("valid max retries", func(t *testing.T) { config := &HandlerConfig{} opt := WithMaxRetries(5) opt.apply(config) if config.maxRetries != 5 { t.Errorf("expected maxRetries 5, got %d", config.maxRetries) } }) t.Run("zero max retries", func(t *testing.T) { config := &HandlerConfig{} opt := WithMaxRetries(0) opt.apply(config) if config.maxRetries != 0 { t.Errorf("expected maxRetries 0, got %d", config.maxRetries) } }) t.Run("maximum valid retries", func(t *testing.T) { config := &HandlerConfig{} opt := WithMaxRetries(MaxMaxRetries) opt.apply(config) if config.maxRetries != MaxMaxRetries { t.Errorf("expected maxRetries %d, got %d", MaxMaxRetries, config.maxRetries) } }) t.Run("negative max retries panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for negative max retries") } }() WithMaxRetries(-1) }) t.Run("max retries above max panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for max retries above max") } }() WithMaxRetries(MaxMaxRetries + 1) }) } func TestWithIdleTimeout(t *testing.T) { t.Run("valid idle timeout", func(t *testing.T) { config := &HandlerConfig{} timeout := 10 * time.Second opt := WithIdleTimeout(timeout) opt.apply(config) if config.idleTimeout != timeout { t.Errorf("expected idleTimeout %v, got %v", timeout, config.idleTimeout) } }) t.Run("minimum valid idle timeout", func(t *testing.T) { config := &HandlerConfig{} opt := WithIdleTimeout(MinIdleTimeout) opt.apply(config) if config.idleTimeout != MinIdleTimeout { t.Errorf("expected idleTimeout %v, got %v", MinIdleTimeout, config.idleTimeout) } }) t.Run("idle timeout below minimum panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for idle timeout below minimum") } }() WithIdleTimeout(MinIdleTimeout - 1*time.Second) }) t.Run("zero idle timeout panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected panic for zero idle timeout") } }() WithIdleTimeout(0) }) } func TestWithHandlerOptions(t *testing.T) { t.Run("applies single handler option", func(t *testing.T) { config := &ConsumerConfig{} opt := WithHandlerOptions(WithMaxRetries(10)) opt.apply(config) if config.DefaultHandlerConfig.maxRetries != 10 { t.Errorf("expected maxRetries 10, got %d", config.DefaultHandlerConfig.maxRetries) } }) t.Run("applies multiple handler options", func(t *testing.T) { config := &ConsumerConfig{} timeout := 10 * time.Second opt := WithHandlerOptions( WithMaxRetries(5), WithIdleTimeout(timeout), ) opt.apply(config) if config.DefaultHandlerConfig.maxRetries != 5 { t.Errorf("expected maxRetries 5, got %d", config.DefaultHandlerConfig.maxRetries) } if config.DefaultHandlerConfig.idleTimeout != timeout { t.Errorf("expected idleTimeout %v, got %v", timeout, config.DefaultHandlerConfig.idleTimeout) } }) t.Run("applies no handler options", func(t *testing.T) { config := &ConsumerConfig{} opt := WithHandlerOptions() opt.apply(config) // Should not panic and should leave config unchanged if config.DefaultHandlerConfig.maxRetries != 0 { t.Errorf("expected maxRetries 0, got %d", config.DefaultHandlerConfig.maxRetries) } }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/options.go
stream/options.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "fmt" "time" ) const ( // MaxConcurrency is the max number of concurrent go routines (for message handling) for a single stream consumer. MaxConcurrency = 64 // MaxMaxRetries is the max number of retries of a message for a single consumer group. MaxMaxRetries = 64 // MinIdleTimeout is the minimum time that can be configured as idle timeout for a stream consumer. MinIdleTimeout = 5 * time.Second ) // ConsumerOption is used to configure consumers. type ConsumerOption interface { apply(*ConsumerConfig) } // consumerOptionFunc allows to have functions implement the ConsumerOption interface. type consumerOptionFunc func(*ConsumerConfig) // Apply calls f(config). func (f consumerOptionFunc) apply(config *ConsumerConfig) { f(config) } // WithConcurrency sets up the concurrency of the stream consumer. func WithConcurrency(concurrency int) ConsumerOption { if concurrency < 1 || concurrency > MaxConcurrency { // misconfiguration - panic to keep options clean panic(fmt.Sprintf("provided concurrency %d is invalid - has to be between 1 and %d", concurrency, MaxConcurrency)) } return consumerOptionFunc(func(c *ConsumerConfig) { c.Concurrency = concurrency }) } // WithHandlerOptions sets up the default handler options of a stream consumer. func WithHandlerOptions(opts ...HandlerOption) ConsumerOption { return consumerOptionFunc(func(c *ConsumerConfig) { for _, opt := range opts { opt.apply(&c.DefaultHandlerConfig) } }) } // HandlerOption is used to configure the handler consuming a single stream. type HandlerOption interface { apply(*HandlerConfig) } // handlerOptionFunc allows to have functions implement the HandlerOption interface. type handlerOptionFunc func(*HandlerConfig) // Apply calls f(config). func (f handlerOptionFunc) apply(config *HandlerConfig) { f(config) } // WithMaxRetries can be used to set the max retry count for a specific handler. func WithMaxRetries(maxRetries int) HandlerOption { if maxRetries < 0 || maxRetries > MaxMaxRetries { // misconfiguration - panic to keep options clean panic(fmt.Sprintf("provided maxRetries %d is invalid - has to be between 0 and %d", maxRetries, MaxMaxRetries)) } return handlerOptionFunc(func(c *HandlerConfig) { c.maxRetries = maxRetries }) } // WithIdleTimeout can be used to set the idle timeout for a specific handler. func WithIdleTimeout(timeout time.Duration) HandlerOption { if timeout < MinIdleTimeout { // misconfiguration - panic to keep options clean panic(fmt.Sprintf("provided timeout %d is invalid - has to be longer than %s", timeout, MinIdleTimeout)) } return handlerOptionFunc(func(c *HandlerConfig) { c.idleTimeout = timeout }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/memory_consumer.go
stream/memory_consumer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "context" "errors" "fmt" "runtime/debug" "sync" "time" ) // memoryMessage extends the message object to allow tracking retries. type memoryMessage struct { message retries int64 } // MemoryConsumer consumes streams from a MemoryBroker. type MemoryConsumer struct { broker *MemoryBroker // namespace specifies the namespace of the keys - any stream key will be prefixed with it namespace string // groupName specifies the name of the consumer group. groupName string // Config is the generic consumer configuration. Config ConsumerConfig // streams is a map of all registered streams and their handlers. streams map[string]handler isStarted bool messageQueue chan memoryMessage errorCh chan error infoCh chan string } func NewMemoryConsumer(broker *MemoryBroker, namespace string, groupName string) (*MemoryConsumer, error) { if groupName == "" { return nil, errors.New("groupName can't be empty") } const queueCapacity = 500 const errorChCapacity = 64 const infoChCapacity = 64 return &MemoryConsumer{ broker: broker, namespace: namespace, groupName: groupName, streams: map[string]handler{}, Config: defaultConfig, isStarted: false, messageQueue: make(chan memoryMessage, queueCapacity), errorCh: make(chan error, errorChCapacity), infoCh: make(chan string, infoChCapacity), }, nil } func (c *MemoryConsumer) Configure(opts ...ConsumerOption) { if c.isStarted { return } for _, opt := range opts { opt.apply(&c.Config) } } func (c *MemoryConsumer) Register(streamID string, fn HandlerFunc, opts ...HandlerOption) error { if c.isStarted { return ErrAlreadyStarted } if streamID == "" { return errors.New("streamID can't be empty") } if fn == nil { return errors.New("fn can't be empty") } // transpose streamID to key namespace - no need to keep inner streamID transposedStreamID := transposeStreamID(c.namespace, streamID) if _, ok := c.streams[transposedStreamID]; ok { return fmt.Errorf("consumer is already registered for '%s' (full stream '%s')", streamID, transposedStreamID) } config := c.Config.DefaultHandlerConfig for _, opt := range opts { opt.apply(&config) } c.streams[transposedStreamID] = handler{ handle: fn, config: config, } return nil } func (c *MemoryConsumer) Start(ctx context.Context) error { if c.isStarted { return ErrAlreadyStarted } if len(c.streams) == 0 { return errors.New("no streams registered") } // mark as started before starting go routines (can't error out from here) c.isStarted = true wg := &sync.WaitGroup{} // start routines to read messages from broker for streamID := range c.streams { wg.Add(1) go func(stream string) { defer wg.Done() c.reader(ctx, stream) }(streamID) } // start workers for i := 0; i < c.Config.Concurrency; i++ { wg.Add(1) go func() { defer wg.Done() c.consume(ctx) }() } // start cleanup routing go func() { // wait for all go routines to complete wg.Wait() close(c.messageQueue) close(c.infoCh) close(c.errorCh) }() return nil } // reader reads the messages of a specific stream from the broker and puts it // into the single message queue monitored by the consumers. func (c *MemoryConsumer) reader(ctx context.Context, streamID string) { streamQueue := c.broker.messages(streamID, c.groupName) for { select { case <-ctx.Done(): return case m := <-streamQueue: c.messageQueue <- memoryMessage{ message: m, retries: 0, } } } } func (c *MemoryConsumer) consume(ctx context.Context) { for { select { case <-ctx.Done(): return case m := <-c.messageQueue: handler, ok := c.streams[m.streamID] if !ok { // we only take messages from registered streams, this should never happen. // WARNING this will discard the message c.pushError(fmt.Errorf("discard message with id '%s' from stream '%s' - doesn't belong to us", m.id, m.streamID)) continue } c.processMessage(ctx, handler, m) } } } func (c *MemoryConsumer) processMessage(ctx context.Context, handler handler, m memoryMessage) { var handlingErr error ctxWithCancel, cancelFn := context.WithCancel(ctx) defer func(err error) { // If the original execution errors out, we rely on the timeout to retry. This is to keep the behaviour same // as the redis consumer. if err == nil { cancelFn() } }(handlingErr) // Start a retry goroutine with `idleTimeout` delay go c.retryPostTimeout(ctxWithCancel, handler, m) handlingErr = func() (err error) { // Ensure that handlers don't cause panic. defer func() { if r := recover(); r != nil { c.pushError(fmt.Errorf("PANIC when processing message '%s' in stream '%s':\n%s", m.id, m.streamID, debug.Stack())) } }() return handler.handle(ctx, m.id, m.values) }() if handlingErr != nil { c.pushError(fmt.Errorf("failed to process message with id '%s' in stream '%s' (retries: %d): %w", m.id, m.streamID, m.retries, handlingErr)) } } func (c *MemoryConsumer) retryPostTimeout(ctxWithCancel context.Context, handler handler, m memoryMessage) { timer := time.NewTimer(handler.config.idleTimeout) defer timer.Stop() select { case <-timer.C: c.retryMessage(m, handler.config.maxRetries) case <-ctxWithCancel.Done(): // Retry canceled if message is processed // Drain the timer channel if it is already stopped if !timer.Stop() { <-timer.C } } } func (c *MemoryConsumer) retryMessage(m memoryMessage, maxRetries int) { if m.retries >= int64(maxRetries) { c.pushError(fmt.Errorf("discard message with id '%s' from stream '%s' - failed %d retries", m.id, m.streamID, m.retries)) return } // increase retry count m.retries++ // requeue message for a retry (needs to be in a separate go func to avoid deadlock) // IMPORTANT: this won't requeue to broker, only in this consumer's queue! go func() { // TODO: linear/exponential backoff relative to retry count might be good c.messageQueue <- m }() } func (c *MemoryConsumer) Errors() <-chan error { return c.errorCh } func (c *MemoryConsumer) Infos() <-chan string { return c.infoCh } func (c *MemoryConsumer) pushError(err error) { select { case c.errorCh <- err: default: } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/stream/memory_producer.go
stream/memory_producer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package stream import ( "context" "fmt" ) // MemoryProducer sends messages to streams of a MemoryBroker. type MemoryProducer struct { broker *MemoryBroker // namespace specifies the namespace of the keys - any stream key will be prefixed with it namespace string } func NewMemoryProducer(broker *MemoryBroker, namespace string) *MemoryProducer { return &MemoryProducer{ broker: broker, namespace: namespace, } } // Send sends information to the Broker. // Returns the message ID in case of success. func (p *MemoryProducer) Send(_ context.Context, streamID string, payload map[string]any) (string, error) { // ensure we transpose streamID using the key namespace transposedStreamID := transposeStreamID(p.namespace, streamID) msgID, err := p.broker.enqueue( transposedStreamID, message{ streamID: transposedStreamID, values: payload, }) if err != nil { return "", fmt.Errorf("failed to write to stream '%s' (full stream '%s'). Error: %w", streamID, transposedStreamID, err) } return msgID, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/wire.go
blob/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "fmt" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideStore, ) func ProvideStore(ctx context.Context, config Config) (Store, error) { switch config.Provider { case ProviderFileSystem: return NewFileSystemStore(config) case ProviderGCS: return NewGCSStore(ctx, config) default: return nil, fmt.Errorf("invalid blob store provider: %s", config.Provider) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/gcs_test.go
blob/gcs_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "testing" "time" ) func TestNewGCSStore_InvalidConfig(t *testing.T) { ctx := context.Background() tests := []struct { name string config Config expectError bool }{ { name: "empty config", config: Config{ Provider: ProviderGCS, }, expectError: true, // Should fail without proper credentials }, { name: "config with non-existent key file", config: Config{ Provider: ProviderGCS, KeyPath: "/non/existent/path/key.json", Bucket: "test-bucket", }, expectError: true, // Should fail with invalid key path }, { name: "config with empty bucket", config: Config{ Provider: ProviderGCS, KeyPath: "/tmp/fake-key.json", Bucket: "", }, expectError: true, // Should fail with empty bucket }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { store, err := NewGCSStore(ctx, test.config) if test.expectError { if err == nil { t.Error("expected error but got none") } if store != nil { t.Error("expected nil store on error") } return } if err != nil { t.Errorf("unexpected error: %v", err) } if store == nil { t.Error("expected non-nil store") } }) } } func TestGCSStore_ConfigValidation(t *testing.T) { tests := []struct { name string config Config }{ { name: "config with service account key", config: Config{ Provider: ProviderGCS, KeyPath: "/path/to/key.json", Bucket: "test-bucket", }, }, { name: "config with impersonation", config: Config{ Provider: ProviderGCS, Bucket: "test-bucket", TargetPrincipal: "service-account@project.iam.gserviceaccount.com", ImpersonationLifetime: time.Hour, }, }, { name: "config with zero impersonation lifetime", config: Config{ Provider: ProviderGCS, Bucket: "test-bucket", TargetPrincipal: "service-account@project.iam.gserviceaccount.com", ImpersonationLifetime: 0, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // Test that config fields are properly set config := test.config if config.Provider != ProviderGCS { t.Errorf("expected provider %q, got %q", ProviderGCS, config.Provider) } // Verify other fields are accessible _ = config.Bucket _ = config.KeyPath _ = config.TargetPrincipal _ = config.ImpersonationLifetime }) } } func TestGCSStore_Interface(_ *testing.T) { // Test that GCSStore would implement Store interface // Note: We can't actually create a GCSStore without valid GCS credentials, // but we can verify the interface compliance at compile time // This will fail to compile if GCSStore doesn't implement Store var _ Store = (*GCSStore)(nil) } func TestGCSStore_DefaultScope(t *testing.T) { expectedScope := "https://www.googleapis.com/auth/cloud-platform" if defaultScope != expectedScope { t.Errorf("expected default scope %q, got %q", expectedScope, defaultScope) } } // Note: More comprehensive tests for GCSStore would require: // 1. Mock GCS client or test environment // 2. Valid GCS credentials for integration tests // 3. Test bucket setup // These tests focus on the parts that can be tested without external dependencies.
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/config.go
blob/config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import "time" type Provider string const ( ProviderGCS Provider = "gcs" ProviderFileSystem Provider = "filesystem" ) type Config struct { Provider Provider Bucket string KeyPath string TargetPrincipal string ImpersonationLifetime time.Duration }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/interface.go
blob/interface.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "errors" "io" "time" ) var ( ErrNotFound = errors.New("resource not found") ErrNotSupported = errors.New("not supported") ) type Store interface { // Upload uploads a file to the blob store. Upload(ctx context.Context, file io.Reader, filePath string) error // GetSignedURL returns the URL for a file in the blob store. GetSignedURL(ctx context.Context, filePath string, expire time.Time, opts ...SignURLOption) (string, error) // Download returns a reader for a file in the blob store. Download(ctx context.Context, filePath string) (io.ReadCloser, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/filesystem_test.go
blob/filesystem_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "errors" "io" "os" "path/filepath" "strings" "testing" "time" ) func TestNewFileSystemStore(t *testing.T) { tests := []struct { name string config Config expected string }{ { name: "basic config", config: Config{ Bucket: "/tmp/test-storage", }, expected: "/tmp/test-storage", }, { name: "empty bucket", config: Config{ Bucket: "", }, expected: "", }, { name: "relative path", config: Config{ Bucket: "relative/path", }, expected: "relative/path", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { store, err := NewFileSystemStore(test.config) if err != nil { t.Fatalf("unexpected error creating filesystem store: %v", err) } fsStore, ok := store.(*FileSystemStore) if !ok { t.Fatal("expected FileSystemStore type") } if fsStore.basePath != test.expected { t.Errorf("expected base path %q, got %q", test.expected, fsStore.basePath) } }) } } func TestFileSystemStore_Upload(t *testing.T) { // Create temporary directory for testing tempDir, err := os.MkdirTemp("", "blob-test-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) } defer os.RemoveAll(tempDir) store := &FileSystemStore{basePath: tempDir} ctx := context.Background() tests := []struct { name string filePath string content string expectError bool errorCheck func(error) bool }{ { name: "simple file upload", filePath: "test.txt", content: "hello world", expectError: false, }, { name: "nested directory upload", filePath: "subdir/nested/file.txt", content: "nested content", expectError: false, }, { name: "empty file", filePath: "empty.txt", content: "", expectError: false, }, { name: "file with special characters", filePath: "special-file_123.txt", content: "special content", expectError: false, }, { name: "large content", filePath: "large.txt", content: strings.Repeat("a", 10000), expectError: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { reader := strings.NewReader(test.content) err := store.Upload(ctx, reader, test.filePath) if test.expectError { if err == nil { t.Error("expected error but got none") } if test.errorCheck != nil && !test.errorCheck(err) { t.Errorf("error check failed for error: %v", err) } return } if err != nil { t.Fatalf("unexpected error: %v", err) } // Verify file was created and has correct content fullPath := filepath.Join(tempDir, test.filePath) data, err := os.ReadFile(fullPath) if err != nil { t.Fatalf("failed to read uploaded file: %v", err) } if string(data) != test.content { t.Errorf("expected content %q, got %q", test.content, string(data)) } }) } } func TestFileSystemStore_Upload_DirectoryCreation(t *testing.T) { tempDir, err := os.MkdirTemp("", "blob-test-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) } defer os.RemoveAll(tempDir) store := &FileSystemStore{basePath: tempDir} ctx := context.Background() // Test that nested directories are created automatically filePath := "level1/level2/level3/file.txt" content := "nested file content" reader := strings.NewReader(content) err = store.Upload(ctx, reader, filePath) if err != nil { t.Fatalf("unexpected error: %v", err) } // Verify the directory structure was created fullPath := filepath.Join(tempDir, filePath) if _, err := os.Stat(fullPath); os.IsNotExist(err) { t.Error("file was not created") } // Verify directory exists dirPath := filepath.Dir(fullPath) if _, err := os.Stat(dirPath); os.IsNotExist(err) { t.Error("directory was not created") } } func TestFileSystemStore_Download(t *testing.T) { tempDir, err := os.MkdirTemp("", "blob-test-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) } defer os.RemoveAll(tempDir) store := &FileSystemStore{basePath: tempDir} ctx := context.Background() // Create test files testFiles := map[string]string{ "test1.txt": "content1", "subdir/test2.txt": "content2", "empty.txt": "", "large.txt": strings.Repeat("x", 5000), } for filePath, content := range testFiles { fullPath := filepath.Join(tempDir, filePath) dir := filepath.Dir(fullPath) if err := os.MkdirAll(dir, 0755); err != nil { t.Fatalf("failed to create directory: %v", err) } if err := os.WriteFile(fullPath, []byte(content), 0600); err != nil { t.Fatalf("failed to create test file: %v", err) } } tests := []struct { name string filePath string expected string expectError bool errorType error }{ { name: "existing file", filePath: "test1.txt", expected: "content1", expectError: false, }, { name: "nested file", filePath: "subdir/test2.txt", expected: "content2", expectError: false, }, { name: "empty file", filePath: "empty.txt", expected: "", expectError: false, }, { name: "large file", filePath: "large.txt", expected: strings.Repeat("x", 5000), expectError: false, }, { name: "non-existent file", filePath: "nonexistent.txt", expectError: true, errorType: ErrNotFound, }, { name: "non-existent nested file", filePath: "nonexistent/file.txt", expectError: true, errorType: ErrNotFound, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { reader, err := store.Download(ctx, test.filePath) if test.expectError { if err == nil { t.Error("expected error but got none") } if test.errorType != nil && !errors.Is(err, test.errorType) { t.Errorf("expected error type %v, got %v", test.errorType, err) } return } if err != nil { t.Fatalf("unexpected error: %v", err) } defer reader.Close() data, err := io.ReadAll(reader) if err != nil { t.Fatalf("failed to read downloaded content: %v", err) } if string(data) != test.expected { t.Errorf("expected content %q, got %q", test.expected, string(data)) } }) } } func TestFileSystemStore_GetSignedURL(t *testing.T) { store := &FileSystemStore{basePath: "/tmp"} ctx := context.Background() // Test that GetSignedURL returns ErrNotSupported url, err := store.GetSignedURL(ctx, "test.txt", time.Now().Add(time.Hour)) if !errors.Is(err, ErrNotSupported) { t.Errorf("expected ErrNotSupported, got %v", err) } if url != "" { t.Errorf("expected empty URL, got %q", url) } } func TestFileSystemStore_GetSignedURL_WithOptions(t *testing.T) { store := &FileSystemStore{basePath: "/tmp"} ctx := context.Background() // Test with various options options := []SignURLOption{ SignWithMethod("POST"), SignWithContentType("application/json"), SignWithHeaders([]string{"Authorization"}), } url, err := store.GetSignedURL(ctx, "test.txt", time.Now().Add(time.Hour), options...) if !errors.Is(err, ErrNotSupported) { t.Errorf("expected ErrNotSupported, got %v", err) } if url != "" { t.Errorf("expected empty URL, got %q", url) } } func TestFileSystemStore_Upload_ErrorCases(t *testing.T) { // Test with invalid base path (read-only directory) if os.Getuid() != 0 { // Skip if running as root readOnlyDir, err := os.MkdirTemp("", "readonly-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) } defer os.RemoveAll(readOnlyDir) // Make directory read-only if err := os.Chmod(readOnlyDir, 0444); err != nil { t.Fatalf("failed to make directory read-only: %v", err) } store := &FileSystemStore{basePath: readOnlyDir} ctx := context.Background() reader := strings.NewReader("test content") err = store.Upload(ctx, reader, "test.txt") if err == nil { t.Error("expected error when writing to read-only directory") } } } func TestFileSystemStore_Interface(t *testing.T) { // Test that FileSystemStore implements Store interface var _ Store = &FileSystemStore{} // Test that NewFileSystemStore returns Store interface config := Config{Bucket: "/tmp"} store, err := NewFileSystemStore(config) if err != nil { t.Fatalf("unexpected error: %v", err) } _ = store }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/filesystem.go
blob/filesystem.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "errors" "fmt" "io" "io/fs" "os" "path" "time" "github.com/rs/zerolog/log" ) const ( fileDiskPathFmt = "%s/%s" ) type FileSystemStore struct { basePath string } func NewFileSystemStore(cfg Config) (Store, error) { return &FileSystemStore{ basePath: cfg.Bucket, }, nil } func (c FileSystemStore) Upload(ctx context.Context, file io.Reader, filePath string, ) error { fileDiskPath := fmt.Sprintf(fileDiskPathFmt, c.basePath, filePath) dir, _ := path.Split(fileDiskPath) if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) { err = os.MkdirAll(dir, os.ModeDir|os.ModePerm) if err != nil { return fmt.Errorf("failed to create parent directory for the file: %w", err) } } destinationFile, err := os.Create(fileDiskPath) if err != nil { return fmt.Errorf("failed to create file: %w", err) } defer func() { cErr := destinationFile.Close() if cErr != nil { log.Ctx(ctx).Warn().Err(cErr). Msgf("failed to close destination file %q in directory %q", filePath, c.basePath) } }() if _, err := io.Copy(destinationFile, file); err != nil { // Remove the file if it was created. removeErr := os.Remove(fileDiskPath) if removeErr != nil { // Best effort attempt to remove the file on write failure. log.Ctx(ctx).Warn().Err(removeErr).Msgf( "failed to cleanup file %q in directory %q after write to filesystem failed with %s", filePath, c.basePath, err) } return fmt.Errorf("failed to write file to filesystem: %w", err) } return nil } func (c *FileSystemStore) GetSignedURL( context.Context, string, time.Time, ...SignURLOption) (string, error) { return "", ErrNotSupported } func (c *FileSystemStore) Download(_ context.Context, filePath string) (io.ReadCloser, error) { fileDiskPath := fmt.Sprintf(fileDiskPathFmt, c.basePath, filePath) file, err := os.Open(fileDiskPath) if errors.Is(err, fs.ErrNotExist) { return nil, ErrNotFound } if err != nil { return nil, fmt.Errorf("failed to open file: %w", err) } return io.ReadCloser(file), nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/gcs.go
blob/gcs.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "context" "errors" "fmt" "io" "net/http" "time" "cloud.google.com/go/storage" "github.com/rs/zerolog/log" "golang.org/x/oauth2" "google.golang.org/api/impersonate" "google.golang.org/api/option" ) // scopes best practice: https://cloud.google.com/compute/docs/access/service-accounts#scopes_best_practice const defaultScope = "https://www.googleapis.com/auth/cloud-platform" type GCSStore struct { // Bucket is the name of the GCS bucket to use. cachedClient *storage.Client config Config tokenExpirationTime time.Time } func NewGCSStore(ctx context.Context, cfg Config) (Store, error) { // Validate bucket name is provided if cfg.Bucket == "" { return nil, errors.New("bucket name is required") } switch { case cfg.KeyPath != "": // Use service account key file [Development and Non-GCP environments] client, err := storage.NewClient(ctx, option.WithCredentialsFile(cfg.KeyPath)) if err != nil { return nil, fmt.Errorf("failed to create GCS client with service account key: %w", err) } return &GCSStore{ config: cfg, cachedClient: client, tokenExpirationTime: time.Now().Add(cfg.ImpersonationLifetime), }, nil case cfg.TargetPrincipal == "": // Use direct Workload Identity [GKE environments with direct SA access] client, err := storage.NewClient(ctx) if err != nil { return nil, fmt.Errorf("failed to create GCS client with default credentials: %w", err) } return &GCSStore{ config: cfg, cachedClient: client, // No token expiration for default credentials - managed by GCP tokenExpirationTime: time.Time{}, // Zero time - never expires }, nil default: // Use Workload Identity with impersonation [GKE environments with SA impersonation] client, err := createNewImpersonatedClient(ctx, cfg) if err != nil { return nil, fmt.Errorf("failed to create GCS client with workload identity impersonation: %w", err) } return &GCSStore{ config: cfg, cachedClient: client, tokenExpirationTime: time.Now().Add(cfg.ImpersonationLifetime), }, nil } } func (c *GCSStore) Upload(ctx context.Context, file io.Reader, filePath string) error { gcsClient, err := c.getClient(ctx) if err != nil { return fmt.Errorf("failed to retrieve latest client: %w", err) } bkt := gcsClient.Bucket(c.config.Bucket) wc := bkt.Object(filePath).NewWriter(ctx) defer func() { cErr := wc.Close() if cErr != nil { log.Ctx(ctx).Warn().Err(cErr). Msgf("failed to close gcs blob writer for file %q in bucket %q", filePath, c.config.Bucket) } }() if _, err := io.Copy(wc, file); err != nil { // Best effort attempt to delete the file on upload failure. deleteErr := gcsClient.Bucket(c.config.Bucket).Object(filePath).Delete(ctx) if deleteErr != nil { log.Ctx(ctx).Warn().Err(deleteErr).Msgf( "failed to cleanup file %q from bucket %q after write to gcs failed with %s", filePath, c.config.Bucket, err) } return fmt.Errorf("failed to write file to GCS: %w", err) } return nil } func (c *GCSStore) GetSignedURL( ctx context.Context, filePath string, expire time.Time, opts ...SignURLOption) (string, error) { gcsClient, err := c.getClient(ctx) if err != nil { return "", fmt.Errorf("failed to retrieve latest client: %w", err) } config := SignURLConfig{ Method: http.MethodGet, } for _, opt := range opts { opt.Apply(&config) } bkt := gcsClient.Bucket(c.config.Bucket) signedURL, err := bkt.SignedURL(filePath, &storage.SignedURLOptions{ Method: config.Method, Expires: expire, ContentType: config.ContentType, Headers: config.Headers, QueryParameters: config.QueryParameters, Insecure: config.Insecure, }) if err != nil { return "", fmt.Errorf("failed to create signed URL for file %q: %w", filePath, err) } return signedURL, nil } func (c *GCSStore) Download(ctx context.Context, filePath string) (io.ReadCloser, error) { gcsClient, err := c.getClient(ctx) if err != nil { return nil, fmt.Errorf("failed to retrieve latest client: %w", err) } bkt := gcsClient.Bucket(c.config.Bucket) rc, err := bkt.Object(filePath).NewReader(ctx) if err != nil { if errors.Is(err, storage.ErrObjectNotExist) { return nil, ErrNotFound } return nil, fmt.Errorf("failed to create reader for file %q in bucket %q: %w", filePath, c.config.Bucket, err) } return rc, nil } func createNewImpersonatedClient(ctx context.Context, cfg Config) (*storage.Client, error) { // Use workload identity impersonation default credentials (GKE environment) ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: cfg.TargetPrincipal, Scopes: []string{defaultScope}, // Required field Lifetime: cfg.ImpersonationLifetime, }) if err != nil { return nil, fmt.Errorf("failed to impersonate the client service account %q: %w", cfg.TargetPrincipal, err) } // Generate a new token token, err := ts.Token() if err != nil { return nil, fmt.Errorf("failed to refresh token from impersonated credentials: %w", err) } client, err := storage.NewClient(ctx, option.WithTokenSource(oauth2.StaticTokenSource(token))) if err != nil { return nil, fmt.Errorf("failed to create GCS client with workload identity impersonation: %w", err) } return client, nil } func (c *GCSStore) getClient(ctx context.Context) (*storage.Client, error) { // Skip token refresh for direct Workload Identity (no impersonation) if c.config.KeyPath == "" && c.config.TargetPrincipal == "" { return c.cachedClient, nil } err := c.checkAndRefreshToken(ctx) if err != nil { return nil, fmt.Errorf("failed to refresh token: %w", err) } return c.cachedClient, nil } func (c *GCSStore) checkAndRefreshToken(ctx context.Context) error { if time.Now().Before(c.tokenExpirationTime) { return nil } now := time.Now() client, err := createNewImpersonatedClient(ctx, c.config) if err != nil { return fmt.Errorf("failed to create GCS client with workload identity impersonation after expiration: %w", err) } c.cachedClient = client c.tokenExpirationTime = now.Add(c.config.ImpersonationLifetime) return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/config_test.go
blob/config_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "testing" "time" ) func TestProviderConstants(t *testing.T) { tests := []struct { name string provider Provider expected string }{ { name: "GCS provider", provider: ProviderGCS, expected: "gcs", }, { name: "FileSystem provider", provider: ProviderFileSystem, expected: "filesystem", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if string(test.provider) != test.expected { t.Errorf("expected provider %q, got %q", test.expected, string(test.provider)) } }) } } func TestConfigStruct(t *testing.T) { tests := []struct { name string config Config }{ { name: "empty config", config: Config{}, }, { name: "GCS config", config: Config{ Provider: ProviderGCS, Bucket: "test-bucket", KeyPath: "/path/to/key.json", TargetPrincipal: "test@example.com", ImpersonationLifetime: time.Hour, }, }, { name: "FileSystem config", config: Config{ Provider: ProviderFileSystem, Bucket: "/local/storage/path", }, }, { name: "config with zero duration", config: Config{ Provider: ProviderGCS, ImpersonationLifetime: 0, }, }, { name: "config with negative duration", config: Config{ Provider: ProviderGCS, ImpersonationLifetime: -time.Hour, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // Test that the config can be created and accessed config := test.config // Verify provider field if config.Provider != test.config.Provider { t.Errorf("expected provider %q, got %q", test.config.Provider, config.Provider) } // Verify bucket field if config.Bucket != test.config.Bucket { t.Errorf("expected bucket %q, got %q", test.config.Bucket, config.Bucket) } // Verify key path field if config.KeyPath != test.config.KeyPath { t.Errorf("expected key path %q, got %q", test.config.KeyPath, config.KeyPath) } // Verify target principal field if config.TargetPrincipal != test.config.TargetPrincipal { t.Errorf("expected target principal %q, got %q", test.config.TargetPrincipal, config.TargetPrincipal) } // Verify impersonation lifetime field if config.ImpersonationLifetime != test.config.ImpersonationLifetime { t.Errorf("expected impersonation lifetime %v, got %v", test.config.ImpersonationLifetime, config.ImpersonationLifetime) } }) } } func TestProviderStringConversion(t *testing.T) { // Test that Provider type can be converted to string gcsStr := string(ProviderGCS) if gcsStr != "gcs" { t.Errorf("expected 'gcs', got %q", gcsStr) } fsStr := string(ProviderFileSystem) if fsStr != "filesystem" { t.Errorf("expected 'filesystem', got %q", fsStr) } } func TestProviderComparison(t *testing.T) { // Test provider equality if ProviderGCS == ProviderFileSystem { t.Error("ProviderGCS should not equal ProviderFileSystem") } if ProviderGCS == ProviderFileSystem { t.Error("ProviderGCS should not equal ProviderFileSystem") } if ProviderFileSystem == ProviderGCS { t.Error("ProviderFileSystem should not equal ProviderGCS") } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/options_test.go
blob/options_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "net/http" "net/url" "reflect" "testing" ) func TestSignURLConfig(t *testing.T) { tests := []struct { name string config SignURLConfig }{ { name: "empty config", config: SignURLConfig{}, }, { name: "full config", config: SignURLConfig{ Method: "POST", ContentType: "application/json", Headers: []string{"Authorization", "X-Custom-Header"}, QueryParameters: url.Values{"param1": []string{"value1"}, "param2": []string{"value2"}}, Insecure: true, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := test.config if config.Method != test.config.Method { t.Errorf("expected method %q, got %q", test.config.Method, config.Method) } if config.ContentType != test.config.ContentType { t.Errorf("expected content type %q, got %q", test.config.ContentType, config.ContentType) } if !reflect.DeepEqual(config.Headers, test.config.Headers) { t.Errorf("expected headers %v, got %v", test.config.Headers, config.Headers) } if !reflect.DeepEqual(config.QueryParameters, test.config.QueryParameters) { t.Errorf("expected query parameters %v, got %v", test.config.QueryParameters, config.QueryParameters) } if config.Insecure != test.config.Insecure { t.Errorf("expected insecure %v, got %v", test.config.Insecure, config.Insecure) } }) } } func TestSignWithMethod(t *testing.T) { tests := []struct { name string method string expected string }{ { name: "GET method", method: "GET", expected: "GET", }, { name: "POST method", method: "POST", expected: "POST", }, { name: "PUT method", method: "PUT", expected: "PUT", }, { name: "DELETE method", method: "DELETE", expected: "DELETE", }, { name: "empty method", method: "", expected: "", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := &SignURLConfig{} option := SignWithMethod(test.method) option.Apply(config) if config.Method != test.expected { t.Errorf("expected method %q, got %q", test.expected, config.Method) } }) } } func TestSignWithContentType(t *testing.T) { tests := []struct { name string contentType string expected string }{ { name: "JSON content type", contentType: "application/json", expected: "application/json", }, { name: "XML content type", contentType: "application/xml", expected: "application/xml", }, { name: "plain text content type", contentType: "text/plain", expected: "text/plain", }, { name: "empty content type", contentType: "", expected: "", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := &SignURLConfig{} option := SignWithContentType(test.contentType) option.Apply(config) if config.ContentType != test.expected { t.Errorf("expected content type %q, got %q", test.expected, config.ContentType) } }) } } func TestSignWithHeaders(t *testing.T) { tests := []struct { name string headers []string expected []string }{ { name: "single header", headers: []string{"Authorization"}, expected: []string{"Authorization"}, }, { name: "multiple headers", headers: []string{"Authorization", "X-Custom-Header", "Content-Type"}, expected: []string{"Authorization", "X-Custom-Header", "Content-Type"}, }, { name: "empty headers", headers: []string{}, expected: []string{}, }, { name: "nil headers", headers: nil, expected: nil, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := &SignURLConfig{} option := SignWithHeaders(test.headers) option.Apply(config) if !reflect.DeepEqual(config.Headers, test.expected) { t.Errorf("expected headers %v, got %v", test.expected, config.Headers) } }) } } func TestSignWithQueryParameters(t *testing.T) { tests := []struct { name string params url.Values expected url.Values }{ { name: "single parameter", params: url.Values{"key": []string{"value"}}, expected: url.Values{"key": []string{"value"}}, }, { name: "multiple parameters", params: url.Values{"key1": []string{"value1"}, "key2": []string{"value2", "value3"}}, expected: url.Values{"key1": []string{"value1"}, "key2": []string{"value2", "value3"}}, }, { name: "empty parameters", params: url.Values{}, expected: url.Values{}, }, { name: "nil parameters", params: nil, expected: nil, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := &SignURLConfig{} option := SignWithQueryParameters(test.params) option.Apply(config) if !reflect.DeepEqual(config.QueryParameters, test.expected) { t.Errorf("expected query parameters %v, got %v", test.expected, config.QueryParameters) } }) } } func TestSignWithInsecure(t *testing.T) { tests := []struct { name string insecure bool expected bool }{ { name: "insecure true", insecure: true, expected: true, }, { name: "insecure false", insecure: false, expected: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { config := &SignURLConfig{} option := SignWithInsecure(test.insecure) option.Apply(config) if config.Insecure != test.expected { t.Errorf("expected insecure %v, got %v", test.expected, config.Insecure) } }) } } func TestSignedURLConfigFunc(t *testing.T) { // Test that SignedURLConfigFunc implements SignURLOption interface var _ SignURLOption = SignedURLConfigFunc(func(_ *SignURLConfig) {}) // Test custom function customFunc := SignedURLConfigFunc(func(opts *SignURLConfig) { opts.Method = "CUSTOM" opts.ContentType = "custom/type" opts.Insecure = true }) config := &SignURLConfig{} customFunc.Apply(config) if config.Method != "CUSTOM" { t.Errorf("expected method 'CUSTOM', got %q", config.Method) } if config.ContentType != "custom/type" { t.Errorf("expected content type 'custom/type', got %q", config.ContentType) } if !config.Insecure { t.Error("expected insecure to be true") } } func TestMultipleOptions(t *testing.T) { config := &SignURLConfig{} // Apply multiple options options := []SignURLOption{ SignWithMethod("POST"), SignWithContentType("application/json"), SignWithHeaders([]string{"Authorization", "X-Custom"}), SignWithQueryParameters(url.Values{"test": []string{"value"}}), SignWithInsecure(true), } for _, option := range options { option.Apply(config) } // Verify all options were applied if config.Method != http.MethodPost { t.Errorf("expected method 'POST', got %q", config.Method) } if config.ContentType != "application/json" { t.Errorf("expected content type 'application/json', got %q", config.ContentType) } expectedHeaders := []string{"Authorization", "X-Custom"} if !reflect.DeepEqual(config.Headers, expectedHeaders) { t.Errorf("expected headers %v, got %v", expectedHeaders, config.Headers) } expectedParams := url.Values{"test": []string{"value"}} if !reflect.DeepEqual(config.QueryParameters, expectedParams) { t.Errorf("expected query parameters %v, got %v", expectedParams, config.QueryParameters) } if !config.Insecure { t.Error("expected insecure to be true") } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/options.go
blob/options.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "net/url" ) type SignURLConfig struct { Method string ContentType string Headers []string QueryParameters url.Values Insecure bool } type SignURLOption interface { Apply(*SignURLConfig) } type SignedURLConfigFunc func(opts *SignURLConfig) func (opts SignedURLConfigFunc) Apply(config *SignURLConfig) { opts(config) } // SignWithMethod use http method for signing url request. func SignWithMethod(method string) SignedURLConfigFunc { return func(opts *SignURLConfig) { opts.Method = method } } // SignWithContentType use http content type for signing url request. func SignWithContentType(contentType string) SignedURLConfigFunc { return func(opts *SignURLConfig) { opts.ContentType = contentType } } // SignWithHeaders use http headers for signing url request. func SignWithHeaders(headers []string) SignedURLConfigFunc { return func(opts *SignURLConfig) { opts.Headers = headers } } // SignWithQueryParameters use http query params for signing url request. func SignWithQueryParameters(queryParameters url.Values) SignedURLConfigFunc { return func(opts *SignURLConfig) { opts.QueryParameters = queryParameters } } // SignWithInsecure use http insecure (no https) for signing url request. func SignWithInsecure(insecure bool) SignedURLConfigFunc { return func(opts *SignURLConfig) { opts.Insecure = insecure } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/blob/interface_test.go
blob/interface_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blob import ( "errors" "testing" ) func TestErrors(t *testing.T) { tests := []struct { name string err error expected string }{ { name: "ErrNotFound", err: ErrNotFound, expected: "resource not found", }, { name: "ErrNotSupported", err: ErrNotSupported, expected: "not supported", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if got := test.err.Error(); got != test.expected { t.Errorf("expected error message %q, got %q", test.expected, got) } }) } } func TestErrorsAreDistinct(t *testing.T) { if errors.Is(ErrNotFound, ErrNotSupported) { t.Error("ErrNotFound should not be the same as ErrNotSupported") } if errors.Is(ErrNotSupported, ErrNotFound) { t.Error("ErrNotSupported should not be the same as ErrNotFound") } } func TestErrorsCanBeWrapped(t *testing.T) { wrappedNotFound := errors.New("wrapped: " + ErrNotFound.Error()) wrappedNotSupported := errors.New("wrapped: " + ErrNotSupported.Error()) if wrappedNotFound.Error() != "wrapped: resource not found" { t.Errorf("unexpected wrapped error message: %s", wrappedNotFound.Error()) } if wrappedNotSupported.Error() != "wrapped: not supported" { t.Errorf("unexpected wrapped error message: %s", wrappedNotSupported.Error()) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/cache.go
cache/cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "context" ) // Cache is an abstraction of a simple cache. type Cache[K any, V any] interface { Stats() (int64, int64) Get(ctx context.Context, key K) (V, error) Evict(ctx context.Context, key K) } // ExtendedCache is an extension of the simple cache abstraction that adds mapping functionality. type ExtendedCache[K comparable, V Identifiable[K]] interface { Cache[K, V] Map(ctx context.Context, keys []K) (map[K]V, error) } type Identifiable[K comparable] interface { Identifier() K } type Getter[K any, V any] interface { Find(ctx context.Context, key K) (V, error) } type ExtendedGetter[K comparable, V Identifiable[K]] interface { Getter[K, V] FindMany(ctx context.Context, keys []K) ([]V, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/cache_test.go
cache/cache_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "reflect" "testing" ) func TestDeduplicate(t *testing.T) { tests := []struct { name string input []int expected []int }{ { name: "empty", input: nil, expected: nil, }, { name: "one-element", input: []int{1}, expected: []int{1}, }, { name: "one-element-duplicated", input: []int{1, 1}, expected: []int{1}, }, { name: "two-elements", input: []int{2, 1}, expected: []int{1, 2}, }, { name: "three-elements", input: []int{2, 2, 3, 3, 1, 1}, expected: []int{1, 2, 3}, }, { name: "many-elements", input: []int{2, 5, 1, 2, 3, 3, 4, 5, 1, 1}, expected: []int{1, 2, 3, 4, 5}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.input = Deduplicate(test.input) if want, got := test.expected, test.input; !reflect.DeepEqual(want, got) { t.Errorf("failed - want=%v, got=%v", want, got) return } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/ttl_cache.go
cache/ttl_cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "context" "fmt" "slices" "sync" "sync/atomic" "time" "golang.org/x/exp/constraints" ) // TTLCache is a generic TTL based cache that stores objects for the specified period. // The TTLCache has no maximum capacity, so the idea is to store objects for short period. // The goal of the TTLCache is to reduce database load. // Every instance of TTLCache has a background routine that purges stale items. type TTLCache[K comparable, V any] struct { mx sync.RWMutex cache map[K]cacheEntry[V] purgeStop chan struct{} getter Getter[K, V] maxAge time.Duration countHit atomic.Int64 countMiss atomic.Int64 } // ExtendedTTLCache is an extended version of the TTLCache. type ExtendedTTLCache[K constraints.Ordered, V Identifiable[K]] struct { TTLCache[K, V] getter ExtendedGetter[K, V] } type cacheEntry[V any] struct { added time.Time data V } // New creates a new TTLCache instance and a background routine // that periodically purges stale items. func New[K comparable, V any](getter Getter[K, V], maxAge time.Duration) *TTLCache[K, V] { c := &TTLCache[K, V]{ cache: make(map[K]cacheEntry[V]), purgeStop: make(chan struct{}), getter: getter, maxAge: maxAge, } go c.purger() return c } // NewExtended creates a new TTLCacheExtended instance and a background routine // that periodically purges stale items. func NewExtended[K constraints.Ordered, V Identifiable[K]]( getter ExtendedGetter[K, V], maxAge time.Duration, ) *ExtendedTTLCache[K, V] { c := &ExtendedTTLCache[K, V]{ TTLCache: TTLCache[K, V]{ cache: make(map[K]cacheEntry[V]), purgeStop: make(chan struct{}), getter: getter, maxAge: maxAge, }, getter: getter, } go c.purger() return c } // purger periodically evicts stale items from the Cache. func (c *TTLCache[K, V]) purger() { purgeTick := time.NewTicker(time.Minute) defer purgeTick.Stop() for { select { case <-c.purgeStop: return case now := <-purgeTick.C: c.mx.Lock() for id, v := range c.cache { if now.Sub(v.added) >= c.maxAge { delete(c.cache, id) } } c.mx.Unlock() } } } // Stop stops the internal purger of stale elements. func (c *TTLCache[K, V]) Stop() { close(c.purgeStop) } // Stats returns number of cache hits and misses and can be used to monitor the cache efficiency. func (c *TTLCache[K, V]) Stats() (int64, int64) { return c.countHit.Load(), c.countMiss.Load() } func (c *TTLCache[K, V]) Evict(_ context.Context, key K) { c.mx.Lock() delete(c.cache, key) c.mx.Unlock() } func (c *TTLCache[K, V]) EvictAll(_ context.Context) { c.mx.Lock() clear(c.cache) c.mx.Unlock() } func (c *TTLCache[K, V]) fetch(key K, now time.Time) (V, bool) { c.mx.RLock() defer c.mx.RUnlock() item, ok := c.cache[key] if !ok || now.Sub(item.added) > c.maxAge { c.countMiss.Add(1) var nothing V return nothing, false } c.countHit.Add(1) // we deliberately don't update the `item.added` timestamp for `now` because // we want to cache the items only for a short period. return item.data, true } // Map returns map with all objects requested through the slice of IDs. func (c *ExtendedTTLCache[K, V]) Map(ctx context.Context, keys []K) (map[K]V, error) { m := make(map[K]V) now := time.Now() keys = Deduplicate(keys) // Check what's already available in the cache. var idx int for idx < len(keys) { key := keys[idx] item, ok := c.fetch(key, now) if !ok { idx++ continue } // found in cache: Add to the result map and remove the ID from the list. m[key] = item keys[idx] = keys[len(keys)-1] keys = keys[:len(keys)-1] } if len(keys) == 0 { return m, nil } // Pull entries from the getter that are not in the cache. items, err := c.getter.FindMany(ctx, keys) if err != nil { return nil, fmt.Errorf("cache: failed to find many: %w", err) } c.mx.Lock() defer c.mx.Unlock() for _, item := range items { id := item.Identifier() m[id] = item c.cache[id] = cacheEntry[V]{ added: now, data: item, } } return m, nil } // Get returns one object by its ID. func (c *TTLCache[K, V]) Get(ctx context.Context, key K) (V, error) { now := time.Now() var nothing V item, ok := c.fetch(key, now) if ok { return item, nil } item, err := c.getter.Find(ctx, key) if err != nil { return nothing, fmt.Errorf("cache: failed to find one: %w", err) } c.mx.Lock() c.cache[key] = cacheEntry[V]{ added: now, data: item, } c.mx.Unlock() return item, nil } // Deduplicate is a utility function that removes duplicates from slice. func Deduplicate[V constraints.Ordered](slice []V) []V { if len(slice) <= 1 { return slice } slices.Sort(slice) pointer := 0 for i := 1; i < len(slice); i++ { if slice[pointer] != slice[i] { pointer++ slice[pointer] = slice[i] } } return slice[:pointer+1] }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/no_cache.go
cache/no_cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "context" ) type NoCache[K any, V any] struct { getter Getter[K, V] } func NewNoCache[K any, V any](getter Getter[K, V]) NoCache[K, V] { return NoCache[K, V]{ getter: getter, } } func (c NoCache[K, V]) Stats() (int64, int64) { return 0, 0 } func (c NoCache[K, V]) Get(ctx context.Context, key K) (V, error) { return c.getter.Find(ctx, key) } func (c NoCache[K, V]) Evict(context.Context, K) {}
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/redis_cache.go
cache/redis_cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "context" "errors" "fmt" "sync/atomic" "time" "github.com/go-redis/redis/v8" ) type LogErrFn func(context.Context, error) type Redis[K any, V any] struct { client redis.UniversalClient duration time.Duration getter Getter[K, V] keyEncoder func(K) string codec Codec[V] countHit atomic.Int64 countMiss atomic.Int64 logErrFn LogErrFn } type Encoder[V any] interface { Encode(value V) string } type Decoder[V any] interface { Decode(encoded string) (V, error) } type Codec[V any] interface { Encoder[V] Decoder[V] } func NewRedis[K any, V any]( client redis.UniversalClient, getter Getter[K, V], keyEncoder func(K) string, codec Codec[V], duration time.Duration, logErrFn LogErrFn, ) *Redis[K, V] { return &Redis[K, V]{ client: client, duration: duration, getter: getter, keyEncoder: keyEncoder, codec: codec, logErrFn: logErrFn, } } // Stats returns number of cache hits and misses and can be used to monitor the cache efficiency. func (c *Redis[K, V]) Stats() (int64, int64) { return c.countHit.Load(), c.countMiss.Load() } // Get implements the cache.Cache interface. func (c *Redis[K, V]) Get(ctx context.Context, key K) (V, error) { var nothing V strKey := c.keyEncoder(key) raw, err := c.client.Get(ctx, strKey).Result() if err == nil { value, decErr := c.codec.Decode(raw) if decErr == nil { c.countHit.Add(1) return value, nil } } else if !errors.Is(err, redis.Nil) && c.logErrFn != nil { c.logErrFn(ctx, err) } c.countMiss.Add(1) item, err := c.getter.Find(ctx, key) if err != nil { return nothing, fmt.Errorf("cache: failed to find one: %w", err) } err = c.client.Set(ctx, strKey, c.codec.Encode(item), c.duration).Err() if err != nil && c.logErrFn != nil { c.logErrFn(ctx, err) } return item, nil } func (c *Redis[K, V]) Evict(ctx context.Context, key K) { strKey := c.keyEncoder(key) err := c.client.Del(ctx, strKey).Err() if err != nil && c.logErrFn != nil { c.logErrFn(ctx, err) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cache/no_cache_test.go
cache/no_cache_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cache import ( "context" "errors" "testing" ) const testValue = "value" type contextKey string type mockGetter struct { findFunc func(ctx context.Context, key string) (string, error) } func (m *mockGetter) Find(ctx context.Context, key string) (string, error) { return m.findFunc(ctx, key) } func TestNewNoCache(t *testing.T) { getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { return testValue, nil }, } cache := NewNoCache[string, string](getter) if cache.getter == nil { t.Error("expected getter to be set") } } func TestNoCache_Stats(t *testing.T) { getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { return testValue, nil }, } cache := NewNoCache[string, string](getter) hits, misses := cache.Stats() if hits != 0 { t.Errorf("expected hits to be 0, got %d", hits) } if misses != 0 { t.Errorf("expected misses to be 0, got %d", misses) } } func TestNoCache_Get(t *testing.T) { t.Run("successful get", func(t *testing.T) { getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { if key == "test-key" { return "test-value", nil } return "", errors.New("not found") }, } cache := NewNoCache[string, string](getter) value, err := cache.Get(context.Background(), "test-key") if err != nil { t.Fatalf("unexpected error: %v", err) } if value != "test-value" { t.Errorf("expected value to be 'test-value', got '%s'", value) } }) t.Run("get with error", func(t *testing.T) { expectedErr := errors.New("getter error") getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { return "", expectedErr }, } cache := NewNoCache[string, string](getter) _, err := cache.Get(context.Background(), "test-key") if !errors.Is(err, expectedErr) { t.Errorf("expected error to be %v, got %v", expectedErr, err) } }) t.Run("multiple gets call getter each time", func(t *testing.T) { callCount := 0 getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { callCount++ return testValue, nil }, } cache := NewNoCache[string, string](getter) // Call Get multiple times with the same key _, _ = cache.Get(context.Background(), "key") _, _ = cache.Get(context.Background(), "key") _, _ = cache.Get(context.Background(), "key") if callCount != 3 { t.Errorf("expected getter to be called 3 times, got %d", callCount) } }) t.Run("get with context", func(t *testing.T) { var receivedCtx context.Context getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { receivedCtx = ctx return testValue, nil }, } cache := NewNoCache[string, string](getter) ctx := context.WithValue(context.Background(), contextKey("test-key"), "test-value") _, _ = cache.Get(ctx, "key") if receivedCtx != ctx { t.Error("expected context to be passed to getter") } }) } func TestNoCache_Evict(t *testing.T) { t.Run("evict does nothing", func(t *testing.T) { getter := &mockGetter{ findFunc: func(ctx context.Context, key string) (string, error) { return testValue, nil }, } cache := NewNoCache[string, string](getter) // Evict should not panic or cause any issues cache.Evict(context.Background(), "key") // Verify we can still get values after evict value, err := cache.Get(context.Background(), "key") if err != nil { t.Fatalf("unexpected error: %v", err) } if value != "value" { t.Errorf("expected value to be 'value', got '%s'", value) } }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/version/version_test.go
version/version_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package version import ( "testing" "github.com/coreos/go-semver/semver" ) func TestParseVersionNumber(t *testing.T) { tests := []struct { name string input string expected int64 }{ { name: "empty string returns zero", input: "", expected: 0, }, { name: "zero string returns zero", input: "0", expected: 0, }, { name: "positive number", input: "123", expected: 123, }, { name: "single digit", input: "5", expected: 5, }, { name: "large number", input: "999999", expected: 999999, }, { name: "negative number", input: "-1", expected: -1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := parseVersionNumber(tt.input) if result != tt.expected { t.Errorf("parseVersionNumber(%q) = %d, want %d", tt.input, result, tt.expected) } }) } } func TestParseVersionNumberPanic(t *testing.T) { tests := []struct { name string input string }{ { name: "invalid number", input: "abc", }, { name: "mixed alphanumeric", input: "1a2b", }, { name: "decimal number", input: "1.5", }, { name: "special characters", input: "!@#", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Errorf("parseVersionNumber(%q) should have panicked", tt.input) } }() parseVersionNumber(tt.input) }) } } func TestVersionStructure(t *testing.T) { // Test that Version is properly initialized as a semver.Version if Version.Major < 0 { t.Error("Version.Major should not be negative") } if Version.Minor < 0 { t.Error("Version.Minor should not be negative") } if Version.Patch < 0 { t.Error("Version.Patch should not be negative") } } func TestVersionString(t *testing.T) { // Test that Version can be converted to string without error versionStr := Version.String() if versionStr == "" { t.Error("Version.String() should not be empty") } // Test that the string representation is valid semver _, err := semver.NewVersion(versionStr) if err != nil { t.Errorf("Version.String() should produce valid semver, got: %s, error: %v", versionStr, err) } } func TestGitVariables(t *testing.T) { // Test that git variables are accessible (they may be empty in tests) // This ensures the variables are properly declared and exported _ = GitRepository _ = GitCommit // Test that they are strings if GitRepository != "" { if len(GitRepository) == 0 { t.Error("GitRepository should be a valid string when set") } } if GitCommit != "" { if len(GitCommit) == 0 { t.Error("GitCommit should be a valid string when set") } } } func TestVersionComparison(t *testing.T) { // Test version comparison functionality v1 := semver.Version{Major: 1, Minor: 0, Patch: 0} v2 := semver.Version{Major: 1, Minor: 1, Patch: 0} if !v1.LessThan(v2) { t.Error("v1.0.0 should be less than v1.1.0") } if v2.LessThan(v1) { t.Error("v1.1.0 should not be less than v1.0.0") } } func TestVersionWithPrerelease(t *testing.T) { // Test version with prerelease v := semver.Version{ Major: 1, Minor: 0, Patch: 0, PreRelease: semver.PreRelease("alpha"), } expected := "1.0.0-alpha" if v.String() != expected { t.Errorf("Version with prerelease should be %s, got %s", expected, v.String()) } } func TestVersionWithMetadata(t *testing.T) { // Test version with metadata v := semver.Version{ Major: 1, Minor: 0, Patch: 0, Metadata: "build.1", } expected := "1.0.0+build.1" if v.String() != expected { t.Errorf("Version with metadata should be %s, got %s", expected, v.String()) } } func TestVersionWithBothPrereleaseAndMetadata(t *testing.T) { // Test version with both prerelease and metadata v := semver.Version{ Major: 1, Minor: 0, Patch: 0, PreRelease: semver.PreRelease("beta"), Metadata: "build.2", } expected := "1.0.0-beta+build.2" if v.String() != expected { t.Errorf("Version with prerelease and metadata should be %s, got %s", expected, v.String()) } } // Benchmark tests. func BenchmarkParseVersionNumber(b *testing.B) { for b.Loop() { parseVersionNumber("123") } } func BenchmarkVersionString(b *testing.B) { for b.Loop() { _ = Version.String() } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/version/version.go
version/version.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package version provides the version number. package version import ( "strconv" "github.com/coreos/go-semver/semver" ) var ( // GitRepository is the git repository that was compiled. GitRepository string // GitCommit is the git commit that was compiled. GitCommit string ) var ( // major is for an API incompatible changes. major string // minor is for functionality in a backwards-compatible manner. minor string // patch is for backwards-compatible bug fixes. patch string // pre indicates prerelease. pre = "" // dev indicates development branch. Releases will be empty string. dev string // Version is the specification version that the package types support. Version = semver.Version{ Major: parseVersionNumber(major), Minor: parseVersionNumber(minor), Patch: parseVersionNumber(patch), PreRelease: semver.PreRelease(pre), Metadata: dev, } ) func parseVersionNumber(versionNum string) int64 { if versionNum == "" { return 0 } i, err := strconv.ParseInt(versionNum, 10, 64) if err != nil { panic(err) } return i }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/logging/logging.go
logging/logging.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "context" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) // Option allows to annotate logs with metadata. type Option func(c zerolog.Context) zerolog.Context // UpdateContext updates the existing logging context in the context. // IMPORTANT: No new context is created, all future logs with provided context will be impacted. func UpdateContext(ctx context.Context, opts ...Option) { // updates existing logging context in provided context.Context zerolog.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context { for _, opt := range opts { c = opt(c) } return c }) } // NewContext derives a new LoggingContext from the existing LoggingContext, adds the provided annotations, // and then returns a clone of the provided context.Context with the new LoggingContext. // IMPORTANT: The provided context is not modified, logging annotations are only part of the new context. func NewContext(ctx context.Context, opts ...Option) context.Context { // create child of current context childloggingContext := log.Ctx(ctx).With() // update child context for _, opt := range opts { childloggingContext = opt(childloggingContext) } // return copied context with new logging context return childloggingContext.Logger().WithContext(ctx) } // WithRequestID can be used to annotate logs with the request id. func WithRequestID(reqID string) Option { return func(c zerolog.Context) zerolog.Context { return c.Str("request_id", reqID) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/logging/logging_test.go
logging/logging_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "bytes" "context" "encoding/json" "strings" "testing" "github.com/rs/zerolog" ) func TestWithRequestID(t *testing.T) { tests := []struct { name string requestID string }{ { name: "normal request ID", requestID: "req-123456", }, { name: "empty request ID", requestID: "", }, { name: "UUID request ID", requestID: "550e8400-e29b-41d4-a716-446655440000", }, { name: "long request ID", requestID: strings.Repeat("a", 100), }, { name: "special characters", requestID: "req-123!@#$%^&*()", }, { name: "unicode request ID", requestID: "req-世界-🌍", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Apply the WithRequestID option option := WithRequestID(tt.requestID) logCtx := logger.With() logCtx = option(logCtx) // Log a message to test the option logger = logCtx.Logger() logger.Info().Msg("test message") // Parse the log output var logEntry map[string]any err := json.Unmarshal(buf.Bytes(), &logEntry) if err != nil { t.Fatalf("Failed to parse log output: %v", err) } // Check if request_id is present and correct if requestID, ok := logEntry["request_id"]; ok { if requestID != tt.requestID { t.Errorf("Expected request_id %q, got %q", tt.requestID, requestID) } } else { t.Error("request_id field not found in log output") } }) } } func TestUpdateContext(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a context with the logger ctx := logger.WithContext(context.Background()) // Test updating context with request ID UpdateContext(ctx, WithRequestID("test-req-123")) // Log a message using the updated context zerolog.Ctx(ctx).Info().Msg("test message") // Parse the log output var logEntry map[string]any err := json.Unmarshal(buf.Bytes(), &logEntry) if err != nil { t.Fatalf("Failed to parse log output: %v", err) } // Check if request_id is present if requestID, ok := logEntry["request_id"]; ok { if requestID != "test-req-123" { t.Errorf("Expected request_id %q, got %q", "test-req-123", requestID) } } else { t.Error("request_id field not found in log output") } } func TestUpdateContextMultipleOptions(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a context with the logger ctx := logger.WithContext(context.Background()) // Create multiple options option1 := WithRequestID("req-456") option2 := func(c zerolog.Context) zerolog.Context { return c.Str("user_id", "user-789") } option3 := func(c zerolog.Context) zerolog.Context { return c.Int("version", 1) } // Update context with multiple options UpdateContext(ctx, option1, option2, option3) // Log a message using the updated context zerolog.Ctx(ctx).Info().Msg("test message") // Parse the log output var logEntry map[string]any err := json.Unmarshal(buf.Bytes(), &logEntry) if err != nil { t.Fatalf("Failed to parse log output: %v", err) } // Check all fields are present if requestID, ok := logEntry["request_id"]; !ok || requestID != "req-456" { t.Errorf("Expected request_id %q, got %q", "req-456", requestID) } if userID, ok := logEntry["user_id"]; !ok || userID != "user-789" { t.Errorf("Expected user_id %q, got %q", "user-789", userID) } if version, ok := logEntry["version"]; !ok || version != float64(1) { t.Errorf("Expected version %v, got %v", 1, version) } } func TestNewContext(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a parent context with the logger parentCtx := logger.WithContext(context.Background()) // Create a new context with request ID childCtx := NewContext(parentCtx, WithRequestID("child-req-123")) // Verify that the parent context is not modified zerolog.Ctx(parentCtx).Info().Msg("parent message") // Parse the parent log output lines := strings.Split(strings.TrimSpace(buf.String()), "\n") if len(lines) > 0 { var parentLogEntry map[string]any err := json.Unmarshal([]byte(lines[0]), &parentLogEntry) if err != nil { t.Fatalf("Failed to parse parent log output: %v", err) } // Parent should not have request_id if _, ok := parentLogEntry["request_id"]; ok { t.Error("Parent context should not have request_id") } } // Clear buffer for child test buf.Reset() // Log a message using the child context zerolog.Ctx(childCtx).Info().Msg("child message") // Parse the child log output var childLogEntry map[string]any err := json.Unmarshal(buf.Bytes(), &childLogEntry) if err != nil { t.Fatalf("Failed to parse child log output: %v", err) } // Child should have request_id if requestID, ok := childLogEntry["request_id"]; !ok || requestID != "child-req-123" { t.Errorf("Expected child request_id %q, got %q", "child-req-123", requestID) } } func TestNewContextMultipleOptions(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a parent context with the logger parentCtx := logger.WithContext(context.Background()) // Create multiple options option1 := WithRequestID("new-req-789") option2 := func(c zerolog.Context) zerolog.Context { return c.Str("service", "test-service") } option3 := func(c zerolog.Context) zerolog.Context { return c.Bool("debug", true) } // Create a new context with multiple options childCtx := NewContext(parentCtx, option1, option2, option3) // Log a message using the child context zerolog.Ctx(childCtx).Info().Msg("test message") // Parse the log output var logEntry map[string]any err := json.Unmarshal(buf.Bytes(), &logEntry) if err != nil { t.Fatalf("Failed to parse log output: %v", err) } // Check all fields are present if requestID, ok := logEntry["request_id"]; !ok || requestID != "new-req-789" { t.Errorf("Expected request_id %q, got %q", "new-req-789", requestID) } if service, ok := logEntry["service"]; !ok || service != "test-service" { t.Errorf("Expected service %q, got %q", "test-service", service) } if debug, ok := logEntry["debug"]; !ok || debug != true { t.Errorf("Expected debug %v, got %v", true, debug) } } func TestNewContextIsolation(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a parent context with the logger parentCtx := logger.WithContext(context.Background()) // Create two child contexts with different request IDs child1Ctx := NewContext(parentCtx, WithRequestID("child1-req")) child2Ctx := NewContext(parentCtx, WithRequestID("child2-req")) // Log from child1 zerolog.Ctx(child1Ctx).Info().Msg("child1 message") // Parse child1 log lines := strings.Split(strings.TrimSpace(buf.String()), "\n") var child1LogEntry map[string]any err := json.Unmarshal([]byte(lines[0]), &child1LogEntry) if err != nil { t.Fatalf("Failed to parse child1 log output: %v", err) } if requestID, ok := child1LogEntry["request_id"]; !ok || requestID != "child1-req" { t.Errorf("Expected child1 request_id %q, got %q", "child1-req", requestID) } // Clear buffer buf.Reset() // Log from child2 zerolog.Ctx(child2Ctx).Info().Msg("child2 message") // Parse child2 log var child2LogEntry map[string]any err = json.Unmarshal(buf.Bytes(), &child2LogEntry) if err != nil { t.Fatalf("Failed to parse child2 log output: %v", err) } if requestID, ok := child2LogEntry["request_id"]; !ok || requestID != "child2-req" { t.Errorf("Expected child2 request_id %q, got %q", "child2-req", requestID) } } func TestCustomOption(t *testing.T) { // Create a custom option customOption := func(c zerolog.Context) zerolog.Context { return c.Str("custom_field", "custom_value").Int("number", 42) } // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a context with the logger ctx := logger.WithContext(context.Background()) // Create a new context with custom option newCtx := NewContext(ctx, customOption) // Log a message using the new context zerolog.Ctx(newCtx).Info().Msg("test message") // Parse the log output var logEntry map[string]any err := json.Unmarshal(buf.Bytes(), &logEntry) if err != nil { t.Fatalf("Failed to parse log output: %v", err) } // Check custom fields are present if customField, ok := logEntry["custom_field"]; !ok || customField != "custom_value" { t.Errorf("Expected custom_field %q, got %q", "custom_value", customField) } if number, ok := logEntry["number"]; !ok || number != float64(42) { t.Errorf("Expected number %v, got %v", 42, number) } } func TestEmptyOptions(t *testing.T) { // Create a buffer to capture log output var buf bytes.Buffer logger := zerolog.New(&buf) // Create a context with the logger ctx := logger.WithContext(context.Background()) // Test UpdateContext with no options UpdateContext(ctx) // Test NewContext with no options newCtx := NewContext(ctx) // Log messages from both contexts zerolog.Ctx(ctx).Info().Msg("original context") buf.Reset() zerolog.Ctx(newCtx).Info().Msg("new context") // Both should work without errors if buf.Len() == 0 { t.Error("Expected log output from new context") } } // Benchmark tests. func BenchmarkWithRequestID(b *testing.B) { logger := zerolog.New(bytes.NewBuffer(nil)) for b.Loop() { option := WithRequestID("benchmark-req-123") logCtx := logger.With() _ = option(logCtx) } } func BenchmarkUpdateContext(b *testing.B) { logger := zerolog.New(bytes.NewBuffer(nil)) ctx := logger.WithContext(context.Background()) for b.Loop() { UpdateContext(ctx, WithRequestID("benchmark-req-123")) } } func BenchmarkNewContext(b *testing.B) { logger := zerolog.New(bytes.NewBuffer(nil)) ctx := logger.WithContext(context.Background()) for b.Loop() { NewContext(ctx, WithRequestID("benchmark-req-123")) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/status.go
errors/status.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import ( "errors" "fmt" ) type Status string const ( StatusConflict Status = "conflict" StatusInternal Status = "internal" StatusInvalidArgument Status = "invalid" StatusNotFound Status = "not_found" StatusNotImplemented Status = "not_implemented" StatusUnauthorized Status = "unauthorized" StatusForbidden Status = "forbidden" StatusFailed Status = "failed" StatusPreconditionFailed Status = "precondition_failed" StatusAborted Status = "aborted" ) type Error struct { // Machine-readable status code. Status Status // Human-readable error message. Message string // Source error Err error // Details Details map[string]any } func (e *Error) SetErr(err error) *Error { e.Err = err return e } func (e *Error) SetDetails(details map[string]any) *Error { e.Details = details return e } func (e *Error) Unwrap() error { return e.Err } // Error implements the error interface. func (e *Error) Error() string { if e.Err != nil { return fmt.Sprintf("%s: %s", e.Message, e.Err) } return e.Message } // AsStatus unwraps an error and returns its code. // Non-application errors always return StatusInternal. func AsStatus(err error) Status { if err == nil { return "" } e := AsError(err) if e != nil { return e.Status } return StatusInternal } // Message unwraps an error and returns its message. func Message(err error) string { if err == nil { return "" } e := AsError(err) if e != nil { return e.Message } return err.Error() } // Details unwraps an error and returns its details. func Details(err error) map[string]any { if err == nil { return nil } e := AsError(err) if e != nil { return e.Details } return nil } // AsError return err as Error. func AsError(err error) (e *Error) { if err == nil { return nil } if errors.As(err, &e) { return } return } // Format is a helper function to return an Error with a given status and formatted message. func Format(code Status, format string, args ...any) *Error { msg := fmt.Sprintf(format, args...) return &Error{ Status: code, Message: msg, } } // NotFound is a helper function to return an not found Error. func NotFound(msg string) *Error { return &Error{ Status: StatusNotFound, Message: msg, } } // NotFoundf is a helper function to return an not found Error. func NotFoundf(format string, args ...any) *Error { return Format(StatusNotFound, format, args...) } // InvalidArgument is a helper function to return an invalid argument Error. func InvalidArgument(msg string) *Error { return &Error{ Status: StatusInvalidArgument, Message: msg, } } // InvalidArgumentf is a helper function to return an invalid argument Error. func InvalidArgumentf(format string, args ...any) *Error { return Format(StatusInvalidArgument, format, args...) } // Internal is a helper function to return an internal Error. func Internal(err error, msg string) *Error { return &Error{ Status: StatusInternal, Message: msg, Err: err, } } // Internalf is a helper function to return an internal Error. func Internalf(err error, format string, args ...any) *Error { msg := fmt.Sprintf(format, args...) return Format(StatusInternal, format, args...).SetErr( fmt.Errorf("%s: %w", msg, err), ) } // Conflict is a helper function to return an conflict Error. func Conflict(msg string) *Error { return &Error{ Status: StatusConflict, Message: msg, } } // Conflictf is a helper function to return a conflict Error. func Conflictf(format string, args ...any) *Error { return Format(StatusConflict, format, args...) } // PreconditionFailed is a helper function to return a precondition // failed error. func PreconditionFailed(msg string) *Error { return &Error{ Status: StatusPreconditionFailed, Message: msg, } } // PreconditionFailedf is a helper function to return a precondition // failed error. func PreconditionFailedf(format string, args ...any) *Error { return Format(StatusPreconditionFailed, format, args...) } // Unauthorized is a helper function to return an unauthorized error. func Unauthorized(msg string) *Error { return &Error{ Status: StatusUnauthorized, Message: msg, } } // Unauthorizedf is a helper function to return an unauthorized error. func Unauthorizedf(format string, args ...any) *Error { return Format(StatusUnauthorized, format, args...) } // Forbidden is a helper function to return a forbidden error. func Forbidden(msg string) *Error { return &Error{ Status: StatusForbidden, Message: msg, } } // Forbiddenf is a helper function to return a forbidden error. func Forbiddenf(format string, args ...any) *Error { return Format(StatusForbidden, format, args...) } // Failed is a helper function to return failed error status. func Failed(msg string) *Error { return &Error{ Status: StatusFailed, Message: msg, } } // Failedf is a helper function to return failed error status. func Failedf(format string, args ...any) *Error { return Format(StatusFailed, format, args...) } // Aborted is a helper function to return aborted error status. func Aborted(msg string) *Error { return &Error{ Status: StatusAborted, Message: msg, } } // Abortedf is a helper function to return aborted error status. func Abortedf(format string, args ...any) *Error { return Format(StatusAborted, format, args...) } // IsNotFound checks if err is not found error. func IsNotFound(err error) bool { return AsStatus(err) == StatusNotFound } // IsConflict checks if err is conflict error. func IsConflict(err error) bool { return AsStatus(err) == StatusConflict } // IsInvalidArgument checks if err is invalid argument error. func IsInvalidArgument(err error) bool { return AsStatus(err) == StatusInvalidArgument } // IsInternal checks if err is internal error. func IsInternal(err error) bool { return AsStatus(err) == StatusInternal } // IsPreconditionFailed checks if err is precondition failed error. func IsPreconditionFailed(err error) bool { return AsStatus(err) == StatusPreconditionFailed } // IsAborted checks if err is aborted error. func IsAborted(err error) bool { return AsStatus(err) == StatusAborted }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/status_test.go
errors/status_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import ( "errors" "fmt" "testing" ) func TestStatusConstants(t *testing.T) { tests := []struct { name string status Status expected string }{ {"StatusConflict", StatusConflict, "conflict"}, {"StatusInternal", StatusInternal, "internal"}, {"StatusInvalidArgument", StatusInvalidArgument, "invalid"}, {"StatusNotFound", StatusNotFound, "not_found"}, {"StatusNotImplemented", StatusNotImplemented, "not_implemented"}, {"StatusUnauthorized", StatusUnauthorized, "unauthorized"}, {"StatusForbidden", StatusForbidden, "forbidden"}, {"StatusFailed", StatusFailed, "failed"}, {"StatusPreconditionFailed", StatusPreconditionFailed, "precondition_failed"}, {"StatusAborted", StatusAborted, "aborted"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if string(tt.status) != tt.expected { t.Errorf("Expected %s to be %q, got %q", tt.name, tt.expected, string(tt.status)) } }) } } func TestErrorStruct(t *testing.T) { err := &Error{ Status: StatusNotFound, Message: "resource not found", Err: errors.New("underlying error"), Details: map[string]any{"resource_id": "123"}, } // Test Error() method expectedMsg := "resource not found: underlying error" if err.Error() != expectedMsg { t.Errorf("Expected error message %q, got %q", expectedMsg, err.Error()) } // Test Unwrap() method if err.Unwrap() == nil { t.Error("Expected Unwrap() to return non-nil error") } if err.Unwrap().Error() != "underlying error" { t.Errorf("Expected unwrapped error to be %q, got %q", "underlying error", err.Unwrap().Error()) } } func TestErrorWithoutUnderlyingError(t *testing.T) { err := &Error{ Status: StatusInvalidArgument, Message: "invalid input", } // Test Error() method without underlying error if err.Error() != "invalid input" { t.Errorf("Expected error message %q, got %q", "invalid input", err.Error()) } // Test Unwrap() method if err.Unwrap() != nil { t.Error("Expected Unwrap() to return nil when no underlying error") } } func TestErrorSetErr(t *testing.T) { err := &Error{ Status: StatusInternal, Message: "internal error", } underlyingErr := errors.New("database connection failed") result := err.SetErr(underlyingErr) // Should return the same error instance if result != err { t.Error("Expected SetErr to return the same error instance") } // Should set the underlying error if !errors.Is(err.Err, underlyingErr) { t.Error("Expected SetErr to set the underlying error") } } func TestErrorSetDetails(t *testing.T) { err := &Error{ Status: StatusNotFound, Message: "user not found", } details := map[string]any{ "user_id": "123", "table": "users", } result := err.SetDetails(details) // Should return the same error instance if result != err { t.Error("Expected SetDetails to return the same error instance") } // Should set the details if err.Details == nil { t.Error("Expected SetDetails to set the details") } if err.Details["user_id"] != "123" { t.Error("Expected details to contain user_id") } if err.Details["table"] != "users" { t.Error("Expected details to contain table") } } func TestAsStatus(t *testing.T) { tests := []struct { name string err error expected Status }{ { name: "nil error", err: nil, expected: "", }, { name: "Error with status", err: &Error{Status: StatusNotFound, Message: "not found"}, expected: StatusNotFound, }, { name: "standard error", err: errors.New("standard error"), expected: StatusInternal, }, { name: "wrapped Error", err: fmt.Errorf("wrapped: %w", &Error{Status: StatusConflict, Message: "conflict"}), expected: StatusConflict, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := AsStatus(tt.err) if result != tt.expected { t.Errorf("Expected AsStatus(%v) to be %q, got %q", tt.err, tt.expected, result) } }) } } func TestMessage(t *testing.T) { tests := []struct { name string err error expected string }{ { name: "nil error", err: nil, expected: "", }, { name: "Error with message", err: &Error{Status: StatusNotFound, Message: "resource not found"}, expected: "resource not found", }, { name: "standard error", err: errors.New("standard error message"), expected: "standard error message", }, { name: "wrapped Error", err: fmt.Errorf("wrapped: %w", &Error{Status: StatusConflict, Message: "conflict occurred"}), expected: "conflict occurred", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Message(tt.err) if result != tt.expected { t.Errorf("Expected Message(%v) to be %q, got %q", tt.err, tt.expected, result) } }) } } func TestDetails(t *testing.T) { details := map[string]any{"key": "value", "number": 42} tests := []struct { name string err error expected map[string]any }{ { name: "nil error", err: nil, expected: nil, }, { name: "Error with details", err: &Error{Status: StatusNotFound, Message: "not found", Details: details}, expected: details, }, { name: "Error without details", err: &Error{Status: StatusNotFound, Message: "not found"}, expected: nil, }, { name: "standard error", err: errors.New("standard error"), expected: nil, }, { name: "wrapped Error with details", err: fmt.Errorf("wrapped: %w", &Error{Status: StatusConflict, Message: "conflict", Details: details}), expected: details, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Details(tt.err) if !mapsEqual(result, tt.expected) { t.Errorf("Expected Details(%v) to be %v, got %v", tt.err, tt.expected, result) } }) } } func TestAsError(t *testing.T) { appErr := &Error{Status: StatusNotFound, Message: "not found"} stdErr := errors.New("standard error") tests := []struct { name string err error expected *Error }{ { name: "nil error", err: nil, expected: nil, }, { name: "Error type", err: appErr, expected: appErr, }, { name: "standard error", err: stdErr, expected: nil, }, { name: "wrapped Error", err: fmt.Errorf("wrapped: %w", appErr), expected: appErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := AsError(tt.err) if result != tt.expected { t.Errorf("Expected AsError(%v) to be %v, got %v", tt.err, tt.expected, result) } }) } } func TestFormat(t *testing.T) { tests := []struct { name string status Status format string args []any expected *Error }{ { name: "simple format", status: StatusNotFound, format: "user not found", args: nil, expected: &Error{Status: StatusNotFound, Message: "user not found"}, }, { name: "format with args", status: StatusInvalidArgument, format: "invalid user ID: %d", args: []any{123}, expected: &Error{Status: StatusInvalidArgument, Message: "invalid user ID: 123"}, }, { name: "format with multiple args", status: StatusConflict, format: "user %s already exists with email %s", args: []any{"john", "john@example.com"}, expected: &Error{Status: StatusConflict, Message: "user john already exists with email john@example.com"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Format(tt.status, tt.format, tt.args...) if result.Status != tt.expected.Status { t.Errorf("Expected status %q, got %q", tt.expected.Status, result.Status) } if result.Message != tt.expected.Message { t.Errorf("Expected message %q, got %q", tt.expected.Message, result.Message) } }) } } func TestHelperFunctions(t *testing.T) { tests := []struct { name string fn func(string, ...any) *Error status Status format string args []any expected string }{ {"NotFound", NotFoundf, StatusNotFound, "user %d not found", []any{123}, "user 123 not found"}, {"InvalidArgument", InvalidArgumentf, StatusInvalidArgument, "invalid email: %s", []any{"invalid"}, "invalid email: invalid"}, {"Conflict", Conflictf, StatusConflict, "user %s exists", []any{"john"}, "user john exists"}, {"PreconditionFailed", PreconditionFailedf, StatusPreconditionFailed, "version mismatch", nil, "version mismatch"}, {"Unauthorized", Unauthorizedf, StatusUnauthorized, "invalid token", nil, "invalid token"}, {"Forbidden", Forbiddenf, StatusForbidden, "access denied", nil, "access denied"}, {"Failed", Failedf, StatusFailed, "operation failed", nil, "operation failed"}, {"Aborted", Abortedf, StatusAborted, "operation aborted", nil, "operation aborted"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.fn(tt.format, tt.args...) if result.Status != tt.status { t.Errorf("Expected status %q, got %q", tt.status, result.Status) } if result.Message != tt.expected { t.Errorf("Expected message %q, got %q", tt.expected, result.Message) } }) } } func TestInternal(t *testing.T) { underlyingErr := errors.New("database connection failed") result := Internalf(underlyingErr, "failed to get user %d", 123) if result.Status != StatusInternal { t.Errorf("Expected status %q, got %q", StatusInternal, result.Status) } expectedMsg := "failed to get user 123" if result.Message != expectedMsg { t.Errorf("Expected message %q, got %q", expectedMsg, result.Message) } if result.Err == nil { t.Error("Expected underlying error to be set") } // The underlying error should be wrapped expectedErrMsg := "failed to get user 123: database connection failed" if result.Err.Error() != expectedErrMsg { t.Errorf("Expected underlying error message %q, got %q", expectedErrMsg, result.Err.Error()) } } func TestStatusCheckFunctions(t *testing.T) { tests := []struct { name string fn func(error) bool status Status expected bool }{ {"IsNotFound with NotFound", IsNotFound, StatusNotFound, true}, {"IsNotFound with Conflict", IsNotFound, StatusConflict, false}, {"IsConflict with Conflict", IsConflict, StatusConflict, true}, {"IsConflict with NotFound", IsConflict, StatusNotFound, false}, {"IsInvalidArgument with InvalidArgument", IsInvalidArgument, StatusInvalidArgument, true}, {"IsInvalidArgument with Internal", IsInvalidArgument, StatusInternal, false}, {"IsInternal with Internal", IsInternal, StatusInternal, true}, {"IsInternal with NotFound", IsInternal, StatusNotFound, false}, {"IsPreconditionFailed with PreconditionFailed", IsPreconditionFailed, StatusPreconditionFailed, true}, {"IsPreconditionFailed with Aborted", IsPreconditionFailed, StatusAborted, false}, {"IsAborted with Aborted", IsAborted, StatusAborted, true}, {"IsAborted with Failed", IsAborted, StatusFailed, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := &Error{Status: tt.status, Message: "test error"} result := tt.fn(err) if result != tt.expected { t.Errorf("Expected %s(%v) to be %v, got %v", tt.name, err, tt.expected, result) } }) } } func TestStatusCheckFunctionsWithStandardError(t *testing.T) { stdErr := errors.New("standard error") // All status check functions should return false for standard errors, // except IsInternal which should return true (since standard errors are treated as internal) tests := []struct { name string fn func(error) bool expected bool }{ {"IsNotFound", IsNotFound, false}, {"IsConflict", IsConflict, false}, {"IsInvalidArgument", IsInvalidArgument, false}, {"IsInternal", IsInternal, true}, // Standard errors are treated as internal {"IsPreconditionFailed", IsPreconditionFailed, false}, {"IsAborted", IsAborted, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.fn(stdErr) if result != tt.expected { t.Errorf("Expected %s(standard error) to be %v, got %v", tt.name, tt.expected, result) } }) } } func TestStatusCheckFunctionsWithNil(t *testing.T) { // All status check functions should return false for nil errors tests := []struct { name string fn func(error) bool }{ {"IsNotFound", IsNotFound}, {"IsConflict", IsConflict}, {"IsInvalidArgument", IsInvalidArgument}, {"IsInternal", IsInternal}, {"IsPreconditionFailed", IsPreconditionFailed}, {"IsAborted", IsAborted}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.fn(nil) if result { t.Errorf("Expected %s(nil) to be false, got true", tt.name) } }) } } // Helper function to compare maps. func mapsEqual(a, b map[string]any) bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } if len(a) != len(b) { return false } for k, v := range a { if b[k] != v { return false } } return true } // Benchmark tests. func BenchmarkErrorError(b *testing.B) { err := &Error{ Status: StatusNotFound, Message: "resource not found", Err: errors.New("underlying error"), } for b.Loop() { _ = err.Error() } } func BenchmarkAsStatus(b *testing.B) { err := &Error{Status: StatusNotFound, Message: "not found"} for b.Loop() { AsStatus(err) } } func BenchmarkFormat(b *testing.B) { for b.Loop() { _ = Format(StatusNotFound, "user %d not found", 123) } } func BenchmarkIsNotFound(b *testing.B) { err := &Error{Status: StatusNotFound, Message: "not found"} for b.Loop() { IsNotFound(err) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/util.go
errors/util.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import "errors" // IsType returns true if err is of type T. func IsType[T error](err error) bool { var target T return errors.As(err, &target) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/stderr_test.go
errors/stderr_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import ( "errors" "testing" ) func TestNew(t *testing.T) { tests := []struct { name string text string }{ { name: "simple error message", text: "test error", }, { name: "empty error message", text: "", }, { name: "long error message", text: "this is a very long error message that contains multiple words and should be handled correctly", }, { name: "error with special characters", text: "error with special chars: !@#$%^&*()", }, { name: "error with unicode", text: "error with unicode: 世界 🌍", }, { name: "error with newlines", text: "error\nwith\nnewlines", }, { name: "error with tabs", text: "error\twith\ttabs", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := New(tt.text) if err == nil { t.Error("Expected error to be non-nil") } if err.Error() != tt.text { t.Errorf("Expected error message %q, got %q", tt.text, err.Error()) } }) } } func TestNewComparison(t *testing.T) { // Test that New creates errors that can be compared err1 := New("test error") err2 := New("test error") err3 := New("different error") // Different instances with same message should not be equal if errors.Is(err1, err2) { t.Error("Expected different error instances to not be equal") } // Different messages should not be equal if errors.Is(err1, err3) { t.Error("Expected errors with different messages to not be equal") } // But their messages should be the same if err1.Error() != err2.Error() { t.Error("Expected error messages to be the same") } } func TestIs(t *testing.T) { baseErr := New("base error") wrappedErr := errors.New("wrapped: " + baseErr.Error()) differentErr := New("different error") tests := []struct { name string err error target error expected bool }{ { name: "same error", err: baseErr, target: baseErr, expected: true, }, { name: "different errors", err: baseErr, target: differentErr, expected: false, }, { name: "nil error", err: nil, target: baseErr, expected: false, }, { name: "nil target", err: baseErr, target: nil, expected: false, }, { name: "both nil", err: nil, target: nil, expected: true, }, { name: "wrapped error", err: wrappedErr, target: baseErr, expected: false, // Our wrapper doesn't implement Unwrap }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Is(tt.err, tt.target) if result != tt.expected { t.Errorf("Expected Is(%v, %v) to be %v, got %v", tt.err, tt.target, tt.expected, result) } }) } } // Custom error types for testing. type customError struct { msg string } func (e customError) Error() string { return e.msg } type anotherError struct { code int } func (e anotherError) Error() string { return "another error" } func TestAs(t *testing.T) { customErr := customError{msg: "custom error"} anotherErr := anotherError{code: 123} standardErr := New("standard error") tests := []struct { name string err error target any expected bool }{ { name: "custom error to custom error", err: customErr, target: &customError{}, expected: true, }, { name: "custom error to different type", err: customErr, target: &anotherError{}, expected: false, }, { name: "standard error to custom type", err: standardErr, target: &customError{}, expected: false, }, { name: "nil error", err: nil, target: &customError{}, expected: false, }, { name: "another error type", err: anotherErr, target: &anotherError{}, expected: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := As(tt.err, tt.target) if result != tt.expected { t.Errorf("Expected As(%v, %T) to be %v, got %v", tt.err, tt.target, tt.expected, result) } }) } } // Custom error type for TestAsWithValues. type codeError struct { msg string code int } func (e codeError) Error() string { return e.msg } func TestAsWithValues(t *testing.T) { // Test that As correctly populates the target originalErr := codeError{msg: "test error", code: 42} var target codeError result := As(originalErr, &target) if !result { t.Error("Expected As to return true") } if target.msg != originalErr.msg { t.Errorf("Expected target msg to be %q, got %q", originalErr.msg, target.msg) } if target.code != originalErr.code { t.Errorf("Expected target code to be %d, got %d", originalErr.code, target.code) } } // Benchmark tests. func BenchmarkNew(b *testing.B) { for b.Loop() { _ = New("benchmark error") } } func BenchmarkIs(b *testing.B) { err1 := New("error 1") err2 := New("error 2") for b.Loop() { Is(err1, err2) } } func BenchmarkAs(b *testing.B) { err := customError{msg: "test"} var target customError for b.Loop() { As(err, &target) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/stderr.go
errors/stderr.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import "errors" func New(text string) error { return errors.New(text) } func Is(err error, target error) bool { return errors.Is(err, target) } func As(err error, target any) bool { return errors.As(err, target) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/errors/util_test.go
errors/util_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import ( "errors" "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestIsType(t *testing.T) { err := errors.New("abc") valueErr := testValueError{} valueErrPtr := &testValueError{} customErr := customError{msg: "test"} assert.True(t, IsType[error](err)) assert.True(t, IsType[error](valueErr)) assert.True(t, IsType[error](valueErrPtr)) assert.True(t, IsType[error](customErr)) assert.False(t, IsType[testValueError](err)) assert.True(t, IsType[testValueError](valueErr)) assert.False(t, IsType[testValueError](valueErrPtr)) assert.False(t, IsType[testValueError](customErr)) assert.False(t, IsType[*testValueError](err)) assert.False(t, IsType[*testValueError](valueErr)) assert.True(t, IsType[*testValueError](valueErrPtr)) assert.False(t, IsType[*testValueError](customErr)) assert.False(t, IsType[customError](err)) assert.False(t, IsType[customError](valueErr)) assert.False(t, IsType[customError](valueErrPtr)) assert.True(t, IsType[customError](customErr)) } func TestIsTypeWithNil(t *testing.T) { // Test with nil error assert.False(t, IsType[error](nil)) assert.False(t, IsType[testValueError](nil)) assert.False(t, IsType[*testValueError](nil)) assert.False(t, IsType[*customError](nil)) } func TestIsTypeWithWrappedErrors(t *testing.T) { // Test with wrapped errors valueErr := testValueError{} wrappedErr := fmt.Errorf("wrapped: %w", valueErr) assert.True(t, IsType[error](wrappedErr)) assert.True(t, IsType[testValueError](wrappedErr)) assert.False(t, IsType[*testValueError](wrappedErr)) // Test with wrapped custom error customErr := customError{msg: "custom"} wrappedCustomErr := fmt.Errorf("wrapped: %w", customErr) assert.True(t, IsType[error](wrappedCustomErr)) assert.False(t, IsType[testValueError](wrappedCustomErr)) assert.False(t, IsType[*testValueError](wrappedCustomErr)) assert.True(t, IsType[customError](wrappedCustomErr)) } func TestIsTypeWithCustomError(t *testing.T) { // Test with custom error type customErr := customError{msg: "not found"} assert.True(t, IsType[error](customErr)) assert.True(t, IsType[customError](customErr)) assert.False(t, IsType[*customError](customErr)) assert.False(t, IsType[testValueError](customErr)) assert.False(t, IsType[*testValueError](customErr)) } func TestIsTypeWithMultipleWrapping(t *testing.T) { // Test with multiple levels of wrapping originalErr := testValueError{} wrappedOnce := fmt.Errorf("first wrap: %w", originalErr) wrappedTwice := fmt.Errorf("second wrap: %w", wrappedOnce) assert.True(t, IsType[error](wrappedTwice)) assert.True(t, IsType[testValueError](wrappedTwice)) assert.False(t, IsType[*testValueError](wrappedTwice)) assert.False(t, IsType[customError](wrappedTwice)) } func TestIsTypeWithDifferentErrorTypes(t *testing.T) { // Test with various error types tests := []struct { name string err error }{ {"standard error", errors.New("standard")}, {"value error", testValueError{}}, {"pointer to value error", &testValueError{}}, {"custom error", customError{msg: "custom"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // All should be of type error assert.True(t, IsType[error](tt.err), "All errors should be of type error") // Test specific type checking var testVal testValueError var testPtr *testValueError var customErr customError switch { case errors.As(tt.err, &testVal): assert.True(t, IsType[testValueError](tt.err)) assert.False(t, IsType[*testValueError](tt.err)) case errors.As(tt.err, &testPtr): assert.False(t, IsType[testValueError](tt.err)) assert.True(t, IsType[*testValueError](tt.err)) case errors.As(tt.err, &customErr): assert.True(t, IsType[customError](tt.err)) assert.False(t, IsType[*customError](tt.err)) default: // Standard error - should not match specific types assert.False(t, IsType[testValueError](tt.err)) assert.False(t, IsType[*testValueError](tt.err)) assert.False(t, IsType[customError](tt.err)) } }) } } func TestIsTypeEdgeCases(t *testing.T) { // Test with simple custom error customErr := customError{msg: "test"} assert.True(t, IsType[error](customErr)) assert.True(t, IsType[customError](customErr)) assert.False(t, IsType[*customError](customErr)) // Test type assertion behavior var err error = customErr assert.True(t, IsType[customError](err)) } func TestIsTypePerformance(t *testing.T) { // Test that IsType works efficiently with different error types errors := []error{ errors.New("standard"), testValueError{}, &testValueError{}, &customError{msg: "pointer"}, &Error{Status: StatusNotFound, Message: "not found"}, } for i, err := range errors { t.Run(fmt.Sprintf("error_%d", i), func(t *testing.T) { // Each should be identifiable as an error assert.True(t, IsType[error](err)) // And should have consistent behavior result1 := IsType[error](err) result2 := IsType[error](err) assert.Equal(t, result1, result2, "IsType should be consistent") }) } } type testValueError struct{} func (e testValueError) Error() string { return "value receiver" } // Benchmark tests. func BenchmarkIsTypeValueError(b *testing.B) { err := testValueError{} for b.Loop() { IsType[testValueError](err) } } func BenchmarkIsTypeCustomError(b *testing.B) { err := customError{msg: "test"} for b.Loop() { IsType[customError](err) } } func BenchmarkIsTypeStandardError(b *testing.B) { err := errors.New("standard error") for b.Loop() { IsType[error](err) } } func BenchmarkIsTypeWrappedError(b *testing.B) { err := fmt.Errorf("wrapped: %w", testValueError{}) for b.Loop() { IsType[testValueError](err) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/errors_test.go
store/errors_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package store import ( "errors" "testing" "github.com/stretchr/testify/assert" ) func TestErrors(t *testing.T) { tests := []struct { name string err error msg string }{ { name: "ErrResourceNotFound", err: ErrResourceNotFound, msg: "resource not found", }, { name: "ErrDuplicate", err: ErrDuplicate, msg: "resource is a duplicate", }, { name: "ErrForeignKeyViolation", err: ErrForeignKeyViolation, msg: "foreign resource does not exists", }, { name: "ErrVersionConflict", err: ErrVersionConflict, msg: "resource version conflict", }, { name: "ErrPathTooLong", err: ErrPathTooLong, msg: "the path is too long", }, { name: "ErrPrimaryPathAlreadyExists", err: ErrPrimaryPathAlreadyExists, msg: "primary path already exists for resource", }, { name: "ErrPrimaryPathRequired", err: ErrPrimaryPathRequired, msg: "path has to be primary", }, { name: "ErrAliasPathRequired", err: ErrAliasPathRequired, msg: "path has to be an alias", }, { name: "ErrPrimaryPathCantBeDeleted", err: ErrPrimaryPathCantBeDeleted, msg: "primary path can't be deleted", }, { name: "ErrNoChangeInRequestedMove", err: ErrNoChangeInRequestedMove, msg: "the requested move doesn't change anything", }, { name: "ErrIllegalMoveCyclicHierarchy", err: ErrIllegalMoveCyclicHierarchy, msg: "the requested move is not permitted as it would cause a cyclic dependency", }, { name: "ErrSpaceWithChildsCantBeDeleted", err: ErrSpaceWithChildsCantBeDeleted, msg: "the space can't be deleted as it still contains spaces or repos", }, { name: "ErrPreConditionFailed", err: ErrPreConditionFailed, msg: "precondition failed", }, { name: "ErrLicenseNotFound", err: ErrLicenseNotFound, msg: "license not found", }, { name: "ErrLicenseExpired", err: ErrLicenseExpired, msg: "license expired", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.NotNil(t, tt.err, "error should not be nil") assert.Equal(t, tt.msg, tt.err.Error(), "error message should match") }) } } func TestErrorsAreDistinct(t *testing.T) { // Verify that all errors are distinct allErrors := []error{ ErrResourceNotFound, ErrDuplicate, ErrForeignKeyViolation, ErrVersionConflict, ErrPathTooLong, ErrPrimaryPathAlreadyExists, ErrPrimaryPathRequired, ErrAliasPathRequired, ErrPrimaryPathCantBeDeleted, ErrNoChangeInRequestedMove, ErrIllegalMoveCyclicHierarchy, ErrSpaceWithChildsCantBeDeleted, ErrPreConditionFailed, ErrLicenseNotFound, ErrLicenseExpired, } for i, err1 := range allErrors { for j, err2 := range allErrors { if i != j { assert.False(t, errors.Is(err1, err2), "errors should be distinct: %v vs %v", err1, err2) } } } } func TestErrorsCanBeCompared(t *testing.T) { // Test that errors can be compared using errors.Is err := ErrResourceNotFound assert.True(t, errors.Is(err, ErrResourceNotFound), "should match ErrResourceNotFound") assert.False(t, errors.Is(err, ErrDuplicate), "should not match ErrDuplicate") }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/errors.go
store/errors.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package store import "errors" var ( ErrResourceNotFound = errors.New("resource not found") ErrDuplicate = errors.New("resource is a duplicate") ErrForeignKeyViolation = errors.New("foreign resource does not exists") ErrVersionConflict = errors.New("resource version conflict") ErrPathTooLong = errors.New("the path is too long") ErrPrimaryPathAlreadyExists = errors.New("primary path already exists for resource") ErrPrimaryPathRequired = errors.New("path has to be primary") ErrAliasPathRequired = errors.New("path has to be an alias") ErrPrimaryPathCantBeDeleted = errors.New("primary path can't be deleted") ErrNoChangeInRequestedMove = errors.New("the requested move doesn't change anything") ErrIllegalMoveCyclicHierarchy = errors.New("the requested move is not permitted as it would cause a " + "cyclic dependency") ErrSpaceWithChildsCantBeDeleted = errors.New("the space can't be deleted as it still contains " + "spaces or repos") ErrPreConditionFailed = errors.New("precondition failed") ErrLicenseNotFound = errors.New("license not found") ErrLicenseExpired = errors.New("license expired") )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/util_no_sqlite.go
store/database/util_no_sqlite.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build nosqlite // +build nosqlite package database import ( "github.com/lib/pq" "github.com/pkg/errors" ) func isSQLUniqueConstraintError(original error) bool { var pqErr *pq.Error if errors.As(original, &pqErr) { return pqErr.Code == "23505" // unique_violation } return false } func isSQLForeignKeyViolationError(original error) bool { var pqErr *pq.Error if errors.As(original, &pqErr) { return pqErr.Code == "23503" } return false }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/config.go
store/database/config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database // Config specifies the config for the database package. type Config struct { Driver string Datasource string }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/util.go
store/database/util.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "fmt" "github.com/harness/gitness/store" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) // default query range limit. const defaultLimit = 100 // limit returns the page size to a sql limit. func Limit(size int) uint64 { if size == 0 { size = defaultLimit } return uint64(size) //nolint:gosec } // offset converts the page to a sql offset. func Offset(page, size int) uint64 { if page == 0 { page = 1 } if size == 0 { size = defaultLimit } page-- return uint64(page * size) //nolint:gosec } // Logs the error and message, returns either the provided message. // Always logs the full message with error as warning. // //nolint:unparam // revisit error processing func ProcessSQLErrorf(ctx context.Context, err error, format string, args ...any) error { // If it's a known error, return converted error instead. translatedError := err switch { case errors.Is(err, sql.ErrNoRows): translatedError = store.ErrResourceNotFound case isSQLUniqueConstraintError(err): translatedError = store.ErrDuplicate case isSQLForeignKeyViolationError(err): translatedError = store.ErrForeignKeyViolation default: } //nolint:errorlint // we want to match exactly here. if translatedError != err { log.Ctx(ctx).Debug().Err(err).Msgf("translated sql error to: %s", translatedError) } return fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), translatedError) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/store.go
store/database/store.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package database provides persistent data storage using // a postgres or sqlite3 database. package database import ( "context" "database/sql" "errors" "fmt" "net/url" "time" "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/rs/zerolog/log" ) const ( // sqlForUpdate is the sql statement used for locking rows returned by select queries. SQLForUpdate = "FOR UPDATE" ) type Migrator func(ctx context.Context, dbx *sqlx.DB) error // Builder is a global instance of the sql builder. we are able to // hardcode to postgres since sqlite3 is compatible with postgres. var Builder = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar) // Connect to a database and verify with a ping. func Connect(ctx context.Context, driver string, datasource string) (*sqlx.DB, error) { datasource, err := prepareDatasourceForDriver(driver, datasource) if err != nil { return nil, fmt.Errorf("failed to prepare datasource: %w", err) } db, err := sql.Open(driver, datasource) if err != nil { return nil, fmt.Errorf("failed to open the db: %w", err) } dbx := sqlx.NewDb(db, driver) if err = pingDatabase(ctx, dbx); err != nil { return nil, fmt.Errorf("failed to ping the db: %w", err) } log.Ctx(ctx).Info().Str("driver", driver).Msg("Database connected") return dbx, nil } // ConnectAndMigrate creates the database handle and migrates the database. func ConnectAndMigrate( ctx context.Context, driver string, datasource string, migrators ...Migrator, ) (*sqlx.DB, error) { dbx, err := Connect(ctx, driver, datasource) if err != nil { return nil, err } for _, migrator := range migrators { if err = migrator(ctx, dbx); err != nil { return nil, fmt.Errorf("failed to setup the db: %w", err) } } return dbx, nil } // Must is a helper function that wraps a call to Connect // and panics if the error is non-nil. func Must(db *sqlx.DB, err error) *sqlx.DB { if err != nil { panic(err) } return db } // prepareDatasourceForDriver ensures that required features are enabled on the // datasource connection string based on the driver. func prepareDatasourceForDriver(driver string, datasource string) (string, error) { switch driver { case "sqlite3": url, err := url.Parse(datasource) if err != nil { return "", fmt.Errorf("datasource is of invalid format for driver sqlite3") } // get original query and update it with required settings query := url.Query() // ensure foreign keys are always enabled (disabled by default) // See https://github.com/mattn/go-sqlite3#connection-string query.Set("_foreign_keys", "on") // update url with updated query url.RawQuery = query.Encode() return url.String(), nil default: return datasource, nil } } // helper function to ping the database with backoff to ensure // a connection can be established before we proceed with the // database setup and migration. func pingDatabase(ctx context.Context, db *sqlx.DB) error { var err error for i := 1; i <= 30; i++ { err = db.PingContext(ctx) // No point in continuing if context was cancelled if errors.Is(err, context.Canceled) { return err } // We can complete on first successful ping if err == nil { return nil } log.Debug().Err(err).Msgf("Ping attempt #%d failed", i) time.Sleep(time.Second) } return fmt.Errorf("all 30 tries failed, last failure: %w", err) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/util_sqlite.go
store/database/util_sqlite.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !nosqlite // +build !nosqlite package database import ( "github.com/jackc/pgerrcode" "github.com/lib/pq" "github.com/mattn/go-sqlite3" "github.com/pkg/errors" ) func isSQLUniqueConstraintError(original error) bool { var sqliteErr sqlite3.Error if errors.As(original, &sqliteErr) { return errors.Is(sqliteErr.ExtendedCode, sqlite3.ErrConstraintUnique) || errors.Is(sqliteErr.ExtendedCode, sqlite3.ErrConstraintPrimaryKey) } var pqErr *pq.Error if errors.As(original, &pqErr) { return pqErr.Code == "23505" // unique_violation } return false } func isSQLForeignKeyViolationError(original error) bool { var sqliteErr sqlite3.Error if errors.As(original, &sqliteErr) { return errors.Is(sqliteErr.ExtendedCode, sqlite3.ErrConstraintForeignKey) } var pqErr *pq.Error // this can happen if the child manifest is deleted by // the online GC while attempting to create the list if errors.As(original, &pqErr) && pqErr.Code == pgerrcode.ForeignKeyViolation { return true } return false }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/util_test.go
store/database/util_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "errors" "testing" "github.com/harness/gitness/store" ) func TestOffset(t *testing.T) { tests := []struct { page int size int want uint64 }{ { page: 0, size: 10, want: 0, }, { page: 1, size: 10, want: 0, }, { page: 2, size: 10, want: 10, }, { page: 3, size: 10, want: 20, }, { page: 4, size: 100, want: 300, }, { page: 4, size: 0, // unset, expect default 100 want: 300, }, } for _, test := range tests { got, want := Offset(test.page, test.size), test.want if got != want { t.Errorf("Got %d want %d for page %d, size %d", got, want, test.page, test.size) } } } func TestLimit(t *testing.T) { tests := []struct { size int want uint64 }{ { size: 0, want: 100, }, { size: 10, want: 10, }, } for _, test := range tests { got, want := Limit(test.size), test.want if got != want { t.Errorf("Got %d want %d for size %d", got, want, test.size) } } } func TestProcessSQLErrorf(t *testing.T) { ctx := context.Background() t.Run("sql.ErrNoRows returns ErrResourceNotFound", func(t *testing.T) { err := ProcessSQLErrorf(ctx, sql.ErrNoRows, "test message") if !errors.Is(err, store.ErrResourceNotFound) { t.Errorf("expected ErrResourceNotFound, got %v", err) } if err.Error() != "test message: resource not found" { t.Errorf("unexpected error message: %v", err.Error()) } }) t.Run("formats message with args", func(t *testing.T) { err := ProcessSQLErrorf(ctx, sql.ErrNoRows, "test %s %d", "message", 42) if !errors.Is(err, store.ErrResourceNotFound) { t.Errorf("expected ErrResourceNotFound, got %v", err) } if err.Error() != "test message 42: resource not found" { t.Errorf("unexpected error message: %v", err.Error()) } }) t.Run("unknown error is returned as-is", func(t *testing.T) { originalErr := errors.New("some random error") err := ProcessSQLErrorf(ctx, originalErr, "test message") if !errors.Is(err, originalErr) { t.Errorf("expected original error to be wrapped, got %v", err) } }) t.Run("empty format string", func(t *testing.T) { err := ProcessSQLErrorf(ctx, sql.ErrNoRows, "") if !errors.Is(err, store.ErrResourceNotFound) { t.Errorf("expected ErrResourceNotFound, got %v", err) } }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/wire.go
store/database/dbtx/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "github.com/google/wire" "github.com/jmoiron/sqlx" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideAccessorTx, ProvideAccessor, ProvideTransactor, ) // ProvideAccessorTx provides the most versatile database access interface. // All DB queries and transactions can be performed. func ProvideAccessorTx(db *sqlx.DB) AccessorTx { return New(db) } // ProvideAccessor provides the database access interface. All DB queries can be performed. func ProvideAccessor(a AccessorTx) Accessor { return a } // ProvideTransactor provides ability to run DB transactions. func ProvideTransactor(a AccessorTx) Transactor { return a }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/runner_test.go
store/database/dbtx/runner_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "context" "database/sql" "errors" "testing" "github.com/jmoiron/sqlx" "github.com/stretchr/testify/assert" ) //nolint:gocognit func TestWithTx(t *testing.T) { errTest := errors.New("dummy error") tests := []struct { name string fn func(tx Transaction) error errCommit error cancelCtx bool expectErr error expectCommitted bool expectRollback bool }{ { name: "successful", fn: func(Transaction) error { return nil }, expectCommitted: true, }, { name: "err-in-transaction", fn: func(Transaction) error { return errTest }, expectErr: errTest, expectRollback: true, }, { name: "commit-failed", fn: func(Transaction) error { return nil }, errCommit: errTest, expectErr: errTest, expectRollback: true, }, { name: "commit-failed-tx-done", fn: func(Transaction) error { return nil }, errCommit: sql.ErrTxDone, expectErr: sql.ErrTxDone, expectRollback: true, }, { name: "commit-failed-ctx-cancelled", fn: func(Transaction) error { return nil }, errCommit: sql.ErrTxDone, cancelCtx: true, expectErr: context.Canceled, expectRollback: true, }, { name: "panic-in-transaction", fn: func(Transaction) error { panic("dummy panic") }, expectRollback: true, }, { name: "commit-in-transaction", fn: func(tx Transaction) error { _ = tx.Commit() return nil }, expectCommitted: true, }, { name: "commit-in-transaction-fn-returns-err", fn: func(tx Transaction) error { _ = tx.Commit() return errTest }, expectErr: errTest, expectCommitted: true, }, { name: "rollback-in-transaction", fn: func(tx Transaction) error { _ = tx.Rollback() return nil }, expectRollback: true, }, { name: "rollback-in-transaction-fn-returns-err", fn: func(tx Transaction) error { _ = tx.Rollback() return errTest }, expectErr: errTest, expectRollback: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { mock := &dbMock{ t: t, errCommit: test.errCommit, } run := &runnerDB{ db: mock, mx: lockerNop{}, } ctx, cancelFn := context.WithCancel(context.Background()) defer cancelFn() var err error func() { defer func() { _ = recover() }() err = run.WithTx(ctx, func(ctx context.Context) error { if test.cancelCtx { cancelFn() } return test.fn(GetTransaction(ctx)) }) }() tx := mock.createdTx if tx == nil { t.Error("did not start a transaction") return } if !tx.finished { t.Error("transaction not finished") } if want, got := test.expectErr, err; !errors.Is(got, want) { t.Errorf("expected error %v, but got %v", want, got) } if want, got := test.expectCommitted, tx.committed; want != got { t.Errorf("expected committed %t, but got %t", want, got) } if want, got := test.expectRollback, tx.rollback; want != got { t.Errorf("expected rollback %t, but got %t", want, got) } }) } } type dbMock struct { *sqlx.DB // only to fulfill the Accessor interface, will be nil t *testing.T errCommit error createdTx *txMock } var _ transactor = (*dbMock)(nil) func (d *dbMock) startTx(context.Context, *sql.TxOptions) (TransactionAccessor, error) { d.createdTx = &txMock{ t: d.t, errCommit: d.errCommit, finished: false, committed: false, rollback: false, } return d.createdTx, nil } type txMock struct { *sqlx.Tx // only to fulfill the Accessor interface, will be nil t *testing.T errCommit error finished bool committed bool rollback bool } var _ TransactionAccessor = (*txMock)(nil) func (tx *txMock) Commit() error { if tx.finished { tx.t.Error("Committing an already finished transaction") return nil } if tx.errCommit == nil { tx.finished = true tx.committed = true } return tx.errCommit } func (tx *txMock) Rollback() error { if tx.finished { tx.t.Error("Rolling back an already finished transaction") return nil } tx.finished = true tx.rollback = true return nil } // nolint:rowserrcheck,sqlclosecheck // it's a unit test, works with mocked DB func TestLocking(t *testing.T) { const dummyQuery = "" tests := []struct { name string fn func(db AccessorTx, l *lockerCounter) }{ { name: "exec-lock", fn: func(db AccessorTx, l *lockerCounter) { ctx := context.Background() _, _ = db.ExecContext(ctx, dummyQuery) _, _ = db.ExecContext(ctx, dummyQuery) _, _ = db.ExecContext(ctx, dummyQuery) assert.Zero(t, l.RLocks) assert.Zero(t, l.RUnlocks) assert.Equal(t, 3, l.Locks) assert.Equal(t, 3, l.Unlocks) }, }, { name: "tx-lock", fn: func(db AccessorTx, l *lockerCounter) { ctx := context.Background() _ = db.WithTx(ctx, func(ctx context.Context) error { _, _ = GetAccessor(ctx, nil).ExecContext(ctx, dummyQuery) _, _ = GetAccessor(ctx, nil).ExecContext(ctx, dummyQuery) return nil }) assert.Zero(t, l.RLocks) assert.Zero(t, l.RUnlocks) assert.Equal(t, 1, l.Locks) assert.Equal(t, 1, l.Unlocks) }, }, { name: "tx-read-lock", fn: func(db AccessorTx, l *lockerCounter) { ctx := context.Background() _ = db.WithTx(ctx, func(ctx context.Context) error { _, _ = GetAccessor(ctx, nil).QueryContext(ctx, dummyQuery) _, _ = GetAccessor(ctx, nil).QueryContext(ctx, dummyQuery) return nil }, TxDefaultReadOnly) assert.Equal(t, 1, l.RLocks) assert.Equal(t, 1, l.RUnlocks) assert.Zero(t, l.Locks) assert.Zero(t, l.Unlocks) }, }, } for _, test := range tests { l := &lockerCounter{} t.Run(test.name, func(_ *testing.T) { test.fn(runnerDB{ db: dbMockNop{}, mx: l, }, l) }) } } type lockerCounter struct { Locks int Unlocks int RLocks int RUnlocks int } func (l *lockerCounter) Lock() { l.Locks++ } func (l *lockerCounter) Unlock() { l.Unlocks++ } func (l *lockerCounter) RLock() { l.RLocks++ } func (l *lockerCounter) RUnlock() { l.RUnlocks++ } type dbMockNop struct{} func (dbMockNop) DriverName() string { return "" } func (dbMockNop) Rebind(string) string { return "" } func (dbMockNop) BindNamed(string, any) (string, []any, error) { return "", nil, nil } //nolint:nilnil // it's a mock func (dbMockNop) QueryContext(context.Context, string, ...any) (*sql.Rows, error) { return nil, nil } //nolint:nilnil // it's a mock func (dbMockNop) QueryxContext(context.Context, string, ...any) (*sqlx.Rows, error) { return nil, nil } func (dbMockNop) QueryRowxContext(context.Context, string, ...any) *sqlx.Row { return nil } func (dbMockNop) ExecContext(context.Context, string, ...any) (sql.Result, error) { //nolint:nilnil return nil, nil } func (dbMockNop) QueryRowContext(context.Context, string, ...any) *sql.Row { return nil } //nolint:nilnil // it's a mock func (dbMockNop) PrepareContext(context.Context, string) (*sql.Stmt, error) { return nil, nil } //nolint:nilnil // it's a mock func (dbMockNop) PreparexContext(context.Context, string) (*sqlx.Stmt, error) { return nil, nil } //nolint:nilnil // it's a mock func (dbMockNop) PrepareNamedContext(context.Context, string) (*sqlx.NamedStmt, error) { return nil, nil } func (dbMockNop) GetContext(context.Context, any, string, ...any) error { return nil } func (dbMockNop) SelectContext(context.Context, any, string, ...any) error { return nil } func (dbMockNop) Commit() error { return nil } func (dbMockNop) Rollback() error { return nil } func (d dbMockNop) startTx(context.Context, *sql.TxOptions) (TransactionAccessor, error) { return d, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/tx.go
store/database/dbtx/tx.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import "database/sql" // TxDefault represents default transaction options. var TxDefault = &sql.TxOptions{Isolation: sql.LevelDefault, ReadOnly: false} // TxDefaultReadOnly represents default transaction options for read-only transactions. var TxDefaultReadOnly = &sql.TxOptions{Isolation: sql.LevelDefault, ReadOnly: true} // TxSerializable represents serializable transaction options. var TxSerializable = &sql.TxOptions{Isolation: sql.LevelSerializable, ReadOnly: false}
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/interface.go
store/database/dbtx/interface.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "context" "database/sql" "github.com/jmoiron/sqlx" ) // Accessor is the SQLx database manipulation interface. type Accessor interface { sqlx.ExtContext // sqlx.binder + sqlx.QueryerContext + sqlx.ExecerContext QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error) PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error) GetContext(ctx context.Context, dest any, query string, args ...any) error SelectContext(ctx context.Context, dest any, query string, args ...any) error } // Transaction is the Go's standard sql transaction interface. type Transaction interface { Commit() error Rollback() error } type Transactor interface { WithTx(ctx context.Context, txFn func(ctx context.Context) error, opts ...any) error } // AccessorTx is used to access the database. It combines Accessor interface // with Transactor (capability to run functions in a transaction). type AccessorTx interface { Accessor Transactor } // TransactionAccessor combines data access capabilities with the transaction commit and rollback. type TransactionAccessor interface { Transaction Accessor }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/locker.go
store/database/dbtx/locker.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "sync" "github.com/jmoiron/sqlx" ) const ( postgres = "postgres" ) type locker interface { Lock() Unlock() RLock() RUnlock() } var globalMx sync.RWMutex func needsLocking(driver string) bool { return driver != postgres } func getLocker(db *sqlx.DB) locker { if needsLocking(db.DriverName()) { return &globalMx } return lockerNop{} } type lockerNop struct{} func (lockerNop) RLock() {} func (lockerNop) RUnlock() {} func (lockerNop) Lock() {} func (lockerNop) Unlock() {}
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/runner.go
store/database/dbtx/runner.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "context" "database/sql" "errors" "github.com/jmoiron/sqlx" ) // runnerDB executes individual sqlx database calls wrapped with the locker calls (Lock/Unlock) // or a transaction wrapped with the locker calls (RLock/RUnlock or Lock/Unlock depending on the transaction type). type runnerDB struct { db transactor mx locker } var _ AccessorTx = runnerDB{} func (r runnerDB) WithTx(ctx context.Context, txFn func(context.Context) error, opts ...any) error { var txOpts *sql.TxOptions for _, opt := range opts { if v, ok := opt.(*sql.TxOptions); ok { txOpts = v } } if txOpts == nil { txOpts = TxDefault } if txOpts.ReadOnly { r.mx.RLock() defer r.mx.RUnlock() } else { r.mx.Lock() defer r.mx.Unlock() } tx, err := r.db.startTx(ctx, txOpts) if err != nil { return err } rtx := &runnerTx{ TransactionAccessor: tx, commit: false, rollback: false, } defer func() { if rtx.commit || rtx.rollback { return } _ = tx.Rollback() // ignoring the rollback error }() err = txFn(context.WithValue(ctx, ctxKeyTx{}, TransactionAccessor(rtx))) if err != nil { return err } if !rtx.commit && !rtx.rollback { err = rtx.Commit() if errors.Is(err, sql.ErrTxDone) { // Check if the transaction failed because of the context, if yes return the ctx error. if ctxErr := ctx.Err(); errors.Is(ctxErr, context.Canceled) || errors.Is(ctxErr, context.DeadlineExceeded) { err = ctxErr } } } return err } func (r runnerDB) DriverName() string { return r.db.DriverName() } func (r runnerDB) Rebind(query string) string { return r.db.Rebind(query) } func (r runnerDB) BindNamed(query string, arg any) (string, []any, error) { return r.db.BindNamed(query, arg) } func (r runnerDB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { r.mx.Lock() defer r.mx.Unlock() //nolint:sqlclosecheck return r.db.QueryContext(ctx, query, args...) } func (r runnerDB) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) { r.mx.Lock() defer r.mx.Unlock() //nolint:sqlclosecheck return r.db.QueryxContext(ctx, query, args...) } func (r runnerDB) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row { r.mx.Lock() defer r.mx.Unlock() return r.db.QueryRowxContext(ctx, query, args...) } func (r runnerDB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { r.mx.Lock() defer r.mx.Unlock() return r.db.ExecContext(ctx, query, args...) } func (r runnerDB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { r.mx.Lock() defer r.mx.Unlock() return r.db.QueryRowContext(ctx, query, args...) } func (r runnerDB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { r.mx.Lock() defer r.mx.Unlock() //nolint:sqlclosecheck return r.db.PrepareContext(ctx, query) } func (r runnerDB) PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error) { r.mx.Lock() defer r.mx.Unlock() //nolint:sqlclosecheck return r.db.PreparexContext(ctx, query) } func (r runnerDB) PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error) { r.mx.Lock() defer r.mx.Unlock() //nolint:sqlclosecheck return r.db.PrepareNamedContext(ctx, query) } func (r runnerDB) GetContext(ctx context.Context, dest any, query string, args ...any) error { r.mx.Lock() defer r.mx.Unlock() return r.db.GetContext(ctx, dest, query, args...) } func (r runnerDB) SelectContext(ctx context.Context, dest any, query string, args ...any) error { r.mx.Lock() defer r.mx.Unlock() return r.db.SelectContext(ctx, dest, query, args...) } // runnerTx executes sqlx database transaction calls. // Locking is not used because runnerDB locks the entire transaction. type runnerTx struct { TransactionAccessor commit bool rollback bool } var _ TransactionAccessor = (*runnerTx)(nil) func (r *runnerTx) Commit() error { err := r.TransactionAccessor.Commit() if err == nil { r.commit = true } return err } func (r *runnerTx) Rollback() error { err := r.TransactionAccessor.Rollback() if err == nil { r.rollback = true } return err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/ctx.go
store/database/dbtx/ctx.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "context" "github.com/jmoiron/sqlx" ) // ctxKeyTx is context key for storing and retrieving TransactionAccessor to and from a context. type ctxKeyTx struct{} // GetAccessor returns Accessor interface from the context if it exists or creates a new one from the provided *sql.DB. // It is intended to be used in data layer functions that might or might not be running inside a transaction. func GetAccessor(ctx context.Context, db *sqlx.DB) Accessor { if a, ok := ctx.Value(ctxKeyTx{}).(Accessor); ok { return a } return New(db) } // GetTransaction returns Transaction interface from the context if it exists or return nil. // It is intended to be used in transactions in service layer functions to explicitly commit or rollback transactions. func GetTransaction(ctx context.Context) Transaction { if a, ok := ctx.Value(ctxKeyTx{}).(Transaction); ok { return a } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/store/database/dbtx/db.go
store/database/dbtx/db.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dbtx import ( "context" "database/sql" "github.com/jmoiron/sqlx" ) // New returns new database Runner interface. func New(db *sqlx.DB) AccessorTx { mx := getLocker(db) run := &runnerDB{ db: sqlDB{db}, mx: mx, } return run } // transactor is combines data access capabilities with transaction starting. type transactor interface { Accessor startTx(ctx context.Context, opts *sql.TxOptions) (TransactionAccessor, error) } // sqlDB is a wrapper for the sqlx.DB that implements the transactor interface. type sqlDB struct { *sqlx.DB } var _ transactor = (*sqlDB)(nil) func (db sqlDB) startTx(ctx context.Context, opts *sql.TxOptions) (TransactionAccessor, error) { tx, err := db.DB.BeginTxx(ctx, opts) return tx, err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/secret/interface.go
secret/interface.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package secret import ( "context" ) type Service interface { DecryptSecret(ctx context.Context, spacePath, secretIdentifier string) (string, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/ssh/wire.go
ssh/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ssh import ( "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/services/publickey" "github.com/harness/gitness/types" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideServer, ) func ProvideServer( config *types.Config, verifier publickey.SSHAuthService, repoctrl *repo.Controller, lfsCtrl *lfs.Controller, ) *Server { return &Server{ Host: config.SSH.Host, Port: config.SSH.Port, DefaultUser: config.SSH.DefaultUser, Ciphers: config.SSH.Ciphers, KeyExchanges: config.SSH.KeyExchanges, MACs: config.SSH.MACs, HostKeys: config.SSH.ServerHostKeys, TrustedUserCAKeys: config.SSH.TrustedUserCAKeys, TrustedUserCAKeysParsed: config.SSH.TrustedUserCAKeysParsed, KeepAliveInterval: config.SSH.KeepAliveInterval, Verifier: verifier, RepoCtrl: repoctrl, LFSCtrl: lfsCtrl, ServerKeyPath: config.SSH.ServerKeyPath, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false