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/api/openapi/account.go
app/api/openapi/account.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 openapi import ( "net/http" "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/types" "github.com/gotidy/ptr" "github.com/swaggest/openapi-go/openapi3" ) var queryParameterIncludeCookie = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamIncludeCookie, In: openapi3.ParameterInQuery, Description: ptr.String("If set to true the token is also returned as a cookie."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeBoolean), Default: ptrptr(false), }, }, }, } // request to login to an account. type loginRequest struct { user.LoginInput } // request to register an account. type registerRequest struct { user.RegisterInput } // helper function that constructs the openapi specification // for the account registration and login endpoints. func buildAccount(reflector *openapi3.Reflector) { onLogin := openapi3.Operation{} onLogin.WithTags("account") onLogin.WithParameters(queryParameterIncludeCookie) onLogin.WithMapOfAnything(map[string]any{"operationId": "onLogin"}) _ = reflector.SetRequest(&onLogin, new(loginRequest), http.MethodPost) _ = reflector.SetJSONResponse(&onLogin, new(types.TokenResponse), http.StatusOK) _ = reflector.SetJSONResponse(&onLogin, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&onLogin, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&onLogin, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPost, "/login", onLogin) opLogout := openapi3.Operation{} opLogout.WithTags("account") opLogout.WithMapOfAnything(map[string]any{"operationId": "opLogout"}) _ = reflector.SetRequest(&opLogout, nil, http.MethodPost) _ = reflector.SetJSONResponse(&opLogout, nil, http.StatusOK) _ = reflector.SetJSONResponse(&opLogout, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opLogout, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opLogout, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPost, "/logout", opLogout) onRegister := openapi3.Operation{} onRegister.WithTags("account") onRegister.WithParameters(queryParameterIncludeCookie) onRegister.WithMapOfAnything(map[string]any{"operationId": "onRegister"}) _ = reflector.SetRequest(&onRegister, new(registerRequest), http.MethodPost) _ = reflector.SetJSONResponse(&onRegister, new(types.TokenResponse), http.StatusOK) _ = reflector.SetJSONResponse(&onRegister, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&onRegister, new(usererror.Error), http.StatusBadRequest) _ = reflector.Spec.AddOperation(http.MethodPost, "/register", onRegister) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/openapi/template.go
app/api/openapi/template.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 openapi import ( "net/http" "github.com/harness/gitness/app/api/controller/template" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/types" "github.com/swaggest/openapi-go/openapi3" ) type createTemplateRequest struct { template.CreateInput } type templateRequest struct { Ref string `path:"template_ref"` } type getTemplateRequest struct { templateRequest } type updateTemplateRequest struct { templateRequest template.UpdateInput } func templateOperations(reflector *openapi3.Reflector) { opCreate := openapi3.Operation{} opCreate.WithTags("template") opCreate.WithMapOfAnything(map[string]any{"operationId": "createTemplate"}) _ = reflector.SetRequest(&opCreate, new(createTemplateRequest), http.MethodPost) _ = reflector.SetJSONResponse(&opCreate, new(types.Template), http.StatusCreated) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusForbidden) _ = reflector.Spec.AddOperation(http.MethodPost, "/templates", opCreate) opFind := openapi3.Operation{} opFind.WithTags("template") opFind.WithMapOfAnything(map[string]any{"operationId": "findTemplate"}) _ = reflector.SetRequest(&opFind, new(getTemplateRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opFind, new(types.Template), http.StatusOK) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/templates/{template_ref}", opFind) opDelete := openapi3.Operation{} opDelete.WithTags("template") opDelete.WithMapOfAnything(map[string]any{"operationId": "deleteTemplate"}) _ = reflector.SetRequest(&opDelete, new(getTemplateRequest), http.MethodDelete) _ = reflector.SetJSONResponse(&opDelete, nil, http.StatusNoContent) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodDelete, "/templates/{template_ref}", opDelete) opUpdate := openapi3.Operation{} opUpdate.WithTags("template") opUpdate.WithMapOfAnything(map[string]any{"operationId": "updateTemplate"}) _ = reflector.SetRequest(&opUpdate, new(updateTemplateRequest), http.MethodPatch) _ = reflector.SetJSONResponse(&opUpdate, new(types.Template), http.StatusOK) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPatch, "/templates/{template_ref}", opUpdate) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/openapi/plugin.go
app/api/openapi/plugin.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 openapi import ( "net/http" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/types" "github.com/gotidy/ptr" "github.com/swaggest/openapi-go/openapi3" ) var queryParameterQueryPlugin = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamQuery, In: openapi3.ParameterInQuery, Description: ptr.String("The substring which is used to filter the plugins by their name."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeString), }, }, }, } type getPluginsRequest struct { } func pluginOperations(reflector *openapi3.Reflector) { opPlugins := openapi3.Operation{} opPlugins.WithTags("plugins") opPlugins.WithMapOfAnything(map[string]any{"operationId": "listPlugins"}) opPlugins.WithParameters(QueryParameterPage, QueryParameterLimit, queryParameterQueryPlugin) _ = reflector.SetRequest(&opPlugins, new(getPluginsRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opPlugins, []types.Plugin{}, http.StatusOK) _ = reflector.SetJSONResponse(&opPlugins, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opPlugins, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opPlugins, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opPlugins, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/plugins", opPlugins) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/openapi/pipeline.go
app/api/openapi/pipeline.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 openapi import ( "net/http" "github.com/harness/gitness/app/api/controller/pipeline" "github.com/harness/gitness/app/api/controller/trigger" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/livelog" "github.com/harness/gitness/types" "github.com/gotidy/ptr" "github.com/swaggest/openapi-go/openapi3" ) type pipelineRequest struct { repoRequest Identifier string `path:"pipeline_identifier"` } type executionRequest struct { pipelineRequest Number string `path:"execution_number"` } type triggerRequest struct { pipelineRequest Identifier string `path:"trigger_identifier"` } type logRequest struct { executionRequest StageNum string `path:"stage_number"` StepNum string `path:"step_number"` } type createExecutionRequest struct { pipelineRequest } type createTriggerRequest struct { pipelineRequest trigger.CreateInput } type createPipelineRequest struct { repoRequest pipeline.CreateInput } type getExecutionRequest struct { executionRequest } type getTriggerRequest struct { triggerRequest } type getPipelineRequest struct { pipelineRequest } type updateTriggerRequest struct { triggerRequest trigger.UpdateInput } type updatePipelineRequest struct { pipelineRequest pipeline.UpdateInput } var queryParameterQueryPipeline = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamQuery, In: openapi3.ParameterInQuery, Description: ptr.String("The substring which is used to filter the pipelines by their names."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeString), }, }, }, } var queryParameterLatest = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamLatest, In: openapi3.ParameterInQuery, Description: ptr.String("Whether to fetch latest build information for each pipeline."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeBoolean), Default: ptrptr(false), }, }, }, } var queryParameterLastExecutions = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamLastExecutions, In: openapi3.ParameterInQuery, Description: ptr.String("The number of last executions to be returned"), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Default: ptrptr(10), Minimum: ptr.Float64(1), }, }, }, } var queryParameterBranch = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamBranch, In: openapi3.ParameterInQuery, Description: ptr.String("Branch to run the execution for."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeString), }, }, }, } func pipelineOperations(reflector *openapi3.Reflector) { opCreate := openapi3.Operation{} opCreate.WithTags("pipeline") opCreate.WithMapOfAnything(map[string]any{"operationId": "createPipeline"}) _ = reflector.SetRequest(&opCreate, new(createPipelineRequest), http.MethodPost) _ = reflector.SetJSONResponse(&opCreate, new(types.Pipeline), http.StatusCreated) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusForbidden) _ = reflector.Spec.AddOperation(http.MethodPost, "/repos/{repo_ref}/pipelines", opCreate) opPipelines := openapi3.Operation{} opPipelines.WithTags("pipeline") opPipelines.WithMapOfAnything(map[string]any{"operationId": "listPipelines"}) opPipelines.WithParameters(queryParameterQueryPipeline, QueryParameterPage, QueryParameterLimit, queryParameterLatest, queryParameterLastExecutions) _ = reflector.SetRequest(&opPipelines, new(repoRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opPipelines, []types.Pipeline{}, http.StatusOK) _ = reflector.SetJSONResponse(&opPipelines, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opPipelines, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opPipelines, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opPipelines, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines", opPipelines) opFind := openapi3.Operation{} opFind.WithTags("pipeline") opFind.WithMapOfAnything(map[string]any{"operationId": "findPipeline"}) _ = reflector.SetRequest(&opFind, new(getPipelineRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opFind, new(types.Pipeline), http.StatusOK) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}", opFind) opDelete := openapi3.Operation{} opDelete.WithTags("pipeline") opDelete.WithMapOfAnything(map[string]any{"operationId": "deletePipeline"}) _ = reflector.SetRequest(&opDelete, new(getPipelineRequest), http.MethodDelete) _ = reflector.SetJSONResponse(&opDelete, nil, http.StatusNoContent) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodDelete, "/repos/{repo_ref}/pipelines/{pipeline_identifier}", opDelete) opUpdate := openapi3.Operation{} opUpdate.WithTags("pipeline") opUpdate.WithMapOfAnything(map[string]any{"operationId": "updatePipeline"}) _ = reflector.SetRequest(&opUpdate, new(updatePipelineRequest), http.MethodPatch) _ = reflector.SetJSONResponse(&opUpdate, new(types.Pipeline), http.StatusOK) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPatch, "/repos/{repo_ref}/pipelines/{pipeline_identifier}", opUpdate) executionCreate := openapi3.Operation{} executionCreate.WithTags("pipeline") executionCreate.WithParameters(queryParameterBranch) executionCreate.WithMapOfAnything(map[string]any{"operationId": "createExecution"}) _ = reflector.SetRequest(&executionCreate, new(createExecutionRequest), http.MethodPost) _ = reflector.SetJSONResponse(&executionCreate, new(types.Execution), http.StatusCreated) _ = reflector.SetJSONResponse(&executionCreate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&executionCreate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&executionCreate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&executionCreate, new(usererror.Error), http.StatusForbidden) _ = reflector.Spec.AddOperation(http.MethodPost, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions", executionCreate) executionFind := openapi3.Operation{} executionFind.WithTags("pipeline") executionFind.WithMapOfAnything(map[string]any{"operationId": "findExecution"}) _ = reflector.SetRequest(&executionFind, new(getExecutionRequest), http.MethodGet) _ = reflector.SetJSONResponse(&executionFind, new(types.Execution), http.StatusOK) _ = reflector.SetJSONResponse(&executionFind, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&executionFind, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&executionFind, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&executionFind, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions/{execution_number}", executionFind) executionCancel := openapi3.Operation{} executionCancel.WithTags("pipeline") executionCancel.WithMapOfAnything(map[string]any{"operationId": "cancelExecution"}) _ = reflector.SetRequest(&executionCancel, new(getExecutionRequest), http.MethodPost) _ = reflector.SetJSONResponse(&executionCancel, new(types.Execution), http.StatusOK) _ = reflector.SetJSONResponse(&executionCancel, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&executionCancel, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&executionCancel, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&executionCancel, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPost, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions/{execution_number}/cancel", executionCancel) executionDelete := openapi3.Operation{} executionDelete.WithTags("pipeline") executionDelete.WithMapOfAnything(map[string]any{"operationId": "deleteExecution"}) _ = reflector.SetRequest(&executionDelete, new(getExecutionRequest), http.MethodDelete) _ = reflector.SetJSONResponse(&executionDelete, nil, http.StatusNoContent) _ = reflector.SetJSONResponse(&executionDelete, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&executionDelete, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&executionDelete, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&executionDelete, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodDelete, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions/{execution_number}", executionDelete) executionList := openapi3.Operation{} executionList.WithTags("pipeline") executionList.WithMapOfAnything(map[string]any{"operationId": "listExecutions"}) executionList.WithParameters(QueryParameterPage, QueryParameterLimit) _ = reflector.SetRequest(&executionList, new(pipelineRequest), http.MethodGet) _ = reflector.SetJSONResponse(&executionList, []types.Execution{}, http.StatusOK) _ = reflector.SetJSONResponse(&executionList, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&executionList, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&executionList, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&executionList, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions", executionList) triggerCreate := openapi3.Operation{} triggerCreate.WithTags("pipeline") triggerCreate.WithMapOfAnything(map[string]any{"operationId": "createTrigger"}) _ = reflector.SetRequest(&triggerCreate, new(createTriggerRequest), http.MethodPost) _ = reflector.SetJSONResponse(&triggerCreate, new(types.Trigger), http.StatusCreated) _ = reflector.SetJSONResponse(&triggerCreate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&triggerCreate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&triggerCreate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&triggerCreate, new(usererror.Error), http.StatusForbidden) _ = reflector.Spec.AddOperation(http.MethodPost, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/triggers", triggerCreate) triggerFind := openapi3.Operation{} triggerFind.WithTags("pipeline") triggerFind.WithMapOfAnything(map[string]any{"operationId": "findTrigger"}) _ = reflector.SetRequest(&triggerFind, new(getTriggerRequest), http.MethodGet) _ = reflector.SetJSONResponse(&triggerFind, new(types.Trigger), http.StatusOK) _ = reflector.SetJSONResponse(&triggerFind, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&triggerFind, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&triggerFind, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&triggerFind, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/triggers/{trigger_identifier}", triggerFind) triggerDelete := openapi3.Operation{} triggerDelete.WithTags("pipeline") triggerDelete.WithMapOfAnything(map[string]any{"operationId": "deleteTrigger"}) _ = reflector.SetRequest(&triggerDelete, new(getTriggerRequest), http.MethodDelete) _ = reflector.SetJSONResponse(&triggerDelete, nil, http.StatusNoContent) _ = reflector.SetJSONResponse(&triggerDelete, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&triggerDelete, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&triggerDelete, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&triggerDelete, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodDelete, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/triggers/{trigger_identifier}", triggerDelete) triggerUpdate := openapi3.Operation{} triggerUpdate.WithTags("pipeline") triggerUpdate.WithMapOfAnything(map[string]any{"operationId": "updateTrigger"}) _ = reflector.SetRequest(&triggerUpdate, new(updateTriggerRequest), http.MethodPatch) _ = reflector.SetJSONResponse(&triggerUpdate, new(types.Trigger), http.StatusOK) _ = reflector.SetJSONResponse(&triggerUpdate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&triggerUpdate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&triggerUpdate, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&triggerUpdate, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&triggerUpdate, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPatch, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/triggers/{trigger_identifier}", triggerUpdate) triggerList := openapi3.Operation{} triggerList.WithTags("pipeline") triggerList.WithMapOfAnything(map[string]any{"operationId": "listTriggers"}) triggerList.WithParameters(queryParameterQueryRepo, QueryParameterPage, QueryParameterLimit) _ = reflector.SetRequest(&triggerList, new(pipelineRequest), http.MethodGet) _ = reflector.SetJSONResponse(&triggerList, []types.Trigger{}, http.StatusOK) _ = reflector.SetJSONResponse(&triggerList, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&triggerList, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&triggerList, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&triggerList, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/triggers", triggerList) logView := openapi3.Operation{} logView.WithTags("pipeline") logView.WithMapOfAnything(map[string]any{"operationId": "viewLogs"}) _ = reflector.SetRequest(&logView, new(logRequest), http.MethodGet) _ = reflector.SetStringResponse(&logView, http.StatusOK, "application/json") _ = reflector.SetJSONResponse(&logView, []*livelog.Line{}, http.StatusOK) _ = reflector.SetJSONResponse(&logView, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&logView, new(usererror.Error), http.StatusUnauthorized) _ = reflector.SetJSONResponse(&logView, new(usererror.Error), http.StatusForbidden) _ = reflector.SetJSONResponse(&logView, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation( http.MethodGet, "/repos/{repo_ref}/pipelines/{pipeline_identifier}/executions/{execution_number}/logs/{stage_number}/{step_number}", logView, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/openapi/users.go
app/api/openapi/users.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 openapi import ( "net/http" "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/api/usererror" "github.com/harness/gitness/types" "github.com/swaggest/openapi-go/openapi3" ) type ( // adminUsersCreateRequest is the request for the admin user create operation. adminUsersCreateRequest struct { user.CreateInput } // adminUsersRequest is the request for user specific admin user operations. adminUsersRequest struct { UserUID string `path:"user_uid"` } // adminUsersUpdateRequest is the request for the admin user update operation. adminUsersUpdateRequest struct { adminUsersRequest user.UpdateInput } // adminUserListRequest is the request for listing users. adminUserListRequest struct { Sort string `query:"sort" enum:"id,email,created,updated"` Order string `query:"order" enum:"asc,desc"` // include pagination request paginationRequest } // updateAdminRequest is the request for updating the admin attribute for the user. updateAdminRequest struct { adminUsersRequest user.UpdateAdminInput } ) // helper function that constructs the openapi specification // for admin resources. func buildAdmin(reflector *openapi3.Reflector) { opFind := openapi3.Operation{} opFind.WithTags("admin") opFind.WithMapOfAnything(map[string]any{"operationId": "adminGetUser"}) _ = reflector.SetRequest(&opFind, new(adminUsersRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opFind, new(types.User), http.StatusOK) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opFind, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/admin/users/{user_uid}", opFind) opList := openapi3.Operation{} opList.WithTags("admin") opList.WithMapOfAnything(map[string]any{"operationId": "adminListUsers"}) _ = reflector.SetRequest(&opList, new(adminUserListRequest), http.MethodGet) _ = reflector.SetJSONResponse(&opList, new([]*types.User), http.StatusOK) _ = reflector.SetJSONResponse(&opList, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opList, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opList, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodGet, "/admin/users", opList) opCreate := openapi3.Operation{} opCreate.WithTags("admin") opCreate.WithMapOfAnything(map[string]any{"operationId": "adminCreateUser"}) _ = reflector.SetRequest(&opCreate, new(adminUsersCreateRequest), http.MethodPost) _ = reflector.SetJSONResponse(&opCreate, new(types.User), http.StatusCreated) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opCreate, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPost, "/admin/users", opCreate) opUpdate := openapi3.Operation{} opUpdate.WithTags("admin") opUpdate.WithMapOfAnything(map[string]any{"operationId": "adminUpdateUser"}) _ = reflector.SetRequest(&opUpdate, new(adminUsersUpdateRequest), http.MethodPatch) _ = reflector.SetJSONResponse(&opUpdate, new(types.User), http.StatusOK) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opUpdate, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodPatch, "/admin/users/{user_uid}", opUpdate) opUpdateAdmin := openapi3.Operation{} opUpdateAdmin.WithTags("admin") opUpdateAdmin.WithMapOfAnything(map[string]any{"operationId": "updateUserAdmin"}) _ = reflector.SetRequest(&opUpdateAdmin, new(updateAdminRequest), http.MethodPatch) _ = reflector.SetJSONResponse(&opUpdateAdmin, new(types.User), http.StatusOK) _ = reflector.SetJSONResponse(&opUpdateAdmin, new(usererror.Error), http.StatusNotFound) _ = reflector.SetJSONResponse(&opUpdateAdmin, new(usererror.Error), http.StatusInternalServerError) _ = reflector.Spec.AddOperation(http.MethodPatch, "/admin/users/{user_uid}/admin", opUpdateAdmin) opDelete := openapi3.Operation{} opDelete.WithTags("admin") opDelete.WithMapOfAnything(map[string]any{"operationId": "adminDeleteUser"}) _ = reflector.SetRequest(&opDelete, new(adminUsersRequest), http.MethodDelete) _ = reflector.SetJSONResponse(&opDelete, nil, http.StatusNoContent) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&opDelete, new(usererror.Error), http.StatusNotFound) _ = reflector.Spec.AddOperation(http.MethodDelete, "/admin/users/{user_uid}", opDelete) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/api/openapi/common.go
app/api/openapi/common.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 openapi import ( "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" "github.com/swaggest/openapi-go/openapi3" ) func ptrSchemaType(t openapi3.SchemaType) *openapi3.SchemaType { return &t } func ptrptr(i any) *any { return &i } var QueryParameterPage = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamPage, In: openapi3.ParameterInQuery, Description: ptr.String("The page to return."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Default: ptrptr(1), Minimum: ptr.Float64(1), }, }, }, } var queryParameterOrder = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamOrder, In: openapi3.ParameterInQuery, Description: ptr.String("The order of the output."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeString), Default: ptrptr(enum.OrderDesc.String()), Enum: []any{ ptr.String(enum.OrderAsc.String()), ptr.String(enum.OrderDesc.String()), }, }, }, }, } var QueryParameterLimit = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamLimit, In: openapi3.ParameterInQuery, Description: ptr.String("The maximum number of results to return."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Default: ptrptr(request.PerPageDefault), Minimum: ptr.Float64(1.0), Maximum: ptr.Float64(request.PerPageMax), }, }, }, } var queryParameterAfter = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamAfter, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain only entries created at and after this timestamp (unix millis)."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Minimum: ptr.Float64(0), }, }, }, } var queryParameterCreatedLt = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamCreatedLt, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain only entries created before this timestamp (unix millis)."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Minimum: ptr.Float64(0), }, }, }, } var queryParameterCreatedGt = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamCreatedGt, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain only entries created after this timestamp (unix millis)."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Minimum: ptr.Float64(0), }, }, }, } var queryParameterUpdatedLt = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamUpdatedLt, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain only entries updated before this timestamp (unix millis)."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Minimum: ptr.Float64(0), }, }, }, } var queryParameterUpdatedGt = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamUpdatedGt, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain only entries updated after this timestamp (unix millis)."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeInteger), Minimum: ptr.Float64(0), }, }, }, } var QueryParameterRecursive = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamRecursive, In: openapi3.ParameterInQuery, Description: ptr.String("The result should include entities from child spaces."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeBoolean), Default: ptrptr(false), }, }, }, } var queryParameterIncludeSubspaces = openapi3.ParameterOrRef{ Parameter: &openapi3.Parameter{ Name: request.QueryParamIncludeSubspaces, In: openapi3.ParameterInQuery, Description: ptr.String("The result should contain entries from the desired space and of its subspaces."), Required: ptr.Bool(false), Schema: &openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: ptrSchemaType(openapi3.SchemaTypeBoolean), Default: ptrptr(false), }, }, }, }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/jwt/jwt.go
app/jwt/jwt.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 jwt import ( "fmt" "strings" "time" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/golang-jwt/jwt/v5" ) const ( //TODO: Update when ready to change repo and build issuer = "Gitness" ) // Source represents the source of the SubClaimsAccessPermissions. type Source string const ( OciSource Source = "oci" ) // Claims defines Harness jwt claims. type Claims struct { jwt.RegisteredClaims PrincipalID int64 `json:"pid,omitempty"` Token *SubClaimsToken `json:"tkn,omitempty"` Membership *SubClaimsMembership `json:"ms,omitempty"` AccessPermissions *SubClaimsAccessPermissions `json:"ap,omitempty"` } // SubClaimsToken contains information about the token the JWT was created for. type SubClaimsToken struct { Type enum.TokenType `json:"typ,omitempty"` ID int64 `json:"id,omitempty"` } // SubClaimsMembership contains the ephemeral membership the JWT was created with. type SubClaimsMembership struct { Role enum.MembershipRole `json:"role,omitempty"` SpaceID int64 `json:"sid,omitempty"` } // SubClaimsAccessPermissions stores allowed actions on a resource. type SubClaimsAccessPermissions struct { Source Source `json:"src,omitempty"` Permissions []AccessPermissions `json:"permissions,omitempty"` } // AccessPermissions stores allowed actions on a resource. type AccessPermissions struct { SpaceID int64 `json:"sid,omitempty"` Permissions []enum.Permission `json:"p"` } // extractFirstSecretFromList extracts the first secret from a comma-separated string. // This is a helper function to support JWT secret rotation. func extractFirstSecretFromList(secret string) (string, error) { if secret == "" { return "", fmt.Errorf("empty secret provided") } // If no comma in the string, just trim and return directly. if !strings.Contains(secret, ",") { trimmed := strings.TrimSpace(secret) if trimmed == "" { return "", fmt.Errorf("secret cannot be empty") } return trimmed, nil } parts := strings.Split(secret, ",") firstSecret := strings.TrimSpace(parts[0]) if firstSecret == "" { return "", fmt.Errorf("first secret in list cannot be empty") } return firstSecret, nil } // GenerateForToken generates a jwt for a given token. func GenerateForToken(token *types.Token, secret string) (string, error) { // Use the first secret for signing (support for rotation) signingSecret, err := extractFirstSecretFromList(secret) if err != nil { return "", fmt.Errorf("failed to get first secret: %w", err) } var expiresAt *jwt.NumericDate if token.ExpiresAt != nil { expiresAt = jwt.NewNumericDate(time.UnixMilli(*token.ExpiresAt)) } jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuer, // times required to be in sec not millisec IssuedAt: jwt.NewNumericDate(time.UnixMilli(token.IssuedAt)), ExpiresAt: expiresAt, }, PrincipalID: token.PrincipalID, Token: &SubClaimsToken{ Type: token.Type, ID: token.ID, }, }) res, err := jwtToken.SignedString([]byte(signingSecret)) if err != nil { return "", fmt.Errorf("failed to sign token: %w", err) } return res, nil } // GenerateWithMembership generates a jwt with the given ephemeral membership. func GenerateWithMembership( principalID int64, spaceID int64, role enum.MembershipRole, lifetime time.Duration, secret string, ) (string, error) { // Use the first secret for signing (support for rotation) signingSecret, err := extractFirstSecretFromList(secret) if err != nil { return "", fmt.Errorf("failed to get first secret: %w", err) } issuedAt := time.Now() expiresAt := issuedAt.Add(lifetime) jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuer, // times required to be in sec IssuedAt: jwt.NewNumericDate(issuedAt), ExpiresAt: jwt.NewNumericDate(expiresAt), }, PrincipalID: principalID, Membership: &SubClaimsMembership{ SpaceID: spaceID, Role: role, }, }) res, err := jwtToken.SignedString([]byte(signingSecret)) if err != nil { return "", fmt.Errorf("failed to sign token: %w", err) } return res, nil } // GenerateForTokenWithAccessPermissions generates a jwt for a given token. func GenerateForTokenWithAccessPermissions( principalID int64, lifetime *time.Duration, secret string, accessPermissions *SubClaimsAccessPermissions, ) (string, error) { // Use the first secret for signing (support for rotation) signingSecret, err := extractFirstSecretFromList(secret) if err != nil { return "", fmt.Errorf("failed to get first secret: %w", err) } issuedAt := time.Now() if lifetime == nil { return "", fmt.Errorf("token lifetime is required") } expiresAt := issuedAt.Add(*lifetime) jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuer, IssuedAt: jwt.NewNumericDate(issuedAt), ExpiresAt: jwt.NewNumericDate(expiresAt), }, PrincipalID: principalID, AccessPermissions: accessPermissions, }) res, err := jwtToken.SignedString([]byte(signingSecret)) if err != nil { return "", fmt.Errorf("failed to sign token: %w", err) } return res, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/sse/wire.go
app/sse/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 sse import ( "github.com/harness/gitness/pubsub" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideEventsStreaming, ) func ProvideEventsStreaming(pubsub pubsub.PubSub) Streamer { const namespace = "sse" return NewStreamer(pubsub, namespace) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/sse/sse.go
app/sse/sse.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 sse import ( "context" "encoding/json" "strconv" "github.com/harness/gitness/pubsub" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // Event is a server sent event. type Event struct { Type enum.SSEType `json:"type"` Data json.RawMessage `json:"data"` } type Streamer interface { // Publish publishes an event to a given space ID. Publish(ctx context.Context, spaceID int64, eventType enum.SSEType, data any) // Stream streams the events on a space ID. Stream(ctx context.Context, spaceID int64) (<-chan *Event, <-chan error, func(context.Context) error) } type pubsubStreamer struct { pubsub pubsub.PubSub namespace string } func NewStreamer(pubsub pubsub.PubSub, namespace string) Streamer { return &pubsubStreamer{ pubsub: pubsub, namespace: namespace, } } func (e *pubsubStreamer) Publish( ctx context.Context, spaceID int64, eventType enum.SSEType, data any, ) { dataSerialized, err := json.Marshal(data) if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to serialize data: %v", err.Error()) } event := Event{ Type: eventType, Data: dataSerialized, } serializedEvent, err := json.Marshal(event) if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to serialize event: %v", err.Error()) } namespaceOption := pubsub.WithPublishNamespace(e.namespace) topic := getSpaceTopic(spaceID) err = e.pubsub.Publish(ctx, topic, serializedEvent, namespaceOption) if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to publish %s event", eventType) } } func (e *pubsubStreamer) Stream( ctx context.Context, spaceID int64, ) (<-chan *Event, <-chan error, func(context.Context) error) { chEvent := make(chan *Event, 100) // TODO: check best size here chErr := make(chan error) g := func(payload []byte) error { event := &Event{} err := json.Unmarshal(payload, event) if err != nil { // This should never happen return err } select { case chEvent <- event: default: } return nil } namespaceOption := pubsub.WithChannelNamespace(e.namespace) topic := getSpaceTopic(spaceID) consumer := e.pubsub.Subscribe(ctx, topic, g, namespaceOption) cleanupFN := func(_ context.Context) error { return consumer.Close() } return chEvent, chErr, cleanupFN } // getSpaceTopic creates the namespace name which will be `spaces:<id>`. func getSpaceTopic(spaceID int64) string { return "spaces:" + strconv.Itoa(int(spaceID)) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/wire.go
app/events/rule/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/reader.go
app/events/rule/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/reporter.go
app/events/rule/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/category.go
app/events/rule/category.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 events const ( // category defines the event category used for this package. category = "rule" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/events.go
app/events/rule/events.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 events type Base struct { RuleID int64 `json:"rule_id"` SpaceID *int64 `json:"space_id"` RepoID *int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/rule/events_rule.go
app/events/rule/events_rule.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const CreatedEvent events.EventType = "created" type CreatedPayload struct { Base } func (r *Reporter) Created(ctx context.Context, payload *CreatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send rule created event") return } log.Ctx(ctx).Debug().Msgf("reported rule created event with id '%s'", eventID) } func (r *Reader) RegisterCreated( fn events.HandlerFunc[*CreatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CreatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceinfra/wire.go
app/events/gitspaceinfra/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceinfra/reader.go
app/events/gitspaceinfra/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceinfra/reporter.go
app/events/gitspaceinfra/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceinfra/category.go
app/events/gitspaceinfra/category.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 events const ( // category defines the event category used for this package. category = "gitspace_infra" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceinfra/events.go
app/events/gitspaceinfra/events.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 events import ( "context" "fmt" "github.com/harness/gitness/events" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( // List all Gitspace Infra events below. GitspaceInfraEvent events.EventType = "gitspace_infra_event" ) type ( GitspaceInfraEventPayload struct { Infra types.Infrastructure `json:"infra,omitzero"` Type enum.InfraEvent `json:"type"` } ) func (r *Reporter) EmitGitspaceInfraEvent( ctx context.Context, event events.EventType, payload *GitspaceInfraEventPayload, ) error { if payload == nil { return fmt.Errorf("payload can not be nil for event type %s", GitspaceInfraEvent) } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, event, payload) if err != nil { return fmt.Errorf("failed to send %+v event", event) } log.Ctx(ctx).Debug().Msgf("reported %v event with id '%s'", event, eventID) return nil } func (r *Reader) RegisterGitspaceInfraEvent( fn events.HandlerFunc[*GitspaceInfraEventPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, GitspaceInfraEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/wire.go
app/events/user/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/reader.go
app/events/user/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/reporter.go
app/events/user/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/category.go
app/events/user/category.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 events const ( // category defines the event category used for this package. category = "user" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/events.go
app/events/user/events.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 events type Base struct { PrincipalID int64 `json:"principal_id"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/user/events_user.go
app/events/user/events_user.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const RegisteredEvent events.EventType = "registered" type RegisteredPayload struct { Base } func (r *Reporter) Registered(ctx context.Context, payload *RegisteredPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, RegisteredEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send user registered event") return } log.Ctx(ctx).Debug().Msgf("reported user registered event with id '%s'", eventID) } func (r *Reader) RegisterRegistered( fn events.HandlerFunc[*RegisteredPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, RegisteredEvent, fn, opts...) } const CreatedEvent events.EventType = "created" type CreatedPayload struct { Base // CreatedPrincipalID is ID of the created user. CreatedPrincipalID int64 `json:"created_principal_id"` } func (r *Reporter) Created(ctx context.Context, payload *CreatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send user created event") return } log.Ctx(ctx).Debug().Msgf("reported user created event with id '%s'", eventID) } func (r *Reader) RegisterCreated( fn events.HandlerFunc[*CreatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CreatedEvent, fn, opts...) } const LoggedInEvent events.EventType = "logged-in" type LoggedInPayload struct { Base } func (r *Reporter) LoggedIn(ctx context.Context, payload *LoggedInPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, LoggedInEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send user logged-in event") return } log.Ctx(ctx).Debug().Msgf("reported user logged-in event with id '%s'", eventID) } func (r *Reader) RegisterLoggedIn( fn events.HandlerFunc[*LoggedInPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, LoggedInEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspace/wire.go
app/events/gitspace/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspace/reader.go
app/events/gitspace/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspace/reporter.go
app/events/gitspace/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspace/category.go
app/events/gitspace/category.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 events const ( // category defines the event category used for this package. category = "gitspace" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspace/events.go
app/events/gitspace/events.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( // List all Gitspace events below. GitspaceEvent events.EventType = "gitspace_event" ) type ( GitspaceEventPayload struct { EntityID int64 `json:"entity_id,omitempty"` QueryKey string `json:"query_key,omitempty"` EntityType enum.GitspaceEntityType `json:"entity_type,omitempty"` EventType enum.GitspaceEventType `json:"event_type,omitempty"` Timestamp int64 `json:"timestamp,omitempty"` } ) func (r *Reporter) EmitGitspaceEvent(ctx context.Context, event events.EventType, payload *GitspaceEventPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, event, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send %s event", event) return } log.Ctx(ctx).Debug().Msgf("reported %s event with id '%s'", event, eventID) } func (r *Reader) RegisterGitspaceEvent( fn events.HandlerFunc[*GitspaceEventPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, GitspaceEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/wire.go
app/events/check/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/reader.go
app/events/check/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/reporter.go
app/events/check/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/category.go
app/events/check/category.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 events const ( // category defines the event category used for this package. category = "check" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/events.go
app/events/check/events.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 events type Base struct { RepoID int64 `json:"repo_id"` SHA string `json:"sha"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/check/events_check_reported.go
app/events/check/events_check_reported.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) // ReportedEvent is the event type for check status reporting. const ReportedEvent events.EventType = "reported" type ReportedPayload struct { Base Identifier string `json:"identifier"` Status enum.CheckStatus `json:"status"` } func (r *Reporter) Reported(ctx context.Context, payload *ReportedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ReportedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send check status event") return } log.Ctx(ctx).Debug().Msgf("reported check status event with id '%s'", eventID) } func (r *Reader) RegisterReported( fn events.HandlerFunc[*ReportedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, ReportedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_code_comment_updated.go
app/events/pullreq/events_code_comment_updated.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const CommentUpdatedEvent events.EventType = "comment-updated" type CommentUpdatedPayload struct { Base ActivityID int64 `json:"activity_id"` IsReply bool `json:"is_reply"` } func (r *Reporter) CommentUpdated( ctx context.Context, payload *CommentUpdatedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CommentUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf( "failed to send pull request comment updated event for event id '%s'", eventID, ) return } log.Ctx(ctx).Debug().Msgf("reported pull request comment updated event with id '%s'", eventID) } func (r *Reader) RegisterCommentUpdated( fn events.HandlerFunc[*CommentUpdatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CommentUpdatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/wire.go
app/events/pullreq/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_code_comment_status.go
app/events/pullreq/events_code_comment_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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const CommentStatusUpdatedEvent events.EventType = "comment-status-updated" type CommentStatusUpdatedPayload struct { Base ActivityID int64 `json:"activity_id"` } func (r *Reporter) CommentStatusUpdated( ctx context.Context, payload *CommentStatusUpdatedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CommentStatusUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf( "failed to send pull request comment status updated event for event id '%s'", eventID) return } log.Ctx(ctx).Debug().Msgf("reported pull request comment status update event with id '%s'", eventID) } func (r *Reader) RegisterCommentStatusUpdated( fn events.HandlerFunc[*CommentStatusUpdatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CommentStatusUpdatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_review_submitted.go
app/events/pullreq/events_review_submitted.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ReviewSubmittedEvent events.EventType = "review-submitted" type ReviewSubmittedPayload struct { Base ReviewerID int64 Decision enum.PullReqReviewDecision } func (r *Reporter) ReviewSubmitted( ctx context.Context, payload *ReviewSubmittedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ReviewSubmittedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request review submitted event") return } log.Ctx(ctx).Debug().Msgf("reported pull request review submitted event with id '%s'", eventID) } func (r *Reader) RegisterReviewSubmitted( fn events.HandlerFunc[*ReviewSubmittedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, ReviewSubmittedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_branch.go
app/events/pullreq/events_branch.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const BranchUpdatedEvent events.EventType = "branch-updated" type BranchUpdatedPayload struct { Base OldSHA string `json:"old_sha"` NewSHA string `json:"new_sha"` OldMergeBaseSHA string `json:"old_merge_base_sha"` NewMergeBaseSHA string `json:"new_merge_base_sha"` Forced bool `json:"forced"` } func (r *Reporter) BranchUpdated(ctx context.Context, payload *BranchUpdatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, BranchUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request branch updated event") return } log.Ctx(ctx).Debug().Msgf("reported pull request branch updated event with id '%s'", eventID) } func (r *Reader) RegisterBranchUpdated( fn events.HandlerFunc[*BranchUpdatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, BranchUpdatedEvent, fn, opts...) } const TargetBranchChangedEvent events.EventType = "target-branch-changed" type TargetBranchChangedPayload struct { Base SourceSHA string `json:"source_sha"` OldTargetBranch string `json:"old_target_branch"` NewTargetBranch string `json:"new_target_branch"` OldMergeBaseSHA string `json:"old_merge_base_sha"` NewMergeBaseSHA string `json:"new_merge_base_sha"` } func (r *Reporter) TargetBranchChanged( ctx context.Context, payload *TargetBranchChangedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent( r.innerReporter, ctx, TargetBranchChangedEvent, payload, ) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request target branch changed event") return } log.Ctx(ctx).Debug().Msgf( "reported pull request target branch changed event with id '%s'", eventID, ) } func (r *Reader) RegisterTargetBranchChanged( fn events.HandlerFunc[*TargetBranchChangedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, TargetBranchChangedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_reviewer.go
app/events/pullreq/events_reviewer.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const ( ReviewerAddedEvent events.EventType = "reviewer-added" UserGroupReviewerAdded events.EventType = "usergroup-reviewer-added" ) type ReviewerAddedPayload struct { Base ReviewerID int64 `json:"reviewer_id"` } type UserGroupReviewerAddedPayload struct { Base UserGroupReviewerID int64 `json:"usergroup_reviewer_id"` } func (r *Reporter) ReviewerAdded( ctx context.Context, payload *ReviewerAddedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ReviewerAddedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request reviewer added event") return } log.Ctx(ctx).Debug().Msgf("reported pull request reviewer added event with id '%s'", eventID) } func (r *Reader) RegisterReviewerAdded( fn events.HandlerFunc[*ReviewerAddedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, ReviewerAddedEvent, fn, opts...) } func (r *Reporter) UserGroupReviewerAdded( ctx context.Context, payload *UserGroupReviewerAddedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, UserGroupReviewerAdded, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request reviewer added event") return } log.Ctx(ctx).Debug().Msgf("reported pull request reviewer added event with id '%s'", eventID) } func (r *Reader) RegisterUserGroupReviewerAdded( fn events.HandlerFunc[*UserGroupReviewerAddedPayload], opts ...events.HandlerOption, ) error { // TODO: Start using this for sending out notifications return events.ReaderRegisterEvent(r.innerReader, UserGroupReviewerAdded, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_state.go
app/events/pullreq/events_state.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const CreatedEvent events.EventType = "created" type CreatedPayload struct { Base SourceBranch string `json:"source_branch"` TargetBranch string `json:"target_branch"` SourceSHA string `json:"source_sha"` ReviewerIDs []int64 `json:"reviewer_ids"` } func (r *Reporter) Created(ctx context.Context, payload *CreatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request created event") return } log.Ctx(ctx).Debug().Msgf("reported pull request created event with id '%s'", eventID) } func (r *Reader) RegisterCreated( fn events.HandlerFunc[*CreatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CreatedEvent, fn, opts...) } const ClosedEvent events.EventType = "closed" type ClosedPayload struct { Base SourceBranch string `json:"source_branch"` SourceSHA string `json:"source_sha"` } func (r *Reporter) Closed(ctx context.Context, payload *ClosedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ClosedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request closed event") return } log.Ctx(ctx).Debug().Msgf("reported pull request closed event with id '%s'", eventID) } func (r *Reader) RegisterClosed( fn events.HandlerFunc[*ClosedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, ClosedEvent, fn, opts...) } const ReopenedEvent events.EventType = "reopened" type ReopenedPayload struct { Base SourceBranch string `json:"source_branch"` SourceSHA string `json:"source_sha"` MergeBaseSHA string `json:"merge_base_sha"` } func (r *Reporter) Reopened(ctx context.Context, payload *ReopenedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ReopenedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request reopened event") return } log.Ctx(ctx).Debug().Msgf("reported pull request reopened event with id '%s'", eventID) } func (r *Reader) RegisterReopened( fn events.HandlerFunc[*ReopenedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, ReopenedEvent, fn, opts...) } const MergedEvent events.EventType = "merged" type MergedPayload struct { Base MergeMethod enum.MergeMethod `json:"merge_method"` MergeSHA string `json:"merge_sha"` TargetSHA string `json:"target_sha"` SourceSHA string `json:"source_sha"` } func (r *Reporter) Merged(ctx context.Context, payload *MergedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, MergedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request merged event") return } log.Ctx(ctx).Debug().Msgf("reported pull request merged event with id '%s'", eventID) } func (r *Reader) RegisterMerged( fn events.HandlerFunc[*MergedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, MergedEvent, fn, opts...) } const UpdatedEvent events.EventType = "updated" type UpdatedPayload struct { Base TitleChanged bool `json:"title_changed"` TitleOld string `json:"title_old"` TitleNew string `json:"title_new"` DescriptionChanged bool `json:"description_changed"` DescriptionOld string `json:"description_old"` DescriptionNew string `json:"description_new"` } func (r *Reporter) Updated(ctx context.Context, payload *UpdatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, UpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request created event") return } log.Ctx(ctx).Debug().Msgf("reported pull request created event with id '%s'", eventID) } func (r *Reader) RegisterUpdated( fn events.HandlerFunc[*UpdatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, UpdatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/reader.go
app/events/pullreq/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/reporter.go
app/events/pullreq/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_label_assigned.go
app/events/pullreq/events_label_assigned.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const LabelAssignedEvent events.EventType = "label-assigned" type LabelAssignedPayload struct { Base LabelID int64 `json:"label_id"` ValueID *int64 `json:"value_id"` } func (r *Reporter) LabelAssigned( ctx context.Context, payload *LabelAssignedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, LabelAssignedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request label assigned event") return } log.Ctx(ctx).Debug().Msgf("reported pull request label assigned event with id '%s'", eventID) } func (r *Reader) RegisterLabelAssigned( fn events.HandlerFunc[*LabelAssignedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, LabelAssignedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/category.go
app/events/pullreq/category.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 events const ( // category defines the event category used for this package. category = "pullreq" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events.go
app/events/pullreq/events.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 events type Base struct { PullReqID int64 `json:"pullreq_id"` SourceRepoID *int64 `json:"source_repo_id"` TargetRepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Number int64 `json:"number"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pullreq/events_comment_created.go
app/events/pullreq/events_comment_created.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const CommentCreatedEvent events.EventType = "comment-created" type CommentCreatedPayload struct { Base ActivityID int64 `json:"activity_id"` SourceSHA string `json:"source_sha"` IsReply bool `json:"is_reply"` } func (r *Reporter) CommentCreated( ctx context.Context, payload *CommentCreatedPayload, ) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CommentCreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pull request comment created event") return } log.Ctx(ctx).Debug().Msgf("reported pull request comment created event with id '%s'", eventID) } func (r *Reader) RegisterCommentCreated( fn events.HandlerFunc[*CommentCreatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CommentCreatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspacedelete/wire.go
app/events/gitspacedelete/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspacedelete/reader.go
app/events/gitspacedelete/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspacedelete/reporter.go
app/events/gitspacedelete/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspacedelete/category.go
app/events/gitspacedelete/category.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 events const ( // category defines the event category used for this package. category = "gitspace_delete" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspacedelete/events.go
app/events/gitspacedelete/events.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const ( GitspaceDeleteEvent events.EventType = "gitspace_delete_event" ) type ( GitspaceDeleteEventPayload struct { GitspaceConfigIdentifier string `json:"gitspace_config_identifier"` SpaceID int64 `json:"space_id"` } ) func (r *Reporter) EmitGitspaceDeleteEvent( ctx context.Context, event events.EventType, payload *GitspaceDeleteEventPayload, ) { if payload == nil { return } if event != GitspaceDeleteEvent { log.Ctx(ctx).Error().Msgf("event type should be %s, got %s, aborting emission, payload: %+v", GitspaceDeleteEvent, event, payload) return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, event, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send %s event", event) return } log.Ctx(ctx).Debug().Msgf("reported %s event with id '%s'", event, eventID) } func (r *Reader) RegisterGitspaceDeleteEvent( fn events.HandlerFunc[*GitspaceDeleteEventPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, GitspaceDeleteEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/wire.go
app/events/repo/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/reader.go
app/events/repo/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/reporter.go
app/events/repo/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/events_repo.go
app/events/repo/events_repo.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const CreatedEvent events.EventType = "created" type CreatedPayload struct { Base IsPublic bool `json:"is_public"` IsMigrated bool `json:"is_migrated"` ImportedFrom string `json:"imported_from"` } func (r *Reporter) Created(ctx context.Context, payload *CreatedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send repo created event") return } log.Ctx(ctx).Debug().Msgf("reported repo created event with id '%s'", eventID) } func (r *Reader) RegisterCreated( fn events.HandlerFunc[*CreatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, CreatedEvent, fn, opts...) } const StateChangedEvent events.EventType = "state-changed" type StateChangedPayload struct { Base OldState enum.RepoState `json:"old_state"` NewState enum.RepoState `json:"new_state"` } func (r *Reporter) StateChanged(ctx context.Context, payload *StateChangedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, StateChangedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send repo srtate change event") return } log.Ctx(ctx).Debug().Msgf("reported repo state change event with id '%s'", eventID) } func (r *Reader) RegisterStateChanged( fn events.HandlerFunc[*StateChangedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, StateChangedEvent, fn, opts...) } const PublicAccessChangedEvent events.EventType = "public-access-changed" type PublicAccessChangedPayload struct { Base OldIsPublic bool `json:"old_is_public"` NewIsPublic bool `json:"new_is_public"` } func (r *Reporter) PublicAccessChanged(ctx context.Context, payload *PublicAccessChangedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, PublicAccessChangedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send repo public access changed event") return } log.Ctx(ctx).Debug().Msgf("reported repo public access changed event with id '%s'", eventID) } func (r *Reader) RegisterPublicAccessChanged( fn events.HandlerFunc[*PublicAccessChangedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, PublicAccessChangedEvent, fn, opts...) } const SoftDeletedEvent events.EventType = "soft-deleted" type SoftDeletedPayload struct { Base RepoPath string `json:"repo_path"` Deleted int64 `json:"deleted"` } func (r *Reporter) SoftDeleted(ctx context.Context, payload *SoftDeletedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, SoftDeletedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send repo soft deleted event") return } log.Ctx(ctx).Debug().Msgf("reported repo soft deleted event with id '%s'", eventID) } func (r *Reader) RegisterSoftDeleted( fn events.HandlerFunc[*SoftDeletedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, SoftDeletedEvent, fn, opts...) } const DeletedEvent events.EventType = "deleted" type DeletedPayload struct { Base } func (r *Reporter) Deleted(ctx context.Context, payload *DeletedPayload) { if payload == nil { return } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, DeletedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send repo deleted event") return } log.Ctx(ctx).Debug().Msgf("reported repo deleted event with id '%s'", eventID) } func (r *Reader) RegisterDeleted( fn events.HandlerFunc[*DeletedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, DeletedEvent, fn, opts...) } const DefaultBranchUpdatedEvent events.EventType = "default-branch-updated" type DefaultBranchUpdatedPayload struct { Base OldName string `json:"old_name"` NewName string `json:"new_name"` } func (r *Reporter) DefaultBranchUpdated(ctx context.Context, payload *DefaultBranchUpdatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, DefaultBranchUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send default branch updated event") return } log.Ctx(ctx).Debug().Msgf("reported default branch updated event with id '%s'", eventID) } func (r *Reader) RegisterDefaultBranchUpdated( fn events.HandlerFunc[*DefaultBranchUpdatedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, DefaultBranchUpdatedEvent, fn, opts...) } const PushedEvent events.EventType = "pushed" type PushedPayload struct { Base } func (r *Reporter) Pushed(ctx context.Context, payload *PushedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, PushedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pushed event") return } log.Ctx(ctx).Debug().Msgf("reported pushed event with id '%s'", eventID) } func (r *Reader) RegisterPushed( fn events.HandlerFunc[*PushedPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, PushedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/category.go
app/events/repo/category.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 events const ( // category defines the event category used for this package. category = "repo" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/repo/events.go
app/events/repo/events.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 events type Base struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/wire.go
app/events/git/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/reader.go
app/events/git/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. // It exposes typesafe event registration methods for all events by this package. // NOTE: Event registration methods are in the event's dedicated file. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/reporter.go
app/events/git/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. // It exposes typesafe send methods for all events of this package. // NOTE: Event send methods are in the event's dedicated file. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/tag.go
app/events/git/tag.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const TagCreatedEvent events.EventType = "tag-created" type TagCreatedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` SHA string `json:"sha"` } func (r *Reporter) TagCreated(ctx context.Context, payload *TagCreatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, TagCreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send tag created event") return } log.Ctx(ctx).Debug().Msgf("reported tag created event with id '%s'", eventID) } func (r *Reader) RegisterTagCreated(fn events.HandlerFunc[*TagCreatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, TagCreatedEvent, fn, opts...) } const TagUpdatedEvent events.EventType = "tag-updated" type TagUpdatedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` OldSHA string `json:"old_sha"` NewSHA string `json:"new_sha"` Forced bool `json:"forced"` } func (r *Reporter) TagUpdated(ctx context.Context, payload *TagUpdatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, TagUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send tag updated event") return } log.Ctx(ctx).Debug().Msgf("reported tag updated event with id '%s'", eventID) } func (r *Reader) RegisterTagUpdated(fn events.HandlerFunc[*TagUpdatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, TagUpdatedEvent, fn, opts...) } const TagDeletedEvent events.EventType = "tag-deleted" type TagDeletedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` SHA string `json:"sha"` } func (r *Reporter) TagDeleted(ctx context.Context, payload *TagDeletedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, TagDeletedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send tag deleted event") return } log.Ctx(ctx).Debug().Msgf("reported tag deleted event with id '%s'", eventID) } func (r *Reader) RegisterTagDeleted(fn events.HandlerFunc[*TagDeletedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, TagDeletedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/branch.go
app/events/git/branch.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const BranchCreatedEvent events.EventType = "branch-created" type BranchCreatedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` SHA string `json:"sha"` } func (r *Reporter) BranchCreated(ctx context.Context, payload *BranchCreatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, BranchCreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send branch created event") return } log.Ctx(ctx).Debug().Msgf("reported branch created event with id '%s'", eventID) } func (r *Reader) RegisterBranchCreated(fn events.HandlerFunc[*BranchCreatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, BranchCreatedEvent, fn, opts...) } const BranchUpdatedEvent events.EventType = "branch-updated" type BranchUpdatedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` OldSHA string `json:"old_sha"` NewSHA string `json:"new_sha"` Forced bool `json:"forced"` } func (r *Reporter) BranchUpdated(ctx context.Context, payload *BranchUpdatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, BranchUpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send branch updated event") return } log.Ctx(ctx).Debug().Msgf("reported branch updated event with id '%s'", eventID) } func (r *Reader) RegisterBranchUpdated(fn events.HandlerFunc[*BranchUpdatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, BranchUpdatedEvent, fn, opts...) } const BranchDeletedEvent events.EventType = "branch-deleted" type BranchDeletedPayload struct { RepoID int64 `json:"repo_id"` PrincipalID int64 `json:"principal_id"` Ref string `json:"ref"` SHA string `json:"sha"` } func (r *Reporter) BranchDeleted(ctx context.Context, payload *BranchDeletedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, BranchDeletedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send branch deleted event") return } log.Ctx(ctx).Debug().Msgf("reported branch deleted event with id '%s'", eventID) } func (r *Reader) RegisterBranchDeleted(fn events.HandlerFunc[*BranchDeletedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, BranchDeletedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/git/events.go
app/events/git/events.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 events const ( // category defines the event category used for this package. category = "git" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/aitask/wire.go
app/events/aitask/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/aitask/reader.go
app/events/aitask/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/aitask/reporter.go
app/events/aitask/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/aitask/category.go
app/events/aitask/category.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 events const ( // category defines the event category used for this package. category = "gitspace-ai-task" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/aitask/events.go
app/events/aitask/events.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 events import ( "context" "fmt" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( AITaskEvent events.EventType = "gitspace_ai_task_event" ) type ( AITaskEventPayload struct { Type enum.AITaskEvent `json:"type"` AITaskIdentifier string `json:"ai_task_identifier"` AITaskSpaceID int64 `json:"ai_task_space_id"` } ) func (r *Reporter) EmitAITaskEvent( ctx context.Context, event events.EventType, payload *AITaskEventPayload, ) error { if payload == nil { return fmt.Errorf("payload can not be nil for event type %s", AITaskEvent) } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, event, payload) if err != nil { return fmt.Errorf("failed to send %s event: %w", event, err) } log.Ctx(ctx).Debug().Msgf("reported %v event with id '%s'", event, eventID) return nil } func (r *Reader) RegisterAITaskEvent( fn events.HandlerFunc[*AITaskEventPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, AITaskEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceoperations/wire.go
app/events/gitspaceoperations/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceoperations/reader.go
app/events/gitspaceoperations/reader.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 events import ( "github.com/harness/gitness/events" ) func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceoperations/reporter.go
app/events/gitspaceoperations/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceoperations/category.go
app/events/gitspaceoperations/category.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 events const ( // category defines the event category used for this package. category = "gitspace_operations" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/gitspaceoperations/events.go
app/events/gitspaceoperations/events.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 events import ( "context" "fmt" "github.com/harness/gitness/events" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ( GitspaceOperationsEvent events.EventType = "gitspace_operations_event" ) type ( GitspaceOperationsEventPayload struct { Type enum.GitspaceOperationsEvent `json:"type"` Infra types.Infrastructure `json:"infra,omitzero"` Response any `json:"response,omitempty"` } ) func (r *Reporter) EmitGitspaceOperationsEvent( ctx context.Context, event events.EventType, payload *GitspaceOperationsEventPayload, ) error { if payload == nil { return fmt.Errorf("payload can not be nil for event type %s", GitspaceOperationsEvent) } eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, event, payload) if err != nil { return fmt.Errorf("failed to send %s event: %w", event, err) } log.Ctx(ctx).Debug().Msgf("reported %v event with id '%s'", event, eventID) return nil } func (r *Reader) RegisterGitspaceOperationsEvent( fn events.HandlerFunc[*GitspaceOperationsEventPayload], opts ...events.HandlerOption, ) error { return events.ReaderRegisterEvent(r.innerReader, GitspaceOperationsEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/wire.go
app/events/pipeline/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 events import ( "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideReaderFactory, ProvideReporter, ) func ProvideReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { return NewReaderFactory(eventsSystem) } func ProvideReporter(eventsSystem *events.System) (*Reporter, error) { return NewReporter(eventsSystem) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/create.go
app/events/pipeline/create.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const CreatedEvent events.EventType = "created" type CreatedPayload struct { PipelineID int64 `json:"pipeline_id"` RepoID int64 `json:"repo_id"` } func (r *Reporter) Created(ctx context.Context, payload *CreatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, CreatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pipeline created event") return } log.Ctx(ctx).Debug().Msgf("reported pipeline created event with id '%s'", eventID) } func (r *Reader) RegisterCreated(fn events.HandlerFunc[*CreatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, CreatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/reader.go
app/events/pipeline/reader.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 events import "github.com/harness/gitness/events" func NewReaderFactory(eventsSystem *events.System) (*events.ReaderFactory[*Reader], error) { readerFactoryFunc := func(innerReader *events.GenericReader) (*Reader, error) { return &Reader{ innerReader: innerReader, }, nil } return events.NewReaderFactory(eventsSystem, category, readerFactoryFunc) } // Reader is the event reader for this package. // It exposes typesafe event registration methods for all events by this package. // NOTE: Event registration methods are in the event's dedicated file. type Reader struct { innerReader *events.GenericReader } func (r *Reader) Configure(opts ...events.ReaderOption) { r.innerReader.Configure(opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/reporter.go
app/events/pipeline/reporter.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 events import ( "errors" "github.com/harness/gitness/events" ) // Reporter is the event reporter for this package. // It exposes typesafe send methods for all events of this package. // NOTE: Event send methods are in the event's dedicated file. type Reporter struct { innerReporter *events.GenericReporter } func NewReporter(eventsSystem *events.System) (*Reporter, error) { innerReporter, err := events.NewReporter(eventsSystem, category) if err != nil { return nil, errors.New("failed to create new GenericReporter from event system") } return &Reporter{ innerReporter: innerReporter, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/execute.go
app/events/pipeline/execute.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 events import ( "context" "github.com/harness/gitness/events" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) const ExecutedEvent events.EventType = "executed" type ExecutedPayload struct { PipelineID int64 `json:"pipeline_id"` RepoID int64 `json:"repo_id"` ExecutionNum int64 `json:"execution_number"` Status enum.CIStatus `json:"status"` } func (r *Reporter) Executed(ctx context.Context, payload *ExecutedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, ExecutedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pipeline executed event") return } log.Ctx(ctx).Debug().Msgf("reported pipeline executed event with id '%s'", eventID) } func (r *Reader) RegisterExecuted(fn events.HandlerFunc[*ExecutedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, ExecutedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/events.go
app/events/pipeline/events.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 events const ( // category defines the event category used for this package. category = "pipeline" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/events/pipeline/update.go
app/events/pipeline/update.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 events import ( "context" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) const UpdatedEvent events.EventType = "updated" type UpdatedPayload struct { PipelineID int64 `json:"pipeline_id"` RepoID int64 `json:"repo_id"` } func (r *Reporter) Updated(ctx context.Context, payload *UpdatedPayload) { eventID, err := events.ReporterSendEvent(r.innerReporter, ctx, UpdatedEvent, payload) if err != nil { log.Ctx(ctx).Err(err).Msgf("failed to send pipeline updated event") return } log.Ctx(ctx).Debug().Msgf("reported pipeline update event with id '%s'", eventID) } func (r *Reader) RegisterUpdated(fn events.HandlerFunc[*UpdatedPayload], opts ...events.HandlerOption) error { return events.ReaderRegisterEvent(r.innerReader, UpdatedEvent, fn, opts...) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/token/token.go
app/token/token.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 token import ( "context" "fmt" "math/rand/v2" "time" "github.com/harness/gitness/app/jwt" "github.com/harness/gitness/app/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/gotidy/ptr" ) const ( // userSessionTokenLifeTime is the duration a login / register token is valid. // NOTE: Users can list / delete session tokens via rest API if they want to cleanup earlier. userSessionTokenLifeTime time.Duration = 30 * 24 * time.Hour // 30 days. sessionTokenWithAccessPermissionsLifeTime time.Duration = 24 * time.Hour // 24 hours. RemoteAuthTokenLifeTime time.Duration = 15 * time.Minute // 15 minutes. ) func CreateUserWithAccessPermissions( user *types.User, accessPermissions *jwt.SubClaimsAccessPermissions, ) (string, error) { principal := user.ToPrincipal() return createWithAccessPermissions( principal, ptr.Duration(sessionTokenWithAccessPermissionsLifeTime), accessPermissions, ) } func CreateUserSession( ctx context.Context, tokenStore store.TokenStore, user *types.User, identifier string, ) (*types.Token, string, error) { principal := user.ToPrincipal() return create( ctx, tokenStore, enum.TokenTypeSession, principal, principal, identifier, ptr.Duration(userSessionTokenLifeTime), ) } func CreatePAT( ctx context.Context, tokenStore store.TokenStore, createdBy *types.Principal, createdFor *types.User, identifier string, lifetime *time.Duration, ) (*types.Token, string, error) { return create( ctx, tokenStore, enum.TokenTypePAT, createdBy, createdFor.ToPrincipal(), identifier, lifetime, ) } func CreateSAT( ctx context.Context, tokenStore store.TokenStore, createdBy *types.Principal, createdFor *types.ServiceAccount, identifier string, lifetime *time.Duration, ) (*types.Token, string, error) { return create( ctx, tokenStore, enum.TokenTypeSAT, createdBy, createdFor.ToPrincipal(), identifier, lifetime, ) } func CreateRemoteAuthToken( ctx context.Context, tokenStore store.TokenStore, principal *types.Principal, identifier string, ) (*types.Token, string, error) { return create( ctx, tokenStore, enum.TokenTypeRemoteAuth, principal, principal, identifier, ptr.Duration(RemoteAuthTokenLifeTime), ) } func GenerateIdentifier(prefix string) string { //nolint:gosec // math/rand is sufficient for this use case r := rand.IntN(0x10000) return fmt.Sprintf("%s-%08x-%04x", prefix, time.Now().Unix(), r) } func create( ctx context.Context, tokenStore store.TokenStore, tokenType enum.TokenType, createdBy *types.Principal, createdFor *types.Principal, identifier string, lifetime *time.Duration, ) (*types.Token, string, error) { issuedAt := time.Now() var expiresAt *int64 if lifetime != nil { expiresAt = ptr.Int64(issuedAt.Add(*lifetime).UnixMilli()) } // create db entry first so we get the id. token := types.Token{ Type: tokenType, Identifier: identifier, PrincipalID: createdFor.ID, IssuedAt: issuedAt.UnixMilli(), ExpiresAt: expiresAt, CreatedBy: createdBy.ID, } err := tokenStore.Create(ctx, &token) if err != nil { return nil, "", fmt.Errorf("failed to store token in db: %w", err) } // create jwt token. jwtToken, err := jwt.GenerateForToken(&token, createdFor.Salt) if err != nil { return nil, "", fmt.Errorf("failed to create jwt token: %w", err) } return &token, jwtToken, nil } func createWithAccessPermissions( createdFor *types.Principal, lifetime *time.Duration, accessPermissions *jwt.SubClaimsAccessPermissions, ) (string, error) { jwtToken, err := jwt.GenerateForTokenWithAccessPermissions( createdFor.ID, lifetime, createdFor.Salt, accessPermissions, ) if err != nil { return "", fmt.Errorf("failed to create jwt token: %w", err) } return jwtToken, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/paths/paths_test.go
app/paths/paths_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 paths import ( "testing" "github.com/stretchr/testify/assert" ) func Test_Concatenate(t *testing.T) { type testCase struct { in []string want string } tests := []testCase{ { in: nil, want: "", }, { in: []string{}, want: "", }, { in: []string{ "", }, want: "", }, { in: []string{ "", "", }, want: "", }, { in: []string{ "a", }, want: "a", }, { in: []string{ "", "a", }, want: "a", }, { in: []string{ "a", "", }, want: "a", }, { in: []string{ "", "a", "", }, want: "a", }, { in: []string{ "a", "b", }, want: "a/b", }, { in: []string{ "a", "b", "c", }, want: "a/b/c", }, { in: []string{ "seg1", "seg2/seg3", "seg4", }, want: "seg1/seg2/seg3/seg4", }, { in: []string{ "/", "/", "/", }, want: "", }, { in: []string{ "//", }, want: "", }, { in: []string{ "/a/", }, want: "a", }, { in: []string{ "/a/", "/b/", }, want: "a/b", }, { in: []string{ "/a/b/", "//c//d//", "///e///f///", }, want: "a/b/c/d/e/f", }, } for _, tt := range tests { got := Concatenate(tt.in...) assert.Equal(t, tt.want, got, "path isn't matching for %v", tt.in) } } func Test_Depth(t *testing.T) { type testCase struct { in string want int } tests := []testCase{ { in: "", want: 0, }, { in: "/", want: 0, }, { in: "a", want: 1, }, { in: "/a/", want: 1, }, { in: "a/b", want: 2, }, { in: "/a/b/c/d/e/f/", want: 6, }, } for _, tt := range tests { got := Depth(tt.in) assert.Equal(t, tt.want, got, "depth isn't matching for %q", tt.in) } } func Test_DisectLeaf(t *testing.T) { type testCase struct { in string wantParent string wantLeaf string wantErr error } tests := []testCase{ { in: "", wantParent: "", wantLeaf: "", wantErr: ErrPathEmpty, }, { in: "/", wantParent: "", wantLeaf: "", wantErr: ErrPathEmpty, }, { in: "space1", wantParent: "", wantLeaf: "space1", wantErr: nil, }, { in: "/space1/", wantParent: "", wantLeaf: "space1", wantErr: nil, }, { in: "space1/space2", wantParent: "space1", wantLeaf: "space2", wantErr: nil, }, { in: "/space1/space2/", wantParent: "space1", wantLeaf: "space2", wantErr: nil, }, { in: "space1/space2/space3", wantParent: "space1/space2", wantLeaf: "space3", wantErr: nil, }, { in: "/space1/space2/space3/", wantParent: "space1/space2", wantLeaf: "space3", wantErr: nil, }, } for _, tt := range tests { gotParent, gotLeaf, gotErr := DisectLeaf(tt.in) assert.Equal(t, tt.wantParent, gotParent, "parent isn't matching for %q", tt.in) assert.Equal(t, tt.wantLeaf, gotLeaf, "leaf isn't matching for %q", tt.in) assert.Equal(t, tt.wantErr, gotErr, "error isn't matching for %q", tt.in) } } func Test_DisectRoot(t *testing.T) { type testCase struct { in string wantRoot string wantSubPath string wantErr error } tests := []testCase{ { in: "", wantRoot: "", wantSubPath: "", wantErr: ErrPathEmpty, }, { in: "/", wantRoot: "", wantSubPath: "", wantErr: ErrPathEmpty, }, { in: "space1", wantRoot: "space1", wantSubPath: "", wantErr: nil, }, { in: "/space1/", wantRoot: "space1", wantSubPath: "", wantErr: nil, }, { in: "space1/space2", wantRoot: "space1", wantSubPath: "space2", wantErr: nil, }, { in: "/space1/space2/", wantRoot: "space1", wantSubPath: "space2", wantErr: nil, }, { in: "space1/space2/space3", wantRoot: "space1", wantSubPath: "space2/space3", wantErr: nil, }, { in: "/space1/space2/space3/", wantRoot: "space1", wantSubPath: "space2/space3", wantErr: nil, }, } for _, tt := range tests { gotRoot, gotSubPath, gotErr := DisectRoot(tt.in) assert.Equal(t, tt.wantRoot, gotRoot, "root isn't matching for %q", tt.in) assert.Equal(t, tt.wantSubPath, gotSubPath, "subPath isn't matching for %q", tt.in) assert.Equal(t, tt.wantErr, gotErr, "error isn't matching for %q", tt.in) } } func Test_Segments(t *testing.T) { type testCase struct { in string want []string } tests := []testCase{ { in: "", want: []string{""}, }, { in: "/", want: []string{""}, }, { in: "space1", want: []string{"space1"}, }, { in: "/space1/", want: []string{"space1"}, }, { in: "space1/space2", want: []string{"space1", "space2"}, }, { in: "/space1/space2/", want: []string{"space1", "space2"}, }, { in: "space1/space2/space3", want: []string{"space1", "space2", "space3"}, }, { in: "/space1/space2/space3/", want: []string{"space1", "space2", "space3"}, }, } for _, tt := range tests { got := Segments(tt.in) assert.Equal(t, tt.want, got, "segments aren't matching for %q", tt.in) } } func Test_IsAncesterOf(t *testing.T) { type testCase struct { path string other string want bool } tests := []testCase{ { path: "", other: "", want: true, }, { path: "space1", other: "space1", want: true, }, { path: "space1", other: "space1/space2", want: true, }, { path: "space1", other: "space1/space2/space3", want: true, }, { path: "space1/space2", other: "space1/space2/space3", want: true, }, { path: "/space1/", other: "/space1/space2/", want: true, }, { path: "space1", other: "space2", want: false, }, { path: "space1/space2", other: "space1", want: false, }, { path: "space1/space2", other: "space1/space3", want: false, }, { path: "space1", other: "space10", want: false, }, { path: "space1/in", other: "space1/inner", want: false, }, } for _, tt := range tests { got := IsAncesterOf(tt.path, tt.other) assert.Equal(t, tt.want, got, "IsAncesterOf(%q, %q) isn't matching", tt.path, tt.other) } } func Test_Parent(t *testing.T) { type testCase struct { in string want string } tests := []testCase{ { in: "", want: "", }, { in: "/", want: "", }, { in: "space1", want: "", }, { in: "/space1/", want: "", }, { in: "space1/space2", want: "space1", }, { in: "/space1/space2/", want: "space1", }, { in: "space1/space2/space3", want: "space1/space2", }, { in: "/space1/space2/space3/", want: "space1/space2", }, } for _, tt := range tests { got := Parent(tt.in) assert.Equal(t, tt.want, got, "parent isn't matching for %q", tt.in) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/paths/paths.go
app/paths/paths.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 paths import ( "errors" "strings" "github.com/harness/gitness/types" "github.com/gotidy/ptr" ) var ( ErrPathEmpty = errors.New("path is empty") ) // DisectLeaf splits a path into its parent path and the leaf name // e.g. space1/space2/space3 -> (space1/space2, space3, nil). func DisectLeaf(path string) (string, string, error) { path = strings.Trim(path, types.PathSeparatorAsString) if path == "" { return "", "", ErrPathEmpty } i := strings.LastIndex(path, types.PathSeparatorAsString) if i == -1 { return "", path, nil } return path[:i], path[i+1:], nil } // DisectRoot splits a path into its root space and sub-path // e.g. space1/space2/space3 -> (space1, space2/space3, nil). func DisectRoot(path string) (string, string, error) { path = strings.Trim(path, types.PathSeparatorAsString) if path == "" { return "", "", ErrPathEmpty } i := strings.Index(path, types.PathSeparatorAsString) if i == -1 { return path, "", nil } return path[:i], path[i+1:], nil } /* * Concatenate two paths together (takes care of leading / trailing '/') * e.g. (space1/, /space2/) -> space1/space2 * * NOTE: All leading, trailing, and consecutive '/' will be trimmed to ensure correct paths. */ func Concatenate(paths ...string) string { if len(paths) == 0 { return "" } sb := strings.Builder{} for i := range paths { // remove all leading, trailing, and consecutive '/' var nextRune *rune for _, r := range paths[i] { // skip '/' if we already have '/' as next rune or we don't have anything other than '/' yet if (nextRune == nil || *nextRune == types.PathSeparator) && r == types.PathSeparator { continue } // first time we take a rune we have to make sure we add a separator if needed (guaranteed no '/'). if nextRune == nil && sb.Len() > 0 { sb.WriteString(types.PathSeparatorAsString) } // flush the previous rune before storing the next rune if nextRune != nil { sb.WriteRune(*nextRune) } nextRune = ptr.Of(r) } // flush the final rune if nextRune != nil && *nextRune != types.PathSeparator { sb.WriteRune(*nextRune) } } return sb.String() } // Segments returns all segments of the path // e.g. space1/space2/space3 -> [space1, space2, space3]. func Segments(path string) []string { path = strings.Trim(path, types.PathSeparatorAsString) return strings.Split(path, types.PathSeparatorAsString) } // Depth returns the depth of the path. // e.g. space1/space2 -> 2. func Depth(path string) int { path = strings.Trim(path, types.PathSeparatorAsString) if len(path) == 0 { return 0 } return strings.Count(path, types.PathSeparatorAsString) + 1 } // IsAncesterOf returns true iff 'path' is an ancestor of 'other' or they are the same. // e.g. other = path(/.*). func IsAncesterOf(path string, other string) bool { path = strings.Trim(path, types.PathSeparatorAsString) other = strings.Trim(other, types.PathSeparatorAsString) // add "/" to both to handle space1/inner and space1/in return strings.Contains( other+types.PathSeparatorAsString, path+types.PathSeparatorAsString, ) } // Parent returns the parent path of the provided path. // if the path doesn't have a parent an empty string is returned. func Parent(path string) string { spacePath, _, _ := DisectLeaf(path) return spacePath }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/testing/testing.go
app/testing/testing.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 testing
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/testing/integration/integration.go
app/testing/integration/integration.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 integration
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/server/wire.go
app/server/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 server import ( "github.com/harness/gitness/app/router" "github.com/harness/gitness/http" "github.com/harness/gitness/types" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet(ProvideServer) // ProvideServer provides a server instance. func ProvideServer(config *types.Config, router *router.Router) *Server { return &Server{ http.NewServer( http.Config{ Host: config.HTTP.Host, Port: config.HTTP.Port, Acme: config.Acme.Enabled, AcmeHost: config.Acme.Host, }, router, ), } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/server/server_test.go
app/server/server_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 server
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/server/server.go
app/server/server.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 server implements an http server. package server import ( "github.com/harness/gitness/http" ) // Server is the http server for Harness. type Server struct { *http.Server }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/config/url.go
app/config/url.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 config const ( APIURL = "/api/v1" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/git.go
app/router/git.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 ( "fmt" "net/http" "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/repo" handlerlfs "github.com/harness/gitness/app/api/handler/lfs" handlerrepo "github.com/harness/gitness/app/api/handler/repo" middlewareauthn "github.com/harness/gitness/app/api/middleware/authn" middlewareauthz "github.com/harness/gitness/app/api/middleware/authz" "github.com/harness/gitness/app/api/middleware/encode" "github.com/harness/gitness/app/api/middleware/goget" "github.com/harness/gitness/app/api/middleware/logging" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/services/usage" "github.com/harness/gitness/app/url" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/rs/zerolog/hlog" ) // NewGitHandler returns a new GitHandler. func NewGitHandler( config *types.Config, urlProvider url.Provider, authenticator authn.Authenticator, repoCtrl *repo.Controller, usageSender usage.Sender, lfsCtrl *lfs.Controller, ) http.Handler { // maxRepoDepth depends on config maxRepoDepth := check.MaxRepoPathDepth if !config.NestedSpacesEnabled { maxRepoDepth = 2 } // Use go-chi router for inner routing. r := chi.NewRouter() // Apply common api middleware. r.Use(middleware.NoCache) r.Use(middleware.Recoverer) // configure logging middleware. r.Use(logging.URLHandler("http.url")) r.Use(hlog.MethodHandler("http.method")) r.Use(logging.HLogRequestIDHandler()) r.Use(logging.HLogAccessLogHandler()) // for now always attempt auth - enforced per operation. r.Use(middlewareauthn.Attempt(authenticator)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRepoRef), func(r chi.Router) { r.Use(goget.Middleware(maxRepoDepth, repoCtrl, urlProvider)) // routes that aren't coming from git r.Group(func(r chi.Router) { // redirect to repo (meant for UI, in case user navigates to clone url in browser) r.Get("/", handlerrepo.HandleGitRedirect(urlProvider)) }) // routes that are coming from git (where we block the usage of session tokens) r.Group(func(r chi.Router) { r.Use(middlewareauthz.BlockSessionToken) r.Use(usage.Middleware(usageSender)) // smart protocol r.Post("/git-upload-pack", handlerrepo.HandleGitServicePack( enum.GitServiceTypeUploadPack, repoCtrl, urlProvider)) r.Post("/git-receive-pack", handlerrepo.HandleGitServicePack( enum.GitServiceTypeReceivePack, repoCtrl, urlProvider)) r.Get("/info/refs", handlerrepo.HandleGitInfoRefs(repoCtrl, urlProvider)) // dumb protocol r.Get("/HEAD", stubGitHandler()) r.Get("/objects/info/alternates", stubGitHandler()) r.Get("/objects/info/http-alternates", stubGitHandler()) r.Get("/objects/info/packs", stubGitHandler()) r.Get("/objects/info/{file:[^/]*}", stubGitHandler()) r.Get("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", stubGitHandler()) r.Get("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", stubGitHandler()) r.Get("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", stubGitHandler()) // Git LFS API GitLFSHandler(r, lfsCtrl, urlProvider) }) }) // wrap router in git path encoder. return encode.GitPathBefore(r) } func stubGitHandler() http.HandlerFunc { return func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("Seems like an asteroid destroyed the ancient git protocol")) w.WriteHeader(http.StatusBadGateway) } } func GitLFSHandler(r chi.Router, lfsCtrl *lfs.Controller, urlProvider url.Provider) { r.Route("/info/lfs", func(r chi.Router) { r.Route("/objects", func(r chi.Router) { r.Post("/batch", handlerlfs.HandleLFSTransfer(lfsCtrl, urlProvider)) // direct upload and download handlers for lfs objects r.Put("/", handlerlfs.HandleLFSUpload(lfsCtrl, urlProvider)) r.Get("/", handlerlfs.HandleLFSDownload(lfsCtrl, urlProvider)) }) }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/wire.go
app/router/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 router import ( "context" "strings" "github.com/harness/gitness/app/api/controller/check" "github.com/harness/gitness/app/api/controller/connector" "github.com/harness/gitness/app/api/controller/execution" "github.com/harness/gitness/app/api/controller/githook" "github.com/harness/gitness/app/api/controller/gitspace" "github.com/harness/gitness/app/api/controller/infraprovider" "github.com/harness/gitness/app/api/controller/keywordsearch" "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/logs" "github.com/harness/gitness/app/api/controller/migrate" "github.com/harness/gitness/app/api/controller/pipeline" "github.com/harness/gitness/app/api/controller/plugin" "github.com/harness/gitness/app/api/controller/principal" "github.com/harness/gitness/app/api/controller/pullreq" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/controller/reposettings" "github.com/harness/gitness/app/api/controller/secret" "github.com/harness/gitness/app/api/controller/serviceaccount" "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/api/controller/system" "github.com/harness/gitness/app/api/controller/template" "github.com/harness/gitness/app/api/controller/trigger" "github.com/harness/gitness/app/api/controller/upload" "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/api/controller/usergroup" "github.com/harness/gitness/app/api/controller/webhook" "github.com/harness/gitness/app/api/openapi" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/services/usage" "github.com/harness/gitness/app/url" "github.com/harness/gitness/git" "github.com/harness/gitness/registry/app/api" "github.com/harness/gitness/registry/app/api/router" "github.com/harness/gitness/types" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideRouter, api.WireSet, ) func GetGitRoutingHost(ctx context.Context, urlProvider url.Provider) string { // use url provider as it has the latest data. gitHostname := urlProvider.GetGITHostname(ctx) apiHostname := urlProvider.GetAPIHostname(ctx) // only use host name to identify git traffic if it differs from api hostname. // TODO: Can we make this even more flexible - aka use the full base urls to route traffic? gitRoutingHost := "" if !strings.EqualFold(gitHostname, apiHostname) { gitRoutingHost = gitHostname } return gitRoutingHost } // ProvideRouter provides ordered list of routers. func ProvideRouter( appCtx context.Context, config *types.Config, authenticator authn.Authenticator, repoCtrl *repo.Controller, repoSettingsCtrl *reposettings.Controller, executionCtrl *execution.Controller, logCtrl *logs.Controller, spaceCtrl *space.Controller, pipelineCtrl *pipeline.Controller, secretCtrl *secret.Controller, triggerCtrl *trigger.Controller, connectorCtrl *connector.Controller, templateCtrl *template.Controller, pluginCtrl *plugin.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *githook.Controller, git git.Interface, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, userGroupCtrl *usergroup.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, blobCtrl *upload.Controller, searchCtrl *keywordsearch.Controller, infraProviderCtrl *infraprovider.Controller, gitspaceCtrl *gitspace.Controller, migrateCtrl *migrate.Controller, urlProvider url.Provider, openapi openapi.Service, registryRouter router.AppRouter, usageSender usage.Sender, lfsCtrl *lfs.Controller, ) *Router { routers := make([]Interface, 4) gitRoutingHost := GetGitRoutingHost(appCtx, urlProvider) gitHandler := NewGitHandler( config, urlProvider, authenticator, repoCtrl, usageSender, lfsCtrl, ) routers[0] = NewGitRouter(gitHandler, gitRoutingHost) routers[1] = router.NewRegistryRouter(registryRouter) apiHandler := NewAPIHandler( appCtx, config, authenticator, repoCtrl, repoSettingsCtrl, executionCtrl, logCtrl, spaceCtrl, pipelineCtrl, secretCtrl, triggerCtrl, connectorCtrl, templateCtrl, pluginCtrl, pullreqCtrl, webhookCtrl, githookCtrl, git, saCtrl, userCtrl, principalCtrl, userGroupCtrl, checkCtrl, sysCtrl, blobCtrl, searchCtrl, infraProviderCtrl, migrateCtrl, gitspaceCtrl, usageSender) routers[2] = NewAPIRouter(apiHandler) sec := NewSecure(config) webHandler := NewWebHandler( authenticator, openapi, sec, config.PublicResourceCreationEnabled, config.Development.UISourceOverride, ) routers[3] = NewWebRouter(webHandler) return NewRouter(routers) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/logging.go
app/router/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 router import ( "github.com/harness/gitness/logging" "github.com/rs/zerolog" ) // WithLoggingRouter can be used to annotate logs with the handler info. func WithLoggingRouter(handler string) logging.Option { return func(c zerolog.Context) zerolog.Context { return c.Str("http.router", handler) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/api.go
app/router/api.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 ( "context" "fmt" "net/http" "github.com/harness/gitness/app/api/controller/check" "github.com/harness/gitness/app/api/controller/connector" "github.com/harness/gitness/app/api/controller/execution" controllergithook "github.com/harness/gitness/app/api/controller/githook" "github.com/harness/gitness/app/api/controller/gitspace" "github.com/harness/gitness/app/api/controller/infraprovider" "github.com/harness/gitness/app/api/controller/keywordsearch" "github.com/harness/gitness/app/api/controller/logs" "github.com/harness/gitness/app/api/controller/migrate" "github.com/harness/gitness/app/api/controller/pipeline" "github.com/harness/gitness/app/api/controller/plugin" "github.com/harness/gitness/app/api/controller/principal" "github.com/harness/gitness/app/api/controller/pullreq" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/controller/reposettings" "github.com/harness/gitness/app/api/controller/secret" "github.com/harness/gitness/app/api/controller/serviceaccount" "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/api/controller/system" "github.com/harness/gitness/app/api/controller/template" "github.com/harness/gitness/app/api/controller/trigger" "github.com/harness/gitness/app/api/controller/upload" "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/api/controller/usergroup" "github.com/harness/gitness/app/api/controller/webhook" "github.com/harness/gitness/app/api/handler/account" handlercheck "github.com/harness/gitness/app/api/handler/check" handlerconnector "github.com/harness/gitness/app/api/handler/connector" handlerexecution "github.com/harness/gitness/app/api/handler/execution" handlergithook "github.com/harness/gitness/app/api/handler/githook" handlergitspace "github.com/harness/gitness/app/api/handler/gitspace" handlerinfraProvider "github.com/harness/gitness/app/api/handler/infraprovider" handlerkeywordsearch "github.com/harness/gitness/app/api/handler/keywordsearch" handlerlogs "github.com/harness/gitness/app/api/handler/logs" handlermigrate "github.com/harness/gitness/app/api/handler/migrate" handlerpipeline "github.com/harness/gitness/app/api/handler/pipeline" handlerplugin "github.com/harness/gitness/app/api/handler/plugin" handlerprincipal "github.com/harness/gitness/app/api/handler/principal" handlerpullreq "github.com/harness/gitness/app/api/handler/pullreq" handlerrepo "github.com/harness/gitness/app/api/handler/repo" handlerreposettings "github.com/harness/gitness/app/api/handler/reposettings" "github.com/harness/gitness/app/api/handler/resource" handlersecret "github.com/harness/gitness/app/api/handler/secret" handlerserviceaccount "github.com/harness/gitness/app/api/handler/serviceaccount" handlerspace "github.com/harness/gitness/app/api/handler/space" handlersystem "github.com/harness/gitness/app/api/handler/system" handlertemplate "github.com/harness/gitness/app/api/handler/template" handlertrigger "github.com/harness/gitness/app/api/handler/trigger" handlerupload "github.com/harness/gitness/app/api/handler/upload" handleruser "github.com/harness/gitness/app/api/handler/user" handlerUserGroup "github.com/harness/gitness/app/api/handler/usergroup" "github.com/harness/gitness/app/api/handler/users" handlerwebhook "github.com/harness/gitness/app/api/handler/webhook" "github.com/harness/gitness/app/api/middleware/address" middlewareauthn "github.com/harness/gitness/app/api/middleware/authn" "github.com/harness/gitness/app/api/middleware/encode" "github.com/harness/gitness/app/api/middleware/logging" "github.com/harness/gitness/app/api/middleware/nocache" middlewareprincipal "github.com/harness/gitness/app/api/middleware/principal" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/githook" "github.com/harness/gitness/app/services/usage" "github.com/harness/gitness/audit" "github.com/harness/gitness/git" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" "github.com/rs/zerolog/hlog" ) var ( // terminatedPathPrefixesAPI is the list of prefixes that will require resolving terminated paths. terminatedPathPrefixesAPI = []string{"/v1/spaces/", "/v1/repos/", "/v1/secrets/", "/v1/connectors", "/v1/templates/step", "/v1/templates/stage", "/v1/gitspaces", "/v1/infraproviders", "/v1/migrate/repos", "/v1/pipelines"} ) // NewAPIHandler returns a new APIHandler. func NewAPIHandler( appCtx context.Context, config *types.Config, authenticator authn.Authenticator, repoCtrl *repo.Controller, repoSettingsCtrl *reposettings.Controller, executionCtrl *execution.Controller, logCtrl *logs.Controller, spaceCtrl *space.Controller, pipelineCtrl *pipeline.Controller, secretCtrl *secret.Controller, triggerCtrl *trigger.Controller, connectorCtrl *connector.Controller, templateCtrl *template.Controller, pluginCtrl *plugin.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, git git.Interface, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, userGroupCtrl *usergroup.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, uploadCtrl *upload.Controller, searchCtrl *keywordsearch.Controller, infraProviderCtrl *infraprovider.Controller, migrateCtrl *migrate.Controller, gitspaceCtrl *gitspace.Controller, usageSender usage.Sender, ) http.Handler { // Use go-chi router for inner routing. r := chi.NewRouter() // Apply common api middleware. r.Use(nocache.NoCache) r.Use(middleware.Recoverer) // configure logging middleware. r.Use(logging.URLHandler("http.url")) r.Use(hlog.MethodHandler("http.method")) r.Use(logging.HLogRequestIDHandler()) r.Use(logging.HLogAccessLogHandler()) r.Use(address.Handler("", "")) // configure cors middleware r.Use(corsHandler(config)) r.Use(audit.Middleware()) r.Route("/v1", func(r chi.Router) { // special methods that don't require authentication setupAccountWithoutAuth(r, userCtrl, sysCtrl, config) setupSystem(r, config, sysCtrl) setupResources(r) r.Group(func(r chi.Router) { r.Use(middlewareauthn.Attempt(authenticator)) setupRoutesV1WithAuth(r, appCtx, config, repoCtrl, repoSettingsCtrl, executionCtrl, triggerCtrl, logCtrl, pipelineCtrl, connectorCtrl, templateCtrl, pluginCtrl, secretCtrl, spaceCtrl, pullreqCtrl, webhookCtrl, githookCtrl, git, saCtrl, userCtrl, principalCtrl, userGroupCtrl, checkCtrl, uploadCtrl, searchCtrl, gitspaceCtrl, infraProviderCtrl, migrateCtrl, usageSender) }) }) // wrap router in terminatedPath encoder. return encode.TerminatedPathBefore(terminatedPathPrefixesAPI, r) } func corsHandler(config *types.Config) func(http.Handler) http.Handler { return cors.New( cors.Options{ AllowedOrigins: config.Cors.AllowedOrigins, AllowedMethods: config.Cors.AllowedMethods, AllowedHeaders: config.Cors.AllowedHeaders, ExposedHeaders: config.Cors.ExposedHeaders, AllowCredentials: config.Cors.AllowCredentials, MaxAge: config.Cors.MaxAge, }, ).Handler } // nolint: revive // it's the app context, it shouldn't be the first argument func setupRoutesV1WithAuth(r chi.Router, appCtx context.Context, config *types.Config, repoCtrl *repo.Controller, repoSettingsCtrl *reposettings.Controller, executionCtrl *execution.Controller, triggerCtrl *trigger.Controller, logCtrl *logs.Controller, pipelineCtrl *pipeline.Controller, connectorCtrl *connector.Controller, templateCtrl *template.Controller, pluginCtrl *plugin.Controller, secretCtrl *secret.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, git git.Interface, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, userGroupCtrl *usergroup.Controller, checkCtrl *check.Controller, uploadCtrl *upload.Controller, searchCtrl *keywordsearch.Controller, gitspaceCtrl *gitspace.Controller, infraProviderCtrl *infraprovider.Controller, migrateCtrl *migrate.Controller, usageSender usage.Sender, ) { setupAccountWithAuth(r, userCtrl, config) setupSpaces(r, appCtx, infraProviderCtrl, spaceCtrl, userGroupCtrl, webhookCtrl, checkCtrl) setupRepos(r, repoCtrl, repoSettingsCtrl, pipelineCtrl, executionCtrl, triggerCtrl, logCtrl, pullreqCtrl, webhookCtrl, checkCtrl, uploadCtrl, usageSender) setupConnectors(r, connectorCtrl) setupTemplates(r, templateCtrl) setupSecrets(r, secretCtrl) setupUser(r, userCtrl) setupServiceAccounts(r, saCtrl) setupPrincipals(r, principalCtrl) setupInternal(r, githookCtrl, git) setupAdmin(r, userCtrl) setupPlugins(r, pluginCtrl) setupKeywordSearch(r, searchCtrl) setupInfraProviders(r, infraProviderCtrl) setupGitspaces(r, gitspaceCtrl) setupMigrate(r, migrateCtrl) } // nolint: revive // it's the app context, it shouldn't be the first argument func setupSpaces( r chi.Router, appCtx context.Context, infraProviderCtrl *infraprovider.Controller, spaceCtrl *space.Controller, userGroupCtrl *usergroup.Controller, webhookCtrl *webhook.Controller, checkCtrl *check.Controller, ) { r.Route("/spaces", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerspace.HandleCreate(spaceCtrl)) r.Post("/import", handlerspace.HandleImport(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamSpaceRef), func(r chi.Router) { // space operations r.Get("/", handlerspace.HandleFind(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdate(spaceCtrl)) r.Delete("/", handlerspace.HandleSoftDelete(spaceCtrl)) r.Post("/restore", handlerspace.HandleRestore(spaceCtrl)) r.Post("/purge", handlerspace.HandlePurge(spaceCtrl)) r.Get("/events", handlerspace.HandleEvents(appCtx, spaceCtrl)) r.Post("/import", handlerspace.HandleImportRepositories(spaceCtrl)) r.Post("/move", handlerspace.HandleMove(spaceCtrl)) r.Get("/spaces", handlerspace.HandleListSpaces(spaceCtrl)) r.Get("/pipelines", handlerspace.HandleListPipelines(spaceCtrl)) r.Get("/executions", handlerspace.HandleListExecutions(spaceCtrl)) r.Get("/repos", handlerspace.HandleListRepos(spaceCtrl)) r.Get("/usergroups", handlerUserGroup.HandleList(userGroupCtrl)) r.Get("/service-accounts", handlerspace.HandleListServiceAccounts(spaceCtrl)) r.Get("/secrets", handlerspace.HandleListSecrets(spaceCtrl)) r.Get("/connectors", handlerspace.HandleListConnectors(spaceCtrl)) r.Get("/templates", handlerspace.HandleListTemplates(spaceCtrl)) r.Get("/gitspaces", handlerspace.HandleListGitspaces(spaceCtrl)) r.Get("/infraproviders", handlerspace.HandleListInfraProviderConfigs(infraProviderCtrl)) r.Post("/export", handlerspace.HandleExport(spaceCtrl)) r.Get("/export-progress", handlerspace.HandleExportProgress(spaceCtrl)) r.Post("/public-access", handlerspace.HandleUpdatePublicAccess(spaceCtrl)) r.Get("/pullreq", handlerspace.HandleListPullReqs(spaceCtrl)) r.Get("/pullreq/count", handlerspace.HandleCountPullReqs(spaceCtrl)) r.Route("/members", func(r chi.Router) { r.Get("/", handlerspace.HandleMembershipList(spaceCtrl)) r.Post("/", handlerspace.HandleMembershipAdd(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamUserUID), func(r chi.Router) { r.Delete("/", handlerspace.HandleMembershipDelete(spaceCtrl)) r.Patch("/", handlerspace.HandleMembershipUpdate(spaceCtrl)) }) }) SetupSpaceLabels(r, spaceCtrl) SetupWebhookSpace(r, webhookCtrl) SetupRulesSpace(r, spaceCtrl) r.Get("/checks/recent", handlercheck.HandleCheckListRecentSpace(checkCtrl)) r.Route("/usage", func(r chi.Router) { r.Get("/metric", handlerspace.HandleUsageMetric(spaceCtrl)) }) }) }) } func SetupSpaceLabels(r chi.Router, spaceCtrl *space.Controller) { r.Route("/labels", func(r chi.Router) { r.Post("/", handlerspace.HandleDefineLabel(spaceCtrl)) r.Get("/", handlerspace.HandleListLabels(spaceCtrl)) r.Put("/", handlerspace.HandleSaveLabel(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamLabelKey), func(r chi.Router) { r.Get("/", handlerspace.HandleFindLabel(spaceCtrl)) r.Delete("/", handlerspace.HandleDeleteLabel(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdateLabel(spaceCtrl)) r.Route("/values", func(r chi.Router) { r.Post("/", handlerspace.HandleDefineLabelValue(spaceCtrl)) r.Get("/", handlerspace.HandleListLabelValues(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamLabelValue), func(r chi.Router) { r.Delete("/", handlerspace.HandleDeleteLabelValue(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdateLabelValue(spaceCtrl)) }) }) }) }) } func SetupWebhookSpace(r chi.Router, webhookCtrl *webhook.Controller) { r.Route("/webhooks", func(r chi.Router) { r.Post("/", handlerwebhook.HandleCreateSpace(webhookCtrl)) r.Get("/", handlerwebhook.HandleListSpace(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookIdentifier), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindSpace(webhookCtrl)) r.Patch("/", handlerwebhook.HandleUpdateSpace(webhookCtrl)) r.Delete("/", handlerwebhook.HandleDeleteSpace(webhookCtrl)) r.Route("/executions", func(r chi.Router) { r.Get("/", handlerwebhook.HandleListExecutionsSpace(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookExecutionID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindExecutionSpace(webhookCtrl)) r.Post("/retrigger", handlerwebhook.HandleRetriggerExecutionSpace(webhookCtrl)) }) }) }) }) } func SetupRulesSpace(r chi.Router, spaceCtrl *space.Controller) { r.Route("/rules", func(r chi.Router) { r.Post("/", handlerspace.HandleRuleCreate(spaceCtrl)) r.Get("/", handlerspace.HandleRuleList(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRuleIdentifier), func(r chi.Router) { r.Patch("/", handlerspace.HandleRuleUpdate(spaceCtrl)) r.Delete("/", handlerspace.HandleRuleDelete(spaceCtrl)) r.Get("/", handlerspace.HandleRuleFind(spaceCtrl)) }) }) } func setupRepos(r chi.Router, repoCtrl *repo.Controller, repoSettingsCtrl *reposettings.Controller, pipelineCtrl *pipeline.Controller, executionCtrl *execution.Controller, triggerCtrl *trigger.Controller, logCtrl *logs.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, checkCtrl *check.Controller, uploadCtrl *upload.Controller, usageSender usage.Sender, ) { r.Route("/repos", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerrepo.HandleCreate(repoCtrl)) r.Post("/import", handlerrepo.HandleImport(repoCtrl)) r.Post("/link", handlerrepo.HandleLinkedCreate(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRepoRef), func(r chi.Router) { // repo level operations r.Get("/", handlerrepo.HandleFind(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdate(repoCtrl)) r.Delete("/", handlerrepo.HandleSoftDelete(repoCtrl)) r.Post("/purge", handlerrepo.HandlePurge(repoCtrl)) r.Post("/restore", handlerrepo.HandleRestore(repoCtrl)) r.Post("/public-access", handlerrepo.HandleUpdatePublicAccess(repoCtrl)) r.Post("/fork", handlerrepo.HandleCreateFork(repoCtrl)) r.Post("/fork-sync", handlerrepo.HandleForkSync(repoCtrl)) r.Post("/linked/sync", handlerrepo.HandleLinkedSync(repoCtrl)) r.Route("/settings", func(r chi.Router) { r.Get("/security", handlerreposettings.HandleSecurityFind(repoSettingsCtrl)) r.Patch("/security", handlerreposettings.HandleSecurityUpdate(repoSettingsCtrl)) r.Get("/general", handlerreposettings.HandleGeneralFind(repoSettingsCtrl)) r.Patch("/general", handlerreposettings.HandleGeneralUpdate(repoSettingsCtrl)) }) r.Get("/summary", handlerrepo.HandleSummary(repoCtrl)) r.Post("/move", handlerrepo.HandleMove(repoCtrl)) r.Get("/service-accounts", handlerrepo.HandleListServiceAccounts(repoCtrl)) r.Get("/import-progress", handlerrepo.HandleImportProgress(repoCtrl)) r.Post("/default-branch", handlerrepo.HandleUpdateDefaultBranch(repoCtrl)) // content operations // NOTE: this allows /content and /content/ to both be valid (without any other tricks.) // We don't expect there to be any other operations in that route (as that could overlap with file names) r.Route("/content", func(r chi.Router) { r.Get("/*", handlerrepo.HandleGetContent(repoCtrl)) }) r.Get("/paths", handlerrepo.HandleListPaths(repoCtrl)) r.Post("/path-details", handlerrepo.HandlePathsDetails(repoCtrl)) r.Route("/blame", func(r chi.Router) { r.Get("/*", handlerrepo.HandleBlame(repoCtrl)) }) r.Route("/raw", func(r chi.Router) { r.With( usage.Middleware(usageSender), ).Get("/*", handlerrepo.HandleRaw(repoCtrl)) }) // commit operations r.Route("/commits", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommits(repoCtrl)) r.Post("/calculate-divergence", handlerrepo.HandleCalculateCommitDivergence(repoCtrl)) r.Post("/", handlerrepo.HandleCommitFiles(repoCtrl)) // per commit operations r.Route(fmt.Sprintf("/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Get("/", handlerrepo.HandleGetCommit(repoCtrl)) r.Get("/diff", handlerrepo.HandleCommitDiff(repoCtrl)) }) }) // branch operations r.Route("/branches", func(r chi.Router) { r.Get("/", handlerrepo.HandleListBranches(repoCtrl)) r.Post("/", handlerrepo.HandleCreateBranch(repoCtrl)) // per branch operations (can't be grouped in single route) r.Get("/*", handlerrepo.HandleGetBranch(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteBranch(repoCtrl)) }) // tags operations r.Route("/tags", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommitTags(repoCtrl)) r.Post("/", handlerrepo.HandleCreateCommitTag(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteCommitTag(repoCtrl)) }) // diffs r.Route("/diff", func(r chi.Router) { r.Get("/*", handlerrepo.HandleDiff(repoCtrl)) r.Post("/*", handlerrepo.HandleDiff(repoCtrl)) }) r.Route("/diff-stats", func(r chi.Router) { r.Get("/*", handlerrepo.HandleDiffStats(repoCtrl)) }) r.Route("/merge-check", func(r chi.Router) { r.Post("/*", handlerrepo.HandleMergeCheck(repoCtrl)) }) r.Post("/rebase", handlerrepo.HandleRebase(repoCtrl)) r.Post("/squash", handlerrepo.HandleSquash(repoCtrl)) r.Get("/codeowners/validate", handlerrepo.HandleCodeOwnersValidate(repoCtrl)) r.With( usage.Middleware(usageSender), ).Get(fmt.Sprintf("/archive/%s", request.PathParamArchiveGitRef), handlerrepo.HandleArchive(repoCtrl)) SetupPullReq(r, pullreqCtrl) SetupWebhookRepo(r, webhookCtrl) setupPipelines(r, repoCtrl, pipelineCtrl, executionCtrl, triggerCtrl, logCtrl) SetupChecks(r, checkCtrl) SetupUploads(r, uploadCtrl) SetupRulesRepo(r, repoCtrl) SetupRepoLabels(r, repoCtrl) }) }) } func SetupRepoLabels(r chi.Router, repoCtrl *repo.Controller) { r.Route("/labels", func(r chi.Router) { r.Post("/", handlerrepo.HandleDefineLabel(repoCtrl)) r.Get("/", handlerrepo.HandleListLabels(repoCtrl)) r.Put("/", handlerrepo.HandleSaveLabel(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamLabelKey), func(r chi.Router) { r.Get("/", handlerrepo.HandleFindLabel(repoCtrl)) r.Delete("/", handlerrepo.HandleDeleteLabel(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdateLabel(repoCtrl)) r.Route("/values", func(r chi.Router) { r.Post("/", handlerrepo.HandleDefineLabelValue(repoCtrl)) r.Get("/", handlerrepo.HandleListLabelValues(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamLabelValue), func(r chi.Router) { r.Delete("/", handlerrepo.HandleDeleteLabelValue(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdateLabelValue(repoCtrl)) }) }) }) }) } func SetupUploads(r chi.Router, uploadCtrl *upload.Controller) { r.Route("/uploads", func(r chi.Router) { r.Post("/", handlerupload.HandleUpload(uploadCtrl)) r.Get("/*", handlerupload.HandleDownoad(uploadCtrl)) }) } func setupPipelines( r chi.Router, repoCtrl *repo.Controller, pipelineCtrl *pipeline.Controller, executionCtrl *execution.Controller, triggerCtrl *trigger.Controller, logCtrl *logs.Controller) { r.Route("/pipelines", func(r chi.Router) { r.Get("/", handlerrepo.HandleListPipelines(repoCtrl)) // Create takes path and parentId via body, not uri r.Post("/", handlerpipeline.HandleCreate(pipelineCtrl)) r.Get("/generate", handlerrepo.HandlePipelineGenerate(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPipelineIdentifier), func(r chi.Router) { r.Get("/", handlerpipeline.HandleFind(pipelineCtrl)) r.Patch("/", handlerpipeline.HandleUpdate(pipelineCtrl)) r.Delete("/", handlerpipeline.HandleDelete(pipelineCtrl)) setupExecutions(r, executionCtrl, logCtrl) setupTriggers(r, triggerCtrl) }) }) } func setupConnectors( r chi.Router, connectorCtrl *connector.Controller, ) { r.Route("/connectors", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerconnector.HandleCreate(connectorCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamConnectorRef), func(r chi.Router) { r.Get("/", handlerconnector.HandleFind(connectorCtrl)) r.Patch("/", handlerconnector.HandleUpdate(connectorCtrl)) r.Delete("/", handlerconnector.HandleDelete(connectorCtrl)) r.Post("/test", handlerconnector.HandleTest(connectorCtrl)) }) }) } func setupTemplates( r chi.Router, templateCtrl *template.Controller, ) { r.Route("/templates", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlertemplate.HandleCreate(templateCtrl)) r.Route(fmt.Sprintf("/{%s}/{%s}", request.PathParamTemplateType, request.PathParamTemplateRef), func(r chi.Router) { r.Get("/", handlertemplate.HandleFind(templateCtrl)) r.Patch("/", handlertemplate.HandleUpdate(templateCtrl)) r.Delete("/", handlertemplate.HandleDelete(templateCtrl)) }) }) } func setupSecrets(r chi.Router, secretCtrl *secret.Controller) { r.Route("/secrets", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlersecret.HandleCreate(secretCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamSecretRef), func(r chi.Router) { r.Get("/", handlersecret.HandleFind(secretCtrl)) r.Patch("/", handlersecret.HandleUpdate(secretCtrl)) r.Delete("/", handlersecret.HandleDelete(secretCtrl)) }) }) } func setupPlugins(r chi.Router, pluginCtrl *plugin.Controller) { r.Route("/plugins", func(r chi.Router) { r.Get("/", handlerplugin.HandleList(pluginCtrl)) }) } func setupExecutions( r chi.Router, executionCtrl *execution.Controller, logCtrl *logs.Controller, ) { r.Route("/executions", func(r chi.Router) { r.Get("/", handlerexecution.HandleList(executionCtrl)) r.Post("/", handlerexecution.HandleCreate(executionCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamExecutionNumber), func(r chi.Router) { r.Get("/", handlerexecution.HandleFind(executionCtrl)) r.Post("/cancel", handlerexecution.HandleCancel(executionCtrl)) r.Delete("/", handlerexecution.HandleDelete(executionCtrl)) r.Get( fmt.Sprintf("/logs/{%s}/{%s}", request.PathParamStageNumber, request.PathParamStepNumber, ), handlerlogs.HandleFind(logCtrl)) // TODO: Decide whether API should be /stream/logs/{}/{} or /logs/{}/{}/stream r.Get( fmt.Sprintf("/logs/{%s}/{%s}/stream", request.PathParamStageNumber, request.PathParamStepNumber, ), handlerlogs.HandleTail(logCtrl)) }) }) } func setupTriggers( r chi.Router, triggerCtrl *trigger.Controller, ) { r.Route("/triggers", func(r chi.Router) { r.Get("/", handlertrigger.HandleList(triggerCtrl)) r.Post("/", handlertrigger.HandleCreate(triggerCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamTriggerIdentifier), func(r chi.Router) { r.Get("/", handlertrigger.HandleFind(triggerCtrl)) r.Patch("/", handlertrigger.HandleUpdate(triggerCtrl)) r.Delete("/", handlertrigger.HandleDelete(triggerCtrl)) }) }) } func setupInternal(r chi.Router, githookCtrl *controllergithook.Controller, git git.Interface) { r.Route("/internal", func(r chi.Router) { SetupGitHooks(r, githookCtrl, git) }) } func SetupGitHooks(r chi.Router, githookCtrl *controllergithook.Controller, git git.Interface) { r.Route("/git-hooks", func(r chi.Router) { r.Post("/"+githook.HTTPRequestPathPreReceive, handlergithook.HandlePreReceive(githookCtrl, git)) r.Post("/"+githook.HTTPRequestPathUpdate, handlergithook.HandleUpdate(githookCtrl, git)) r.Post("/"+githook.HTTPRequestPathPostReceive, handlergithook.HandlePostReceive(githookCtrl, git)) }) } func SetupPullReq(r chi.Router, pullreqCtrl *pullreq.Controller) { r.Route("/pullreq", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCreate(pullreqCtrl)) r.Get("/", handlerpullreq.HandleList(pullreqCtrl)) r.Get( fmt.Sprintf("/{%s}...{%s}", request.PathParamTargetBranch, request.PathParamSourceBranch), handlerpullreq.HandleFindByBranches(pullreqCtrl), ) r.Get("/candidates", handlerpullreq.HandlePRBranchCandidates(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqNumber), func(r chi.Router) { r.Get("/", handlerpullreq.HandleFind(pullreqCtrl)) r.Patch("/", handlerpullreq.HandleUpdate(pullreqCtrl)) r.Post("/state", handlerpullreq.HandleState(pullreqCtrl)) r.Get("/activities", handlerpullreq.HandleListActivities(pullreqCtrl)) r.Route("/comments", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCommentCreate(pullreqCtrl)) r.Post("/apply-suggestions", handlerpullreq.HandleCommentApplySuggestions(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqCommentID), func(r chi.Router) { r.Patch("/", handlerpullreq.HandleCommentUpdate(pullreqCtrl)) r.Delete("/", handlerpullreq.HandleCommentDelete(pullreqCtrl)) r.Put("/status", handlerpullreq.HandleCommentStatus(pullreqCtrl)) }) }) r.Route("/reviewers", func(r chi.Router) { r.Get("/", handlerpullreq.HandleReviewerList(pullreqCtrl)) r.Put("/", handlerpullreq.HandleReviewerAdd(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamReviewerID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleReviewerDelete(pullreqCtrl)) }) r.Route("/usergroups", func(r chi.Router) { r.Put("/", handlerpullreq.HandleUserGroupReviewerAdd(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamUserGroupID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleUserGroupReviewerDelete(pullreqCtrl)) }) }) r.Route("/combined", func(r chi.Router) { r.Get("/", handlerpullreq.HandleReviewerCombinedList(pullreqCtrl)) }) }) r.Route("/reviews", func(r chi.Router) { r.Post("/", handlerpullreq.HandleReviewSubmit(pullreqCtrl)) }) r.Post("/merge", handlerpullreq.HandleMerge(pullreqCtrl)) r.Post("/revert", handlerpullreq.HandleRevert(pullreqCtrl)) r.Get("/commits", handlerpullreq.HandleCommits(pullreqCtrl)) r.Get("/metadata", handlerpullreq.HandleMetadata(pullreqCtrl)) r.Route("/branch", func(r chi.Router) { r.Post("/", handlerpullreq.HandleRestoreBranch(pullreqCtrl)) r.Delete("/", handlerpullreq.HandleDeleteBranch(pullreqCtrl)) }) r.Put("/target-branch", handlerpullreq.HandleChangeTargetBranch(pullreqCtrl)) r.Route("/file-views", func(r chi.Router) { r.Put("/", handlerpullreq.HandleFileViewAdd(pullreqCtrl)) r.Get("/", handlerpullreq.HandleFileViewList(pullreqCtrl)) r.Delete("/*", handlerpullreq.HandleFileViewDelete(pullreqCtrl)) }) r.Get("/codeowners", handlerpullreq.HandleCodeOwner(pullreqCtrl)) r.Get("/diff", handlerpullreq.HandleDiff(pullreqCtrl)) r.Post("/diff", handlerpullreq.HandleDiff(pullreqCtrl)) r.Get("/checks", handlerpullreq.HandleCheckList(pullreqCtrl)) setupPullReqLabels(r, pullreqCtrl) }) }) } func setupPullReqLabels(r chi.Router, pullreqCtrl *pullreq.Controller) { r.Route("/labels", func(r chi.Router) { r.Put("/", handlerpullreq.HandleAssignLabel(pullreqCtrl)) r.Get("/", handlerpullreq.HandleListLabels(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamLabelID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleUnassignLabel(pullreqCtrl)) }) }) } func SetupWebhookRepo(r chi.Router, webhookCtrl *webhook.Controller) { r.Route("/webhooks", func(r chi.Router) { r.Post("/", handlerwebhook.HandleCreateRepo(webhookCtrl)) r.Get("/", handlerwebhook.HandleListRepo(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookIdentifier), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindRepo(webhookCtrl)) r.Patch("/", handlerwebhook.HandleUpdateRepo(webhookCtrl)) r.Delete("/", handlerwebhook.HandleDeleteRepo(webhookCtrl)) r.Route("/executions", func(r chi.Router) { r.Get("/", handlerwebhook.HandleListExecutionsRepo(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookExecutionID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindExecutionRepo(webhookCtrl)) r.Post("/retrigger", handlerwebhook.HandleRetriggerExecutionRepo(webhookCtrl)) }) }) }) }) } func SetupChecks(r chi.Router, checkCtrl *check.Controller) { r.Route("/checks", func(r chi.Router) { r.Get("/recent", handlercheck.HandleCheckListRecent(checkCtrl)) r.Route(fmt.Sprintf("/commits/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Put("/", handlercheck.HandleCheckReport(checkCtrl)) r.Get("/", handlercheck.HandleCheckList(checkCtrl)) }) }) } func SetupRulesRepo(r chi.Router, repoCtrl *repo.Controller) { r.Route("/rules", func(r chi.Router) { r.Post("/", handlerrepo.HandleRuleCreate(repoCtrl)) r.Get("/", handlerrepo.HandleRuleList(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRuleIdentifier), func(r chi.Router) { r.Patch("/", handlerrepo.HandleRuleUpdate(repoCtrl)) r.Delete("/", handlerrepo.HandleRuleDelete(repoCtrl)) r.Get("/", handlerrepo.HandleRuleFind(repoCtrl)) }) }) } func setupUser(r chi.Router, userCtrl *user.Controller) { r.Route("/user", func(r chi.Router) { // enforce principal authenticated and it's a user r.Use(middlewareprincipal.RestrictTo(enum.PrincipalTypeUser)) r.Get("/", handleruser.HandleFind(userCtrl)) r.Patch("/", handleruser.HandleUpdate(userCtrl)) r.Get("/memberships", handleruser.HandleMembershipSpaces(userCtrl)) // PAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypePAT)) r.Post("/", handleruser.HandleCreateAccessToken(userCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenIdentifier), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypePAT)) }) }) // SESSION TOKENS r.Route("/sessions", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypeSession)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenIdentifier), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypeSession)) }) }) // Private keys r.Route("/keys", func(r chi.Router) { r.Get("/", handleruser.HandleListPublicKeys(userCtrl)) r.Post("/", handleruser.HandleCreatePublicKey(userCtrl)) r.Delete(fmt.Sprintf("/{%s}", request.PathParamPublicKeyIdentifier), handleruser.HandleDeletePublicKey(userCtrl)) r.Patch(fmt.Sprintf("/{%s}", request.PathParamPublicKeyIdentifier), handleruser.HandleUpdatePublicKey(userCtrl)) }) // Favorites r.Route("/favorite", func(r chi.Router) { r.Post("/", handleruser.HandleCreateFavorite(userCtrl))
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
true
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/router.go
app/router/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/app/request" "github.com/harness/gitness/logging" "github.com/go-logr/logr" "github.com/go-logr/zerologr" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) type Router struct { routers []Interface } // NewRouter returns a new http.Handler that routes traffic // to the appropriate handlers. func NewRouter( routers []Interface, ) *Router { return &Router{ routers: routers, } } func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { // setup logger for request log := log.Logger.With().Logger() ctx := log.WithContext(req.Context()) // add logger to logr interface for usage in 3rd party libs ctx = logr.NewContext(ctx, zerologr.New(&log)) req = req.WithContext(ctx) log.UpdateContext(func(c zerolog.Context) zerolog.Context { return c. Str("http.original_url", req.URL.String()) }) for _, router := range r.routers { if ok := router.IsEligibleTraffic(req); ok { req = req.WithContext(logging.NewContext(req.Context(), WithLoggingRouter(router.Name()))) router.Handle(w, req) return } } render.BadRequestf(ctx, w, "No eligible router found") } // StripPrefix removes the prefix from the request path (or noop if it's not there). func StripPrefix(prefix string, req *http.Request) error { if !strings.HasPrefix(req.URL.Path, prefix) { return nil } return request.ReplacePrefix(req, prefix, "") }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/interface.go
app/router/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 router import ( "net/http" ) type Interface interface { Handle(w http.ResponseWriter, req *http.Request) IsEligibleTraffic(req *http.Request) bool Name() string }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/router/git_router.go
app/router/git_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/rs/zerolog/log" ) const GitMount = "/git" type GitRouter struct { handler http.Handler // gitHost describes the optional host via which git traffic is identified. // Note: always stored as lowercase. gitHost string } func NewGitRouter(handler http.Handler, gitHost string) *GitRouter { return &GitRouter{handler: handler, gitHost: gitHost} } func (r *GitRouter) Handle(w http.ResponseWriter, req *http.Request) { // remove matched prefix to simplify API handlers (only if it's there) if err := StripPrefix(GitMount, req); err != nil { log.Ctx(req.Context()).Err(err).Msgf("Failed striping of prefix for git request.") render.InternalError(req.Context(), w) return } r.handler.ServeHTTP(w, req) } func (r *GitRouter) IsEligibleTraffic(req *http.Request) bool { // All Git originating traffic starts with "/space1/space2/repo.git". // git traffic is always reachable via the git mounting path. p := req.URL.Path if strings.HasPrefix(p, GitMount+"/") { return true } // otherwise check if the request came in via the configured git host (if enabled) if len(r.gitHost) > 0 { // cut (optional) port off the host h, _, _ := strings.Cut(req.Host, ":") if strings.EqualFold(r.gitHost, h) { return true } } // otherwise we don't treat it as git traffic return false } func (r *GitRouter) Name() string { return "git" }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false