feat: [CODE-3148]: refactor refcache (#3390)

* linter issues fix
* reintroduce repofinder to aiagent
* Merge remote-tracking branch 'origin/main' into mg/cache/space-and-repo-finder
* removed refcache deps from aiagent
* pr comments
* fix linter issues
* refactor refcache
This commit is contained in:
Marko Gaćeša 2025-02-12 12:42:12 +00:00 committed by Harness
parent 890fe494de
commit a906259562
188 changed files with 1002 additions and 530 deletions

View File

@ -35,7 +35,7 @@ func CheckRepo(
ctx context.Context, ctx context.Context,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
permission enum.Permission, permission enum.Permission,
) error { ) error {
parentSpace, name, err := paths.DisectLeaf(repo.Path) parentSpace, name, err := paths.DisectLeaf(repo.Path)
@ -56,7 +56,7 @@ func IsRepoOwner(
ctx context.Context, ctx context.Context,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
) (bool, error) { ) (bool, error) {
// for now we use repoedit as permission to verify if someone is a SpaceOwner and hence a RepoOwner. // for now we use repoedit as permission to verify if someone is a SpaceOwner and hence a RepoOwner.
err := CheckRepo(ctx, authorizer, session, repo, enum.PermissionRepoEdit) err := CheckRepo(ctx, authorizer, session, repo, enum.PermissionRepoEdit)
@ -71,7 +71,7 @@ func IsRepoOwner(
func CheckRepoState( func CheckRepoState(
_ context.Context, _ context.Context,
_ *auth.Session, _ *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
reqPermission enum.Permission, reqPermission enum.Permission,
additionalAllowedRepoStates ...enum.RepoState, additionalAllowedRepoStates ...enum.RepoState,
) error { ) error {

View File

@ -32,7 +32,7 @@ func CheckSpace(
ctx context.Context, ctx context.Context,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
space *types.Space, space *types.SpaceCore,
permission enum.Permission, permission enum.Permission,
) error { ) error {
parentSpace, name, err := paths.DisectLeaf(space.Path) parentSpace, name, err := paths.DisectLeaf(space.Path)
@ -56,7 +56,7 @@ func CheckSpaceScope(
ctx context.Context, ctx context.Context,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
space *types.Space, space *types.SpaceCore,
resourceType enum.ResourceType, resourceType enum.ResourceType,
permission enum.Permission, permission enum.Permission,
) error { ) error {

View File

@ -90,7 +90,7 @@ type Files struct {
func (c *Controller) commit(ctx context.Context, func (c *Controller) commit(ctx context.Context,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
payload *CommitPayload) (types.CommitFilesResponse, error) { payload *CommitPayload) (types.CommitFilesResponse, error) {
files := payload.Files files := payload.Files
actions := make([]git.CommitFileAction, len(files)) actions := make([]git.CommitFileAction, len(files))

View File

@ -37,7 +37,7 @@ type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
spaceStore store.SpaceStore spaceStore store.SpaceStore
checkStore store.CheckStore checkStore store.CheckStore
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
repoFinder refcache.RepoFinder repoFinder refcache.RepoFinder
git git.Interface git git.Interface
sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error
@ -49,7 +49,7 @@ func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
checkStore store.CheckStore, checkStore store.CheckStore,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
git git.Interface, git git.Interface,
sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error, sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error,
@ -60,7 +60,7 @@ func NewController(
authorizer: authorizer, authorizer: authorizer,
spaceStore: spaceStore, spaceStore: spaceStore,
checkStore: checkStore, checkStore: checkStore,
spaceCache: spaceCache, spaceFinder: spaceFinder,
repoFinder: repoFinder, repoFinder: repoFinder,
git: git, git: git,
sanitizers: sanitizers, sanitizers: sanitizers,
@ -75,7 +75,7 @@ func (c *Controller) getRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
@ -101,6 +101,6 @@ func (c *Controller) getSpaceCheckAccess(
session *auth.Session, session *auth.Session,
spaceRef string, spaceRef string,
permission enum.Permission, permission enum.Permission,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
return space.GetSpaceCheckAuth(ctx, c.spaceCache, c.authorizer, session, spaceRef, permission) return space.GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission)
} }

View File

@ -38,7 +38,7 @@ func ProvideController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
checkStore store.CheckStore, checkStore store.CheckStore,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
git git.Interface, git git.Interface,
sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error, sanitizers map[enum.CheckPayloadKind]func(in *ReportInput, s *auth.Session) error,
@ -49,7 +49,7 @@ func ProvideController(
authorizer, authorizer,
spaceStore, spaceStore,
checkStore, checkStore,
spaceCache, spaceFinder,
repoFinder, repoFinder,
git, git,
sanitizers, sanitizers,

View File

@ -24,7 +24,7 @@ import (
type Controller struct { type Controller struct {
connectorStore store.ConnectorStore connectorStore store.ConnectorStore
connectorService *connector.Service connectorService *connector.Service
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
authorizer authz.Authorizer authorizer authz.Authorizer
} }
@ -32,12 +32,12 @@ func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
connectorStore store.ConnectorStore, connectorStore store.ConnectorStore,
connectorService *connector.Service, connectorService *connector.Service,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
connectorStore: connectorStore, connectorStore: connectorStore,
connectorService: connectorService, connectorService: connectorService,
spaceCache: spaceCache, spaceFinder: spaceFinder,
authorizer: authorizer, authorizer: authorizer,
} }
} }

View File

@ -52,7 +52,7 @@ func (c *Controller) Create(
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
parentSpace, err := c.spaceCache.Get(ctx, in.SpaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }

View File

@ -29,7 +29,7 @@ func (c *Controller) Delete(
spaceRef string, spaceRef string,
identifier string, identifier string,
) error { ) error {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return fmt.Errorf("failed to find space: %w", err) return fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -30,7 +30,7 @@ func (c *Controller) Find(
spaceRef string, spaceRef string,
identifier string, identifier string,
) (*types.Connector, error) { ) (*types.Connector, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -33,7 +33,7 @@ func (c *Controller) Test(
spaceRef string, spaceRef string,
identifier string, identifier string,
) (types.ConnectorTestResponse, error) { ) (types.ConnectorTestResponse, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return types.ConnectorTestResponse{}, fmt.Errorf("failed to find space: %w", err) return types.ConnectorTestResponse{}, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -45,7 +45,7 @@ func (c *Controller) Update(
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -32,7 +32,7 @@ func ProvideController(
connectorStore store.ConnectorStore, connectorStore store.ConnectorStore,
connectorService *connector.Service, connectorService *connector.Service,
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return NewController(authorizer, connectorStore, connectorService, spaceCache) return NewController(authorizer, connectorStore, connectorService, spaceFinder)
} }

View File

@ -81,7 +81,7 @@ func (c *Controller) getRepoCheckPipelineAccess(
pipelineIdentifier string, pipelineIdentifier string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef) repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo by ref: %w", err) return nil, fmt.Errorf("failed to find repo by ref: %w", err)

View File

@ -25,6 +25,7 @@ import (
eventsgit "github.com/harness/gitness/app/events/git" eventsgit "github.com/harness/gitness/app/events/git"
eventsrepo "github.com/harness/gitness/app/events/repo" eventsrepo "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/sse"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
@ -42,6 +43,7 @@ type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
principalStore store.PrincipalStore principalStore store.PrincipalStore
repoStore store.RepoStore repoStore store.RepoStore
repoFinder refcache.RepoFinder
gitReporter *eventsgit.Reporter gitReporter *eventsgit.Reporter
repoReporter *eventsrepo.Reporter repoReporter *eventsrepo.Reporter
git git.Interface git git.Interface
@ -60,6 +62,7 @@ func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
principalStore store.PrincipalStore, principalStore store.PrincipalStore,
repoStore store.RepoStore, repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
gitReporter *eventsgit.Reporter, gitReporter *eventsgit.Reporter,
repoReporter *eventsrepo.Reporter, repoReporter *eventsrepo.Reporter,
git git.Interface, git git.Interface,
@ -77,6 +80,7 @@ func NewController(
authorizer: authorizer, authorizer: authorizer,
principalStore: principalStore, principalStore: principalStore,
repoStore: repoStore, repoStore: repoStore,
repoFinder: repoFinder,
gitReporter: gitReporter, gitReporter: gitReporter,
repoReporter: repoReporter, repoReporter: repoReporter,
git: git, git: git,
@ -97,12 +101,12 @@ func (c *Controller) getRepoCheckAccess(
_ *auth.Session, _ *auth.Session,
repoID int64, repoID int64,
_ enum.Permission, _ enum.Permission,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoID < 1 { if repoID < 1 {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
repo, err := c.repoStore.Find(ctx, repoID) repo, err := c.repoFinder.FindByID(ctx, repoID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo with id %d: %w", repoID, err) return nil, fmt.Errorf("failed to find repo with id %d: %w", repoID, err)
} }
@ -120,7 +124,7 @@ func (c *Controller) getRepoCheckAccess(
func GetBaseSHAForScanningChanges( func GetBaseSHAForScanningChanges(
ctx context.Context, ctx context.Context,
rgit RestrictedGIT, rgit RestrictedGIT,
repo *types.Repository, repo *types.RepositoryCore,
env hook.Environment, env hook.Environment,
refUpdates []hook.ReferenceUpdate, refUpdates []hook.ReferenceUpdate,
findBaseFor hook.ReferenceUpdate, findBaseFor hook.ReferenceUpdate,

View File

@ -27,7 +27,7 @@ type PreReceiveExtender interface {
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookPreReceiveInput, types.GithookPreReceiveInput,
*hook.Output, *hook.Output,
) error ) error
@ -38,7 +38,7 @@ type UpdateExtender interface {
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookUpdateInput, types.GithookUpdateInput,
*hook.Output, *hook.Output,
) error ) error
@ -49,7 +49,7 @@ type PostReceiveExtender interface {
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookPostReceiveInput, types.GithookPostReceiveInput,
*hook.Output, *hook.Output,
) error ) error
@ -66,7 +66,7 @@ func (NoOpPreReceiveExtender) Extend(
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookPreReceiveInput, types.GithookPreReceiveInput,
*hook.Output, *hook.Output,
) error { ) error {
@ -84,7 +84,7 @@ func (NoOpUpdateExtender) Extend(
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookUpdateInput, types.GithookUpdateInput,
*hook.Output, *hook.Output,
) error { ) error {
@ -102,7 +102,7 @@ func (NoOpPostReceiveExtender) Extend(
context.Context, context.Context,
RestrictedGIT, RestrictedGIT,
*auth.Session, *auth.Session,
*types.Repository, *types.RepositoryCore,
types.GithookPostReceiveInput, types.GithookPostReceiveInput,
*hook.Output, *hook.Output,
) error { ) error {

View File

@ -52,10 +52,16 @@ func (c *Controller) PostReceive(
session *auth.Session, session *auth.Session,
in types.GithookPostReceiveInput, in types.GithookPostReceiveInput,
) (hook.Output, error) { ) (hook.Output, error) {
repo, err := c.getRepoCheckAccess(ctx, session, in.RepoID, enum.PermissionRepoPush) repoCore, err := c.getRepoCheckAccess(ctx, session, in.RepoID, enum.PermissionRepoPush)
if err != nil { if err != nil {
return hook.Output{}, err return hook.Output{}, err
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return hook.Output{}, err
}
// create output object and have following messages fill its messages // create output object and have following messages fill its messages
out := hook.Output{} out := hook.Output{}
@ -74,7 +80,7 @@ func (c *Controller) PostReceive(
// handle branch updates related to PRs - best effort // handle branch updates related to PRs - best effort
c.handlePRMessaging(ctx, repo, in.PostReceiveInput, &out) c.handlePRMessaging(ctx, repo, in.PostReceiveInput, &out)
err = c.postReceiveExtender.Extend(ctx, rgit, session, repo, in, &out) err = c.postReceiveExtender.Extend(ctx, rgit, session, repo.Core(), in, &out)
if err != nil { if err != nil {
return hook.Output{}, fmt.Errorf("failed to extend post-receive hook: %w", err) return hook.Output{}, fmt.Errorf("failed to extend post-receive hook: %w", err)
} }
@ -333,6 +339,8 @@ func (c *Controller) handleEmptyRepoPush(
return return
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
if repo.DefaultBranch != oldName { if repo.DefaultBranch != oldName {
c.repoReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{ c.repoReporter.DefaultBranchUpdated(ctx, &repoevents.DefaultBranchUpdatedPayload{
RepoID: repo.ID, RepoID: repo.ID,
@ -366,5 +374,7 @@ func (c *Controller) updateLastGITPushTime(
return return
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
*repo = *newRepo *repo = *newRepo
} }

View File

@ -149,7 +149,7 @@ func (c *Controller) blockPullReqRefUpdate(refUpdates changedRefs, state enum.Re
func (c *Controller) checkProtectionRules( func (c *Controller) checkProtectionRules(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
refUpdates changedRefs, refUpdates changedRefs,
output *hook.Output, output *hook.Output,
) error { ) error {

View File

@ -29,7 +29,7 @@ import (
func (c *Controller) checkFileSizeLimit( func (c *Controller) checkFileSizeLimit(
ctx context.Context, ctx context.Context,
rgit RestrictedGIT, rgit RestrictedGIT,
repo *types.Repository, repo *types.RepositoryCore,
in types.GithookPreReceiveInput, in types.GithookPreReceiveInput,
output *hook.Output, output *hook.Output,
) error { ) error {

View File

@ -37,7 +37,7 @@ type secretFinding struct {
func (c *Controller) scanSecrets( func (c *Controller) scanSecrets(
ctx context.Context, ctx context.Context,
rgit RestrictedGIT, rgit RestrictedGIT,
repo *types.Repository, repo *types.RepositoryCore,
in types.GithookPreReceiveInput, in types.GithookPreReceiveInput,
output *hook.Output, output *hook.Output,
) error { ) error {
@ -81,7 +81,7 @@ func (c *Controller) scanSecrets(
func scanSecretsInternal(ctx context.Context, func scanSecretsInternal(ctx context.Context,
rgit RestrictedGIT, rgit RestrictedGIT,
repo *types.Repository, repo *types.RepositoryCore,
in types.GithookPreReceiveInput, in types.GithookPreReceiveInput,
) ([]secretFinding, error) { ) ([]secretFinding, error) {
var baseRevFallBack *string var baseRevFallBack *string

View File

@ -20,6 +20,7 @@ import (
eventsgit "github.com/harness/gitness/app/events/git" eventsgit "github.com/harness/gitness/app/events/git"
eventsrepo "github.com/harness/gitness/app/events/repo" eventsrepo "github.com/harness/gitness/app/events/repo"
"github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/settings"
"github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/sse"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
@ -45,6 +46,7 @@ func ProvideController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
principalStore store.PrincipalStore, principalStore store.PrincipalStore,
repoStore store.RepoStore, repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
gitReporter *eventsgit.Reporter, gitReporter *eventsgit.Reporter,
repoReporter *eventsrepo.Reporter, repoReporter *eventsrepo.Reporter,
git git.Interface, git git.Interface,
@ -63,6 +65,7 @@ func ProvideController(
authorizer, authorizer,
principalStore, principalStore,
repoStore, repoStore,
repoFinder,
gitReporter, gitReporter,
repoReporter, repoReporter,
git, git,

View File

@ -42,7 +42,7 @@ func (c *Controller) Action(
if err := c.sanitizeActionInput(in); err != nil { if err := c.sanitizeActionInput(in); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
space, err := c.spaceCache.Get(ctx, in.SpaceRef) space, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -29,8 +29,8 @@ import (
type Controller struct { type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
infraProviderSvc *infraprovider.Service infraProviderSvc *infraprovider.Service
spaceCache refcache.SpaceCache
spaceStore store.SpaceStore spaceStore store.SpaceStore
spaceFinder refcache.SpaceFinder
gitspaceEventStore store.GitspaceEventStore gitspaceEventStore store.GitspaceEventStore
tx dbtx.Transactor tx dbtx.Transactor
statefulLogger *logutil.StatefulLogger statefulLogger *logutil.StatefulLogger
@ -44,8 +44,8 @@ func NewController(
tx dbtx.Transactor, tx dbtx.Transactor,
authorizer authz.Authorizer, authorizer authz.Authorizer,
infraProviderSvc *infraprovider.Service, infraProviderSvc *infraprovider.Service,
spaceCache refcache.SpaceCache,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
gitspaceEventStore store.GitspaceEventStore, gitspaceEventStore store.GitspaceEventStore,
statefulLogger *logutil.StatefulLogger, statefulLogger *logutil.StatefulLogger,
scm *scm.SCM, scm *scm.SCM,
@ -57,8 +57,8 @@ func NewController(
tx: tx, tx: tx,
authorizer: authorizer, authorizer: authorizer,
infraProviderSvc: infraProviderSvc, infraProviderSvc: infraProviderSvc,
spaceCache: spaceCache,
spaceStore: spaceStore, spaceStore: spaceStore,
spaceFinder: spaceFinder,
gitspaceEventStore: gitspaceEventStore, gitspaceEventStore: gitspaceEventStore,
statefulLogger: statefulLogger, statefulLogger: statefulLogger,
scm: scm, scm: scm,

View File

@ -66,7 +66,7 @@ func (c *Controller) Create(
session *auth.Session, session *auth.Session,
in *CreateInput, in *CreateInput,
) (*types.GitspaceConfig, error) { ) (*types.GitspaceConfig, error) {
space, err := c.spaceCache.Get(ctx, in.SpaceRef) space, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }
@ -119,7 +119,7 @@ func (c *Controller) Create(
in.ResourceSpaceRef = rootSpaceRef in.ResourceSpaceRef = rootSpaceRef
} }
resourceIdentifier := in.ResourceIdentifier resourceIdentifier := in.ResourceIdentifier
resourceSpace, err := c.spaceCache.Get(ctx, in.ResourceSpaceRef) resourceSpace, err := c.spaceFinder.FindByRef(ctx, in.ResourceSpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }
@ -181,7 +181,7 @@ func (c *Controller) Create(
func (c *Controller) createOrFindInfraProviderResource( func (c *Controller) createOrFindInfraProviderResource(
ctx context.Context, ctx context.Context,
resourceSpace *types.Space, resourceSpace *types.SpaceCore,
resourceIdentifier string, resourceIdentifier string,
now int64, now int64,
) (*types.InfraProviderResource, error) { ) (*types.InfraProviderResource, error) {
@ -203,7 +203,7 @@ func (c *Controller) createOrFindInfraProviderResource(
func (c *Controller) autoCreateDefaultResource( func (c *Controller) autoCreateDefaultResource(
ctx context.Context, ctx context.Context,
currentSpace *types.Space, currentSpace *types.SpaceCore,
now int64, now int64,
) (*types.InfraProviderResource, error) { ) (*types.InfraProviderResource, error) {
rootSpace, err := c.spaceStore.GetRootSpace(ctx, currentSpace.ID) rootSpace, err := c.spaceStore.GetRootSpace(ctx, currentSpace.ID)

View File

@ -39,7 +39,7 @@ func (c *Controller) Events(
page int, page int,
limit int, limit int,
) ([]*types.GitspaceEventResponse, int, error) { ) ([]*types.GitspaceEventResponse, int, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to find space: %w", err) return nil, 0, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -42,7 +42,7 @@ func (c *Controller) ListAllGitspaces( // nolint:gocognit
var spacesMap = make(map[int64]string) var spacesMap = make(map[int64]string)
for idx := 0; idx < len(allGitspaceConfigs); idx++ { for idx := 0; idx < len(allGitspaceConfigs); idx++ {
if spacesMap[allGitspaceConfigs[idx].SpaceID] == "" { if spacesMap[allGitspaceConfigs[idx].SpaceID] == "" {
space, findSpaceErr := c.spaceCache.Get(ctx, allGitspaceConfigs[idx].SpacePath) space, findSpaceErr := c.spaceFinder.FindByRef(ctx, allGitspaceConfigs[idx].SpacePath)
if findSpaceErr != nil { if findSpaceErr != nil {
if !errors.Is(findSpaceErr, store.ErrResourceNotFound) { if !errors.Is(findSpaceErr, store.ErrResourceNotFound) {
return fmt.Errorf( return fmt.Errorf(

View File

@ -48,7 +48,7 @@ func (c *Controller) LookupRepo(
if err := c.sanitizeLookupRepoInput(in); err != nil { if err := c.sanitizeLookupRepoInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err) return nil, fmt.Errorf("invalid input: %w", err)
} }
space, err := c.spaceCache.Get(ctx, in.SpaceRef) space, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -37,8 +37,8 @@ func ProvideController(
tx dbtx.Transactor, tx dbtx.Transactor,
authorizer authz.Authorizer, authorizer authz.Authorizer,
infraProviderSvc *infraprovider.Service, infraProviderSvc *infraprovider.Service,
spaceCache refcache.SpaceCache,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
spaceFinder refcache.SpaceFinder,
eventStore store.GitspaceEventStore, eventStore store.GitspaceEventStore,
statefulLogger *logutil.StatefulLogger, statefulLogger *logutil.StatefulLogger,
scm *scm.SCM, scm *scm.SCM,
@ -50,8 +50,8 @@ func ProvideController(
tx, tx,
authorizer, authorizer,
infraProviderSvc, infraProviderSvc,
spaceCache,
spaceStore, spaceStore,
spaceFinder,
eventStore, eventStore,
statefulLogger, statefulLogger,
scm, scm,

View File

@ -22,18 +22,18 @@ import (
type Controller struct { type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
infraproviderSvc *infraprovider.Service infraproviderSvc *infraprovider.Service
} }
func NewController( func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
infraproviderSvc *infraprovider.Service, infraproviderSvc *infraprovider.Service,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
authorizer: authorizer, authorizer: authorizer,
spaceCache: spaceCache, spaceFinder: spaceFinder,
infraproviderSvc: infraproviderSvc, infraproviderSvc: infraproviderSvc,
} }
} }

View File

@ -66,7 +66,7 @@ func (c *Controller) Create(
if err := c.sanitizeCreateInput(in); err != nil { if err := c.sanitizeCreateInput(in); err != nil {
return nil, fmt.Errorf("invalid input: %w", err) return nil, fmt.Errorf("invalid input: %w", err)
} }
parentSpace, err := c.spaceCache.Get(ctx, in.SpaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref %q : %w", in.SpaceRef, err) return nil, fmt.Errorf("failed to find parent by ref %q : %w", in.SpaceRef, err)
} }
@ -90,7 +90,7 @@ func (c *Controller) Create(
func (c *Controller) MapToInfraProviderConfig( func (c *Controller) MapToInfraProviderConfig(
in CreateInput, in CreateInput,
parentSpace *types.Space, parentSpace *types.SpaceCore,
now int64, now int64,
) *types.InfraProviderConfig { ) *types.InfraProviderConfig {
infraProviderConfig := &types.InfraProviderConfig{ infraProviderConfig := &types.InfraProviderConfig{
@ -102,7 +102,7 @@ func (c *Controller) MapToInfraProviderConfig(
Created: now, Created: now,
Updated: now, Updated: now,
} }
infraProviderConfig.Resources = mapToResourceEntity(in.Resources, *parentSpace, now) infraProviderConfig.Resources = mapToResourceEntity(in.Resources, parentSpace, now)
return infraProviderConfig return infraProviderConfig
} }

View File

@ -35,7 +35,7 @@ func (c *Controller) CreateTemplate(
spaceRef string, spaceRef string,
) (*types.InfraProviderTemplate, error) { ) (*types.InfraProviderTemplate, error) {
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
parentSpace, err := c.spaceCache.Get(ctx, spaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }
@ -83,7 +83,7 @@ func (c *Controller) CreateResources(
return nil, fmt.Errorf("invalid input: %w", err) return nil, fmt.Errorf("invalid input: %w", err)
} }
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
parentSpace, err := c.spaceCache.Get(ctx, spaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }
@ -100,7 +100,7 @@ func (c *Controller) CreateResources(
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find infraprovider config by ref: %q %w", infraProviderConfig.Identifier, err) return nil, fmt.Errorf("failed to find infraprovider config by ref: %q %w", infraProviderConfig.Identifier, err)
} }
resources := mapToResourceEntity(in, *parentSpace, now) resources := mapToResourceEntity(in, parentSpace, now)
err = c.infraproviderSvc.CreateResources(ctx, resources, infraProviderConfig.ID) err = c.infraproviderSvc.CreateResources(ctx, resources, infraProviderConfig.ID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -108,7 +108,7 @@ func (c *Controller) CreateResources(
return resources, nil return resources, nil
} }
func mapToResourceEntity(in []ResourceInput, parentSpace types.Space, now int64) []types.InfraProviderResource { func mapToResourceEntity(in []ResourceInput, parentSpace *types.SpaceCore, now int64) []types.InfraProviderResource {
var resources []types.InfraProviderResource var resources []types.InfraProviderResource
for _, res := range in { for _, res := range in {
infraProviderResource := types.InfraProviderResource{ infraProviderResource := types.InfraProviderResource{

View File

@ -30,7 +30,7 @@ func (c *Controller) Find(
spaceRef string, spaceRef string,
identifier string, identifier string,
) (*types.InfraProviderConfig, error) { ) (*types.InfraProviderConfig, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -29,8 +29,8 @@ var WireSet = wire.NewSet(
func ProvideController( func ProvideController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
infraproviderSvc *infraprovider.Service, infraproviderSvc *infraprovider.Service,
) *Controller { ) *Controller {
return NewController(authorizer, spaceCache, infraproviderSvc) return NewController(authorizer, spaceFinder, infraproviderSvc)
} }

View File

@ -51,7 +51,7 @@ type Controller struct {
tx dbtx.Transactor tx dbtx.Transactor
spaceStore store.SpaceStore spaceStore store.SpaceStore
repoStore store.RepoStore repoStore store.RepoStore
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
repoFinder refcache.RepoFinder repoFinder refcache.RepoFinder
} }
@ -70,7 +70,7 @@ func NewController(
tx dbtx.Transactor, tx dbtx.Transactor,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
repoStore store.RepoStore, repoStore store.RepoStore,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
@ -88,7 +88,7 @@ func NewController(
tx: tx, tx: tx,
spaceStore: spaceStore, spaceStore: spaceStore,
repoStore: repoStore, repoStore: repoStore,
spaceCache: spaceCache, spaceFinder: spaceFinder,
repoFinder: repoFinder, repoFinder: repoFinder,
} }
} }
@ -98,7 +98,7 @@ func (c *Controller) getRepoCheckAccess(
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
@ -122,8 +122,8 @@ func (c *Controller) getSpaceCheckAccess(
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
space, err := c.spaceCache.Get(ctx, parentRef) space, err := c.spaceFinder.FindByRef(ctx, parentRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err) return nil, fmt.Errorf("parent space not found: %w", err)
} }

View File

@ -51,11 +51,16 @@ func (c *Controller) CreateRepo(
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
parentSpace, err := c.spaceCheckAuth(ctx, session, in.ParentRef) parentSpaceCore, err := c.spaceCheckAuth(ctx, session, in.ParentRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to check auth in parent '%s': %w", in.ParentRef, err) return nil, fmt.Errorf("failed to check auth in parent '%s': %w", in.ParentRef, err)
} }
parentSpace, err := c.spaceStore.Find(ctx, parentSpaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
// generate envars (add everything githook CLI needs for execution) // generate envars (add everything githook CLI needs for execution)
envVars, err := githook.GenerateEnvironmentVariables( envVars, err := githook.GenerateEnvironmentVariables(
ctx, ctx,
@ -172,8 +177,8 @@ func (c *Controller) spaceCheckAuth(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
space, err := c.spaceCache.Get(ctx, parentRef) space, err := c.spaceFinder.FindByRef(ctx, parentRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err) return nil, fmt.Errorf("parent space not found: %w", err)
} }

View File

@ -45,23 +45,31 @@ func (c *Controller) UpdateRepoState(
return nil, fmt.Errorf("failed to acquire access to repo: %w", err) return nil, fmt.Errorf("failed to acquire access to repo: %w", err)
} }
if !stateTransitionValid(repo, in.State) { repoFull, err := c.repoStore.Find(ctx, repo.ID)
return nil, usererror.BadRequestf("Changing repo state from %s to %s is not allowed.", repo.State, in.State) if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
} }
repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error { repoFull, err = c.repoStore.UpdateOptLock(ctx, repoFull, func(r *types.Repository) error {
if !stateTransitionValid(r.State, in.State) {
return usererror.BadRequestf("Changing repo state from %s to %s is not allowed.", r.State, in.State)
}
r.State = in.State r.State = in.State
return nil return nil
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to update the repo state: %w", err) return nil, fmt.Errorf("failed to update the repo state: %w", err)
} }
return repo, nil c.repoFinder.MarkChanged(ctx, repo.ID)
return repoFull, nil
} }
func stateTransitionValid(repo *types.Repository, newState enum.RepoState) bool { func stateTransitionValid(currentState enum.RepoState, newState enum.RepoState) bool {
for _, validState := range validTransitions[repo.State] { for _, validState := range validTransitions[currentState] {
if validState == newState { if validState == newState {
return true return true
} }

View File

@ -50,7 +50,7 @@ func ProvideController(
tx dbtx.Transactor, tx dbtx.Transactor,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
repoStore store.RepoStore, repoStore store.RepoStore,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
) *Controller { ) *Controller {
return NewController( return NewController(
@ -68,7 +68,7 @@ func ProvideController(
tx, tx,
spaceStore, spaceStore,
repoStore, repoStore,
spaceCache, spaceFinder,
repoFinder, repoFinder,
) )
} }

View File

@ -64,7 +64,7 @@ func (c *Controller) getRepoCheckPipelineAccess(
pipelineIdentifier string, pipelineIdentifier string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef) repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo by ref: %w", err) return nil, fmt.Errorf("failed to find repo by ref: %w", err)

View File

@ -34,6 +34,7 @@ func (c *Controller) CodeOwners(
if err != nil { if err != nil {
return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to acquire access to repo: %w", err) return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to acquire access to repo: %w", err)
} }
pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum) pr, err := c.pullreqStore.FindByNumber(ctx, repo.ID, pullreqNum)
if err != nil { if err != nil {
return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to get pull request by number: %w", err) return types.CodeOwnerEvaluation{}, fmt.Errorf("failed to get pull request by number: %w", err)

View File

@ -371,7 +371,7 @@ func setAsCodeComment(a *types.PullReqActivity, cut git.DiffCutOutput, path, sou
func (c *Controller) fetchDiffCut( func (c *Controller) fetchDiffCut(
ctx context.Context, ctx context.Context,
repo *types.Repository, repo *types.RepositoryCore,
in *CommentCreateInput, in *CommentCreateInput,
) (git.DiffCutOutput, error) { ) (git.DiffCutOutput, error) {
// maxDiffLineCount restricts the total length of a code comment diff to 1000 lines. // maxDiffLineCount restricts the total length of a code comment diff to 1000 lines.
@ -401,7 +401,7 @@ func (c *Controller) fetchDiffCut(
func (c *Controller) migrateCodeComment( func (c *Controller) migrateCodeComment(
ctx context.Context, ctx context.Context,
repo *types.Repository, repo *types.RepositoryCore,
pr *types.PullReq, pr *types.PullReq,
in *CommentCreateInput, in *CommentCreateInput,
cc *types.CodeComment, cc *types.CodeComment,

View File

@ -150,7 +150,7 @@ func NewController(
} }
func (c *Controller) verifyBranchExistence(ctx context.Context, func (c *Controller) verifyBranchExistence(ctx context.Context,
repo *types.Repository, branch string, repo *types.RepositoryCore, branch string,
) (sha.SHA, error) { ) (sha.SHA, error) {
if branch == "" { if branch == "" {
return sha.SHA{}, usererror.BadRequest("branch name can't be empty") return sha.SHA{}, usererror.BadRequest("branch name can't be empty")
@ -175,7 +175,7 @@ func (c *Controller) verifyBranchExistence(ctx context.Context,
return ref.SHA, nil return ref.SHA, nil
} }
func (c *Controller) getRepo(ctx context.Context, repoRef string) (*types.Repository, error) { func (c *Controller) getRepo(ctx context.Context, repoRef string) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
@ -195,7 +195,7 @@ func (c *Controller) getRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := c.getRepo(ctx, repoRef) repo, err := c.getRepo(ctx, repoRef)
if err != nil { if err != nil {
return nil, err return nil, err
@ -215,7 +215,7 @@ func (c *Controller) getRepoCheckAccess(
func (c *Controller) fetchRules( func (c *Controller) fetchRules(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
) (protection.Protection, bool, error) { ) (protection.Protection, bool, error) {
isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo) isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo)
if err != nil { if err != nil {

View File

@ -178,7 +178,7 @@ func (c *Controller) Merge(
sourceRepo := targetRepo sourceRepo := targetRepo
if pr.SourceRepoID != pr.TargetRepoID { if pr.SourceRepoID != pr.TargetRepoID {
sourceRepo, err = c.repoStore.Find(ctx, pr.SourceRepoID) sourceRepo, err = c.repoFinder.FindByID(ctx, pr.SourceRepoID)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("failed to get source repository: %w", err) return nil, nil, fmt.Errorf("failed to get source repository: %w", err)
} }

View File

@ -140,38 +140,45 @@ func (c *Controller) Create(
} }
var pr *types.PullReq var pr *types.PullReq
targetRepoID := targetRepo.ID targetRepoID := targetRepo.ID
labelAssignInputMap, err := c.prepareLabels( labelAssignInputMap, err := c.prepareLabels(
ctx, in.Labels, session.Principal.ID, targetRepo.ID, targetRepo.ParentID, ctx, in.Labels, session.Principal.ID, targetRepo.ID, targetRepo.ParentID,
) )
if err != nil {
return nil, fmt.Errorf("failed to prepare labels: %w", err)
}
var labelAssignOuts []*labelsvc.AssignToPullReqOut var labelAssignOuts []*labelsvc.AssignToPullReqOut
err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error { err = controller.TxOptLock(ctx, c.tx, func(ctx context.Context) error {
// Always re-fetch at the start of the transaction because the repo we have is from a cache. // Always re-fetch at the start of the transaction because the repo we have is from a cache.
targetRepo, err = c.repoStore.Find(ctx, targetRepoID) targetRepoFull, err := c.repoStore.Find(ctx, targetRepoID)
if err != nil { if err != nil {
return fmt.Errorf("failed to find repository: %w", err) return fmt.Errorf("failed to find repository: %w", err)
} }
// Update the repository's pull request sequence number // Update the repository's pull request sequence number
targetRepo.PullReqSeq++ targetRepoFull.PullReqSeq++
err = c.repoStore.Update(ctx, targetRepo) err = c.repoStore.Update(ctx, targetRepoFull)
if err != nil { if err != nil {
return fmt.Errorf("failed to update pullreq sequence number: %w", err) return fmt.Errorf("failed to update pullreq sequence number: %w", err)
} }
// Create pull request in the DB // Create pull request in the DB
pr = newPullReq(session, targetRepo.PullReqSeq, sourceRepo, targetRepo, in, sourceSHA, mergeBaseSHA) pr = newPullReq(session, targetRepoFull.PullReqSeq, sourceRepo.ID, targetRepo.ID, in, sourceSHA, mergeBaseSHA)
pr.Stats = types.PullReqStats{ pr.Stats = types.PullReqStats{
DiffStats: types.NewDiffStats(prStats.Commits, prStats.FilesChanged, prStats.Additions, prStats.Deletions), DiffStats: types.NewDiffStats(prStats.Commits, prStats.FilesChanged, prStats.Additions, prStats.Deletions),
Conversations: 0, Conversations: 0,
UnresolvedCount: 0, UnresolvedCount: 0,
} }
targetRepo = targetRepoFull.Core()
// Calculate the activity sequence // Calculate the activity sequence
pr.ActivitySeq = int64(len(in.Labels) + len(in.ReviewerIDs)) pr.ActivitySeq = int64(len(in.Labels) + len(in.ReviewerIDs))
@ -196,7 +203,7 @@ func (c *Controller) Create(
err = c.git.UpdateRef(ctx, git.UpdateRefParams{ err = c.git.UpdateRef(ctx, git.UpdateRefParams{
WriteParams: targetWriteParams, WriteParams: targetWriteParams,
Name: strconv.FormatInt(targetRepo.PullReqSeq, 10), Name: strconv.FormatInt(targetRepoFull.PullReqSeq, 10),
Type: gitenum.RefTypePullReqHead, Type: gitenum.RefTypePullReqHead,
NewValue: sourceSHA, NewValue: sourceSHA,
OldValue: sha.None, // we don't care about the old value OldValue: sha.None, // we don't care about the old value
@ -243,7 +250,7 @@ func (c *Controller) createReviewers(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
reviewers []int64, reviewers []int64,
repo *types.Repository, repo *types.RepositoryCore,
pr *types.PullReq, pr *types.PullReq,
) error { ) error {
if len(reviewers) == 0 { if len(reviewers) == 0 {
@ -391,8 +398,8 @@ func (c *Controller) storeLabelAssignActivity(
func newPullReq( func newPullReq(
session *auth.Session, session *auth.Session,
number int64, number int64,
sourceRepo *types.Repository, sourceRepoID int64,
targetRepo *types.Repository, targetRepoID int64,
in *CreateInput, in *CreateInput,
sourceSHA, mergeBaseSHA sha.SHA, sourceSHA, mergeBaseSHA sha.SHA,
) *types.PullReq { ) *types.PullReq {
@ -409,10 +416,10 @@ func newPullReq(
IsDraft: in.IsDraft, IsDraft: in.IsDraft,
Title: in.Title, Title: in.Title,
Description: in.Description, Description: in.Description,
SourceRepoID: sourceRepo.ID, SourceRepoID: sourceRepoID,
SourceBranch: in.SourceBranch, SourceBranch: in.SourceBranch,
SourceSHA: sourceSHA.String(), SourceSHA: sourceSHA.String(),
TargetRepoID: targetRepo.ID, TargetRepoID: targetRepoID,
TargetBranch: in.TargetBranch, TargetBranch: in.TargetBranch,
ActivitySeq: 0, ActivitySeq: 0,
MergedBy: nil, MergedBy: nil,

View File

@ -39,7 +39,7 @@ func (c *Controller) List(
if filter.SourceRepoRef == repoRef { if filter.SourceRepoRef == repoRef {
filter.SourceRepoID = repo.ID filter.SourceRepoID = repo.ID
} else if filter.SourceRepoRef != "" { } else if filter.SourceRepoRef != "" {
var sourceRepo *types.Repository var sourceRepo *types.RepositoryCore
sourceRepo, err = c.getRepoCheckAccess(ctx, session, filter.SourceRepoRef, enum.PermissionRepoView) sourceRepo, err = c.getRepoCheckAccess(ctx, session, filter.SourceRepoRef, enum.PermissionRepoView)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to acquire access to source repo: %w", err) return nil, 0, fmt.Errorf("failed to acquire access to source repo: %w", err)

View File

@ -79,7 +79,7 @@ func (c *Controller) State(ctx context.Context,
sourceRepo := targetRepo sourceRepo := targetRepo
if pr.SourceRepoID != pr.TargetRepoID { if pr.SourceRepoID != pr.TargetRepoID {
sourceRepo, err = c.repoStore.Find(ctx, pr.SourceRepoID) sourceRepo, err = c.repoFinder.FindByID(ctx, pr.SourceRepoID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get source repo by id: %w", err) return nil, fmt.Errorf("failed to get source repo by id: %w", err)
} }

View File

@ -67,9 +67,9 @@ func (c *Controller) Update(ctx context.Context,
} }
if pr.SourceRepoID != pr.TargetRepoID { if pr.SourceRepoID != pr.TargetRepoID {
var sourceRepo *types.Repository var sourceRepo *types.RepositoryCore
sourceRepo, err = c.repoStore.Find(ctx, pr.SourceRepoID) sourceRepo, err = c.repoFinder.FindByID(ctx, pr.SourceRepoID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get source repo by id: %w", err) return nil, fmt.Errorf("failed to get source repo by id: %w", err)
} }

View File

@ -169,7 +169,7 @@ func (c *Controller) reportReviewerAddition(
// newPullReqReviewer creates new pull request reviewer object. // newPullReqReviewer creates new pull request reviewer object.
func newPullReqReviewer( func newPullReqReviewer(
session *auth.Session, pullReq *types.PullReq, session *auth.Session, pullReq *types.PullReq,
repo *types.Repository, reviewerInfo, addedByInfo *types.PrincipalInfo, repo *types.RepositoryCore, reviewerInfo, addedByInfo *types.PrincipalInfo,
reviewerType enum.PullReqReviewerType, in *ReviewerAddInput, reviewerType enum.PullReqReviewerType, in *ReviewerAddInput,
) *types.PullReqReviewer { ) *types.PullReqReviewer {
now := time.Now().UnixMilli() now := time.Now().UnixMilli()

View File

@ -65,7 +65,7 @@ func addReviewerUserGroup(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
c *Controller, c *Controller,
repo *types.Repository, repo *types.RepositoryCore,
pr *types.PullReq, pr *types.PullReq,
in *UserGroupReviewerAddInput, in *UserGroupReviewerAddInput,
) (*types.UserGroupReviewer, error) { ) (*types.UserGroupReviewer, error) {
@ -107,7 +107,7 @@ func addReviewerUserGroup(
func newPullReqUserGroupReviewer( func newPullReqUserGroupReviewer(
session *auth.Session, session *auth.Session,
pullReq *types.PullReq, pullReq *types.PullReq,
repo *types.Repository, repo *types.RepositoryCore,
userGroupReviewerInfo types.UserGroupInfo, userGroupReviewerInfo types.UserGroupInfo,
addedByInfo *types.PrincipalInfo, addedByInfo *types.PrincipalInfo,
in *UserGroupReviewerAddInput, in *UserGroupReviewerAddInput,

View File

@ -93,7 +93,7 @@ type Controller struct {
userGroupService usergroup.SearchService userGroupService usergroup.SearchService
protectionManager *protection.Manager protectionManager *protection.Manager
git git.Interface git git.Interface
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
repoFinder refcache.RepoFinder repoFinder refcache.RepoFinder
importer *importer.Repository importer *importer.Repository
codeOwners *codeowners.Service codeOwners *codeowners.Service
@ -129,7 +129,7 @@ func NewController(
principalInfoCache store.PrincipalInfoCache, principalInfoCache store.PrincipalInfoCache,
protectionManager *protection.Manager, protectionManager *protection.Manager,
git git.Interface, git git.Interface,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
importer *importer.Repository, importer *importer.Repository,
codeOwners *codeowners.Service, codeOwners *codeowners.Service,
@ -166,7 +166,7 @@ func NewController(
principalInfoCache: principalInfoCache, principalInfoCache: principalInfoCache,
protectionManager: protectionManager, protectionManager: protectionManager,
git: git, git: git,
spaceCache: spaceCache, spaceFinder: spaceFinder,
repoFinder: repoFinder, repoFinder: repoFinder,
importer: importer, importer: importer,
codeOwners: codeOwners, codeOwners: codeOwners,
@ -198,7 +198,7 @@ func (c *Controller) getRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
return GetRepoCheckAccess( return GetRepoCheckAccess(
ctx, ctx,
c.repoFinder, c.repoFinder,
@ -217,7 +217,7 @@ func (c *Controller) getRepoCheckAccessForGit(
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
return GetRepoCheckAccess( return GetRepoCheckAccess(
ctx, ctx,
c.repoFinder, c.repoFinder,
@ -234,8 +234,8 @@ func (c *Controller) getSpaceCheckAuthRepoCreation(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
return GetSpaceCheckAuthRepoCreation(ctx, c.spaceCache, c.authorizer, session, parentRef) return GetSpaceCheckAuthRepoCreation(ctx, c.spaceFinder, c.authorizer, session, parentRef)
} }
func ValidateParentRef(parentRef string) error { func ValidateParentRef(parentRef string) error {
@ -250,7 +250,7 @@ func ValidateParentRef(parentRef string) error {
func (c *Controller) fetchRules( func (c *Controller) fetchRules(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
) (protection.Protection, bool, error) { ) (protection.Protection, bool, error) {
isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo) isRepoOwner, err := apiauth.IsRepoOwner(ctx, c.authorizer, session, repo)
if err != nil { if err != nil {

View File

@ -101,7 +101,7 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
} }
// lock the space for update during repo creation to prevent racing conditions with space soft delete. // lock the space for update during repo creation to prevent racing conditions with space soft delete.
parentSpace, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID)
if err != nil { if err != nil {
return fmt.Errorf("failed to find the parent space: %w", err) return fmt.Errorf("failed to find the parent space: %w", err)
} }

View File

@ -49,7 +49,6 @@ func (c *Controller) UpdateDefaultBranch(
return nil, err return nil, err
} }
repoClone := repo.Clone()
// the max time we give an update default branch to succeed // the max time we give an update default branch to succeed
const timeout = 2 * time.Minute const timeout = 2 * time.Minute
@ -79,6 +78,11 @@ func (c *Controller) UpdateDefaultBranch(
) )
defer cancel() defer cancel()
repoFull, err := c.repoStore.Find(ctx, repo.ID)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
}
err = c.git.UpdateDefaultBranch(ctx, &git.UpdateDefaultBranchParams{ err = c.git.UpdateDefaultBranch(ctx, &git.UpdateDefaultBranchParams{
WriteParams: writeParams, WriteParams: writeParams,
BranchName: in.Name, BranchName: in.Name,
@ -87,16 +91,24 @@ func (c *Controller) UpdateDefaultBranch(
return nil, fmt.Errorf("failed to update the repo default branch: %w", err) return nil, fmt.Errorf("failed to update the repo default branch: %w", err)
} }
oldName := repo.DefaultBranch var oldName string
repo, err = c.repoStore.UpdateOptLock(ctx, repo, func(r *types.Repository) error { var repoClone types.Repository
repoFull, err = c.repoStore.UpdateOptLock(ctx, repoFull, func(r *types.Repository) error {
repoClone = *repoFull
oldName = repoFull.DefaultBranch
r.DefaultBranch = in.Name r.DefaultBranch = in.Name
return nil return nil
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to update the repo default branch on db:%w", err) return nil, fmt.Errorf("failed to update the repo default branch on db:%w", err)
} }
repoOutput, err := GetRepoOutput(ctx, c.publicAccess, repo) c.repoFinder.MarkChanged(ctx, repo.ID)
repoOutput, err := GetRepoOutput(ctx, c.publicAccess, repoFull)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get repo output: %w", err) return nil, fmt.Errorf("failed to get repo output: %w", err)
} }
@ -111,7 +123,7 @@ func (c *Controller) UpdateDefaultBranch(
IsPublic: repoOutput.IsPublic, IsPublic: repoOutput.IsPublic,
}), }),
audit.WithNewObject(audit.RepositoryObject{ audit.WithNewObject(audit.RepositoryObject{
Repository: *repo, Repository: *repoFull,
IsPublic: repoOutput.IsPublic, IsPublic: repoOutput.IsPublic,
}), }),
) )

View File

@ -16,6 +16,7 @@ package repo
import ( import (
"context" "context"
"fmt"
apiauth "github.com/harness/gitness/app/api/auth" apiauth "github.com/harness/gitness/app/api/auth"
"github.com/harness/gitness/app/auth" "github.com/harness/gitness/app/auth"
@ -25,15 +26,20 @@ import (
// Find finds a repo. // Find finds a repo.
func (c *Controller) Find(ctx context.Context, session *auth.Session, repoRef string) (*RepositoryOutput, error) { func (c *Controller) Find(ctx context.Context, session *auth.Session, repoRef string) (*RepositoryOutput, error) {
// note: can't use c.getRepoCheckAccess because even repositories that are currently being imported can be fetched. // note: can't use c.getRepoCheckAccess because even repositories that are currently being imported can be fetched.
repo, err := c.repoFinder.FindByRef(ctx, repoRef) repoCore, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView); err != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoView); err != nil {
return nil, err return nil, err
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to fetch repo by ID: %w", err)
}
// backfill clone url // backfill clone url
repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path) repo.GitURL = c.urlProvider.GenerateGITCloneURL(ctx, repo.Path)
repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path) repo.GitSSHURL = c.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path)

View File

@ -37,12 +37,12 @@ var importingStates = []enum.RepoState{
enum.RepoStateMigrateGitPush, enum.RepoStateMigrateGitPush,
} }
// GetRepo fetches an repository. // GetRepo fetches a repository.
func GetRepo( func GetRepo(
ctx context.Context, ctx context.Context,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
repoRef string, repoRef string,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }
@ -65,7 +65,7 @@ func GetRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := GetRepo(ctx, repoFinder, repoRef) repo, err := GetRepo(ctx, repoFinder, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err) return nil, fmt.Errorf("failed to find repo: %w", err)
@ -84,12 +84,12 @@ func GetRepoCheckAccess(
func GetSpaceCheckAuthRepoCreation( func GetSpaceCheckAuthRepoCreation(
ctx context.Context, ctx context.Context,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
space, err := spaceCache.Get(ctx, parentRef) space, err := spaceFinder.FindByRef(ctx, parentRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err) return nil, fmt.Errorf("parent space not found: %w", err)
} }
@ -153,7 +153,7 @@ func GetRepoCheckServiceAccountAccess(
repoStore store.RepoStore, repoStore store.RepoStore,
spaceStore store.SpaceStore, spaceStore store.SpaceStore,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := GetRepo(ctx, repoFinder, repoRef) repo, err := GetRepo(ctx, repoFinder, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err) return nil, fmt.Errorf("failed to find repo: %w", err)

View File

@ -71,7 +71,7 @@ func (c *Controller) Import(ctx context.Context, session *auth.Session, in *Impo
} }
// lock the space for update during repo creation to prevent racing conditions with space soft delete. // lock the space for update during repo creation to prevent racing conditions with space soft delete.
parentSpace, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID) _, err = c.spaceStore.FindForUpdate(ctx, parentSpace.ID)
if err != nil { if err != nil {
return fmt.Errorf("failed to find the parent space: %w", err) return fmt.Errorf("failed to find the parent space: %w", err)
} }

View File

@ -80,7 +80,7 @@ func (c *Controller) ListBranches(ctx context.Context,
// Each of these would be returned only if the corresponding option is true. // Each of these would be returned only if the corresponding option is true.
func (c *Controller) collectBranchMetadata( func (c *Controller) collectBranchMetadata(
ctx context.Context, ctx context.Context,
repo *types.Repository, repo *types.RepositoryCore,
branches []git.Branch, branches []git.Branch,
options types.BranchMetadataOptions, options types.BranchMetadataOptions,
) (branchMetadataOutput, error) { ) (branchMetadataOutput, error) {

View File

@ -51,11 +51,16 @@ func (c *Controller) Move(ctx context.Context,
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) repoCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find or acquire access to repo: %w", err) return nil, fmt.Errorf("failed to find or acquire access to repo: %w", err)
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
}
if !in.hasChanges(repo) { if !in.hasChanges(repo) {
return GetRepoOutput(ctx, c.publicAccess, repo) return GetRepoOutput(ctx, c.publicAccess, repo)
} }
@ -87,6 +92,8 @@ func (c *Controller) Move(ctx context.Context,
return nil, fmt.Errorf("failed to update repo: %w", err) return nil, fmt.Errorf("failed to update repo: %w", err)
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
// set public access for the new repo path // set public access for the new repo path
if err := c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic); err != nil { if err := c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic); err != nil {
// ensure public access for new repo path is cleaned up first or we risk leaking it // ensure public access for new repo path is cleaned up first or we risk leaking it
@ -108,6 +115,8 @@ func (c *Controller) Move(ctx context.Context,
) )
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
// revert public access changes only after we successfully restored original path // revert public access changes only after we successfully restored original path
if dErr = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic); dErr != nil { if dErr = c.publicAccess.Set(ctx, enum.PublicResourceTypeRepo, repo.Path, isPublic); dErr != nil {
return nil, fmt.Errorf( return nil, fmt.Errorf(

View File

@ -42,7 +42,7 @@ func (c *Controller) Purge(
return fmt.Errorf("failed to find the repo (deleted at %d): %w", deletedAt, err) return fmt.Errorf("failed to find the repo (deleted at %d): %w", deletedAt, err)
} }
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoDelete); err != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo.Core(), enum.PermissionRepoDelete); err != nil {
return err return err
} }

View File

@ -46,7 +46,7 @@ func (c *Controller) Restore(
return nil, fmt.Errorf("failed to find repository: %w", err) return nil, fmt.Errorf("failed to find repository: %w", err)
} }
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoCreate); err != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo.Core(), enum.PermissionRepoCreate); err != nil {
return nil, fmt.Errorf("access check failed: %w", err) return nil, fmt.Errorf("access check failed: %w", err)
} }

View File

@ -41,15 +41,20 @@ func (c *Controller) SoftDelete(
repoRef string, repoRef string,
) (*SoftDeleteResponse, error) { ) (*SoftDeleteResponse, error) {
// note: can't use c.getRepoCheckAccess because import job for repositories being imported must be cancelled. // note: can't use c.getRepoCheckAccess because import job for repositories being imported must be cancelled.
repo, err := c.repoFinder.FindByRef(ctx, repoRef) repoCore, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find the repo for soft delete: %w", err) return nil, fmt.Errorf("failed to find the repo for soft delete: %w", err)
} }
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoDelete); err != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoDelete); err != nil {
return nil, fmt.Errorf("access check failed: %w", err) return nil, fmt.Errorf("access check failed: %w", err)
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find the repo by ID: %w", err)
}
if repo.Deleted != nil { if repo.Deleted != nil {
return nil, usererror.BadRequest("repository has been already deleted") return nil, usererror.BadRequest("repository has been already deleted")
} }
@ -105,5 +110,7 @@ func (c *Controller) SoftDeleteNoAuth(
return fmt.Errorf("failed to soft delete repo from db: %w", err) return fmt.Errorf("failed to soft delete repo from db: %w", err)
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
return nil return nil
} }

View File

@ -30,15 +30,14 @@ func (c *Controller) Summary(
session *auth.Session, session *auth.Session,
repoRef string, repoRef string,
) (*types.RepositorySummary, error) { ) (*types.RepositorySummary, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView) repoCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoView)
if err != nil { if err != nil {
return nil, fmt.Errorf("access check failed: %w", err) return nil, fmt.Errorf("access check failed: %w", err)
} }
// fetch the repo because the one we have probably comes from the cache. repo, err := c.repoStore.Find(ctx, repoCore.ID)
repo, err = c.repoStore.Find(ctx, repo.ID)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get the repo: %w", err) return nil, fmt.Errorf("failed to find repo by ID: %w", err)
} }
summary, err := c.git.Summary(ctx, git.SummaryParams{ReadParams: git.CreateReadParams(repo)}) summary, err := c.git.Summary(ctx, git.SummaryParams{ReadParams: git.CreateReadParams(repo)})

View File

@ -62,7 +62,7 @@ func (c *Controller) Update(ctx context.Context,
repoRef string, repoRef string,
in *UpdateInput, in *UpdateInput,
) (*RepositoryOutput, error) { ) (*RepositoryOutput, error) {
repo, err := GetRepo(ctx, c.repoFinder, repoRef) repoCore, err := GetRepo(ctx, c.repoFinder, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err) return nil, fmt.Errorf("failed to find repo: %w", err)
} }
@ -74,15 +74,20 @@ func (c *Controller) Update(ctx context.Context,
enum.RepoStateArchived, enum.RepoStateMigrateDataImport, enum.RepoStateMigrateGitPush} enum.RepoStateArchived, enum.RepoStateMigrateDataImport, enum.RepoStateMigrateGitPush}
} }
err = apiauth.CheckRepoState(ctx, session, repo, enum.PermissionRepoEdit, additionalAllowedRepoStates...) err = apiauth.CheckRepoState(ctx, session, repoCore, enum.PermissionRepoEdit, additionalAllowedRepoStates...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoEdit); err != nil { if err = apiauth.CheckRepo(ctx, c.authorizer, session, repoCore, enum.PermissionRepoEdit); err != nil {
return nil, fmt.Errorf("access check failed: %w", err) return nil, fmt.Errorf("access check failed: %w", err)
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find repository by ID: %w", err)
}
repoClone := repo.Clone() repoClone := repo.Clone()
if !in.hasChanges(repo) { if !in.hasChanges(repo) {
@ -114,6 +119,8 @@ func (c *Controller) Update(ctx context.Context,
return nil, fmt.Errorf("failed to update the repo: %w", err) return nil, fmt.Errorf("failed to update the repo: %w", err)
} }
c.repoFinder.MarkChanged(ctx, repo.ID)
err = c.auditService.Log(ctx, err = c.auditService.Log(ctx,
session.Principal, session.Principal,
audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier), audit.NewResource(audit.ResourceTypeRepositorySettings, repo.Identifier),

View File

@ -35,15 +35,16 @@ func (c *Controller) UpdatePublicAccess(ctx context.Context,
repoRef string, repoRef string,
in *UpdatePublicAccessInput, in *UpdatePublicAccessInput,
) (*RepositoryOutput, error) { ) (*RepositoryOutput, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit) repoCore, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoEdit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
parentPath, _, err := paths.DisectLeaf(repo.Path) parentPath, _, err := paths.DisectLeaf(repoCore.Path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to disect path %q: %w", repo.Path, err) return nil, fmt.Errorf("failed to disect path %q: %w", repoCore.Path, err)
} }
isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, parentPath) isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, parentPath)
if err != nil { if err != nil {
return nil, fmt.Errorf( return nil, fmt.Errorf(
@ -56,11 +57,16 @@ func (c *Controller) UpdatePublicAccess(ctx context.Context,
return nil, errPublicRepoCreationDisabled return nil, errPublicRepoCreationDisabled
} }
isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repo.Path) isPublic, err := c.publicAccess.Get(ctx, enum.PublicResourceTypeRepo, repoCore.Path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to check current public access status: %w", err) return nil, fmt.Errorf("failed to check current public access status: %w", err)
} }
repo, err := c.repoStore.Find(ctx, repoCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find repo by ID: %w", err)
}
// no op // no op
if isPublic == in.IsPublic { if isPublic == in.IsPublic {
return GetRepoOutputWithAccess(ctx, isPublic, repo), nil return GetRepoOutputWithAccess(ctx, isPublic, repo), nil

View File

@ -65,7 +65,7 @@ func ProvideController(
principalInfoCache store.PrincipalInfoCache, principalInfoCache store.PrincipalInfoCache,
protectionManager *protection.Manager, protectionManager *protection.Manager,
rpcClient git.Interface, rpcClient git.Interface,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
importer *importer.Repository, importer *importer.Repository,
codeOwners *codeowners.Service, codeOwners *codeowners.Service,
@ -89,7 +89,7 @@ func ProvideController(
authorizer, authorizer,
repoStore, spaceStore, pipelineStore, executionStore, repoStore, spaceStore, pipelineStore, executionStore,
principalStore, ruleStore, checkStore, pullReqStore, settings, principalStore, ruleStore, checkStore, pullReqStore, settings,
principalInfoCache, protectionManager, rpcClient, spaceCache, repoFinder, importer, principalInfoCache, protectionManager, rpcClient, spaceFinder, repoFinder, importer,
codeOwners, repoReporter, indexer, limiter, locker, auditService, mtxManager, identifierCheck, codeOwners, repoReporter, indexer, limiter, locker, auditService, mtxManager, identifierCheck,
repoChecks, publicAccess, labelSvc, instrumentation, userGroupStore, userGroupService, repoChecks, publicAccess, labelSvc, instrumentation, userGroupStore, userGroupService,
rulesSvc, sseStreamer, rulesSvc, sseStreamer,

View File

@ -58,7 +58,7 @@ func (c *Controller) getRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := repo.GetRepo(ctx, c.repoFinder, repoRef) repo, err := repo.GetRepo(ctx, c.repoFinder, repoRef)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -16,6 +16,7 @@ package secret
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt" "github.com/harness/gitness/encrypt"
) )
@ -24,19 +25,19 @@ type Controller struct {
encrypter encrypt.Encrypter encrypter encrypt.Encrypter
secretStore store.SecretStore secretStore store.SecretStore
authorizer authz.Authorizer authorizer authz.Authorizer
spaceStore store.SpaceStore spaceFinder refcache.SpaceFinder
} }
func NewController( func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
encrypter encrypt.Encrypter, encrypter encrypt.Encrypter,
secretStore store.SecretStore, secretStore store.SecretStore,
spaceStore store.SpaceStore, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
encrypter: encrypter, encrypter: encrypter,
secretStore: secretStore, secretStore: secretStore,
authorizer: authorizer, authorizer: authorizer,
spaceStore: spaceStore, spaceFinder: spaceFinder,
} }
} }

View File

@ -50,7 +50,7 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
parentSpace, err := c.spaceStore.FindByRef(ctx, in.SpaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }

View File

@ -24,7 +24,7 @@ import (
) )
func (c *Controller) Delete(ctx context.Context, session *auth.Session, spaceRef string, identifier string) error { func (c *Controller) Delete(ctx context.Context, session *auth.Session, spaceRef string, identifier string) error {
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return fmt.Errorf("failed to find space: %w", err) return fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -30,7 +30,7 @@ func (c *Controller) Find(
spaceRef string, spaceRef string,
identifier string, identifier string,
) (*types.Secret, error) { ) (*types.Secret, error) {
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -46,7 +46,7 @@ func (c *Controller) Update(
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -16,6 +16,7 @@ package secret
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/harness/gitness/encrypt" "github.com/harness/gitness/encrypt"
@ -31,7 +32,7 @@ func ProvideController(
encrypter encrypt.Encrypter, encrypter encrypt.Encrypter,
secretStore store.SecretStore, secretStore store.SecretStore,
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceStore store.SpaceStore, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return NewController(authorizer, encrypter, secretStore, spaceStore) return NewController(authorizer, encrypter, secretStore, spaceFinder)
} }

View File

@ -90,7 +90,7 @@ type Controller struct {
repoCtrl *repo.Controller repoCtrl *repo.Controller
membershipStore store.MembershipStore membershipStore store.MembershipStore
prListService *pullreq.ListService prListService *pullreq.ListService
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
importer *importer.Repository importer *importer.Repository
exporter *exporter.Repository exporter *exporter.Repository
resourceLimiter limiter.ResourceLimiter resourceLimiter limiter.ResourceLimiter
@ -110,7 +110,7 @@ func NewController(config *types.Config, tx dbtx.Transactor, urlProvider url.Pro
connectorStore store.ConnectorStore, templateStore store.TemplateStore, spaceStore store.SpaceStore, connectorStore store.ConnectorStore, templateStore store.TemplateStore, spaceStore store.SpaceStore,
repoStore store.RepoStore, principalStore store.PrincipalStore, repoCtrl *repo.Controller, repoStore store.RepoStore, principalStore store.PrincipalStore, repoCtrl *repo.Controller,
membershipStore store.MembershipStore, prListService *pullreq.ListService, membershipStore store.MembershipStore, prListService *pullreq.ListService,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
importer *importer.Repository, exporter *exporter.Repository, importer *importer.Repository, exporter *exporter.Repository,
limiter limiter.ResourceLimiter, publicAccess publicaccess.Service, auditService audit.Service, limiter limiter.ResourceLimiter, publicAccess publicaccess.Service, auditService audit.Service,
gitspaceSvc *gitspace.Service, labelSvc *label.Service, gitspaceSvc *gitspace.Service, labelSvc *label.Service,
@ -135,7 +135,7 @@ func NewController(config *types.Config, tx dbtx.Transactor, urlProvider url.Pro
repoCtrl: repoCtrl, repoCtrl: repoCtrl,
membershipStore: membershipStore, membershipStore: membershipStore,
prListService: prListService, prListService: prListService,
spaceCache: spaceCache, spaceFinder: spaceFinder,
importer: importer, importer: importer,
exporter: exporter, exporter: exporter,
resourceLimiter: limiter, resourceLimiter: limiter,
@ -156,23 +156,23 @@ func (c *Controller) getSpaceCheckAuth(
session *auth.Session, session *auth.Session,
spaceRef string, spaceRef string,
permission enum.Permission, permission enum.Permission,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
return GetSpaceCheckAuth(ctx, c.spaceCache, c.authorizer, session, spaceRef, permission) return GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission)
} }
func (c *Controller) getSpaceCheckAuthRepoCreation( func (c *Controller) getSpaceCheckAuthRepoCreation(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
return repo.GetSpaceCheckAuthRepoCreation(ctx, c.spaceCache, c.authorizer, session, parentRef) return repo.GetSpaceCheckAuthRepoCreation(ctx, c.spaceFinder, c.authorizer, session, parentRef)
} }
func (c *Controller) getSpaceCheckAuthSpaceCreation( func (c *Controller) getSpaceCheckAuthSpaceCreation(
ctx context.Context, ctx context.Context,
session *auth.Session, session *auth.Session,
parentRef string, parentRef string,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
parentRefAsID, err := strconv.ParseInt(parentRef, 10, 64) parentRefAsID, err := strconv.ParseInt(parentRef, 10, 64)
if (parentRefAsID <= 0 && err == nil) || (len(strings.TrimSpace(parentRef)) == 0) { if (parentRefAsID <= 0 && err == nil) || (len(strings.TrimSpace(parentRef)) == 0) {
// TODO: Restrict top level space creation - should be move to authorizer? // TODO: Restrict top level space creation - should be move to authorizer?
@ -180,10 +180,10 @@ func (c *Controller) getSpaceCheckAuthSpaceCreation(
return nil, fmt.Errorf("anonymous user not allowed to create top level spaces: %w", usererror.ErrUnauthorized) return nil, fmt.Errorf("anonymous user not allowed to create top level spaces: %w", usererror.ErrUnauthorized)
} }
return &types.Space{}, nil return &types.SpaceCore{}, nil
} }
parentSpace, err := c.spaceCache.Get(ctx, parentRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, parentRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get parent space: %w", err) return nil, fmt.Errorf("failed to get parent space: %w", err)
} }

View File

@ -22,17 +22,17 @@ import (
"github.com/harness/gitness/types/enum" "github.com/harness/gitness/types/enum"
) )
/* // Find finds a space.
* Find finds a space.
*/
func (c *Controller) Find(ctx context.Context, session *auth.Session, spaceRef string) (*SpaceOutput, error) { func (c *Controller) Find(ctx context.Context, session *auth.Session, spaceRef string) (*SpaceOutput, error) {
if c == nil {
return nil, fmt.Errorf("controller instance is nil")
}
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView) space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceView)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err) return nil, fmt.Errorf("failed to acquire access to space: %w", err)
} }
return GetSpaceOutput(ctx, c.publicAccess, space) spaceFull, err := c.spaceStore.Find(ctx, space.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
return GetSpaceOutput(ctx, c.publicAccess, spaceFull)
} }

View File

@ -30,13 +30,13 @@ import (
// GetSpaceCheckAuth checks whether the user has the requested permission on the provided space and returns the space. // GetSpaceCheckAuth checks whether the user has the requested permission on the provided space and returns the space.
func GetSpaceCheckAuth( func GetSpaceCheckAuth(
ctx context.Context, ctx context.Context,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
authorizer authz.Authorizer, authorizer authz.Authorizer,
session *auth.Session, session *auth.Session,
spaceRef string, spaceRef string,
permission enum.Permission, permission enum.Permission,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
space, err := spaceCache.Get(ctx, spaceRef) space, err := spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("parent space not found: %w", err) return nil, fmt.Errorf("parent space not found: %w", err)
} }

View File

@ -90,7 +90,7 @@ func (c *Controller) ImportRepositories(
err = c.tx.WithTx(ctx, func(ctx context.Context) error { err = c.tx.WithTx(ctx, func(ctx context.Context) error {
// lock the space for update during repo creation to prevent racing conditions with space soft delete. // lock the space for update during repo creation to prevent racing conditions with space soft delete.
space, err = c.spaceStore.FindForUpdate(ctx, space.ID) _, err = c.spaceStore.FindForUpdate(ctx, space.ID)
if err != nil { if err != nil {
return fmt.Errorf("failed to find the parent space: %w", err) return fmt.Errorf("failed to find the parent space: %w", err)
} }

View File

@ -31,7 +31,7 @@ func (c *Controller) ListConnectors(
spaceRef string, spaceRef string,
filter types.ListQueryFilter, filter types.ListQueryFilter,
) ([]*types.Connector, int64, error) { ) ([]*types.Connector, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to find parent space: %w", err) return nil, 0, fmt.Errorf("failed to find parent space: %w", err)
} }

View File

@ -30,7 +30,7 @@ func (c *Controller) ListGitspaces(
spaceRef string, spaceRef string,
filter types.GitspaceFilter, filter types.GitspaceFilter,
) ([]*types.GitspaceConfig, int64, int64, error) { ) ([]*types.GitspaceConfig, int64, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, 0, fmt.Errorf("failed to find space: %w", err) return nil, 0, 0, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -33,7 +33,7 @@ func (c *Controller) ListRepositories(
spaceRef string, spaceRef string,
filter *types.RepoFilter, filter *types.RepoFilter,
) ([]*repoCtrl.RepositoryOutput, int64, error) { ) ([]*repoCtrl.RepositoryOutput, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

View File

@ -32,7 +32,7 @@ func (c *Controller) ListSecrets(
spaceRef string, spaceRef string,
filter types.ListQueryFilter, filter types.ListQueryFilter,
) ([]*types.Secret, int64, error) { ) ([]*types.Secret, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to find parent space: %w", err) return nil, 0, fmt.Errorf("failed to find parent space: %w", err)
} }

View File

@ -33,7 +33,7 @@ func (c *Controller) ListServiceAccounts(
inherited bool, inherited bool,
opts *types.PrincipalFilter, opts *types.PrincipalFilter,
) ([]*types.ServiceAccountInfo, int64, error) { ) ([]*types.ServiceAccountInfo, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

View File

@ -31,7 +31,7 @@ func (c *Controller) ListSpaces(ctx context.Context,
spaceRef string, spaceRef string,
filter *types.SpaceFilter, filter *types.SpaceFilter,
) ([]*SpaceOutput, int64, error) { ) ([]*SpaceOutput, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

View File

@ -31,7 +31,7 @@ func (c *Controller) ListTemplates(
spaceRef string, spaceRef string,
filter types.ListQueryFilter, filter types.ListQueryFilter,
) ([]*types.Template, int64, error) { ) ([]*types.Template, int64, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("failed to find parent space: %w", err) return nil, 0, fmt.Errorf("failed to find parent space: %w", err)
} }

View File

@ -49,15 +49,20 @@ func (c *Controller) Move(
spaceRef string, spaceRef string,
in *MoveInput, in *MoveInput,
) (*SpaceOutput, error) { ) (*SpaceOutput, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err) return nil, fmt.Errorf("failed to acquire access to space: %w", err)
} }
if err = c.sanitizeMoveInput(in, space.ParentID == 0); err != nil { if err = c.sanitizeMoveInput(in, spaceCore.ParentID == 0); err != nil {
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
// exit early if there are no changes // exit early if there are no changes
if !in.hasChanges(space) { if !in.hasChanges(space) {
return GetSpaceOutput(ctx, c.publicAccess, space) return GetSpaceOutput(ctx, c.publicAccess, space)
@ -129,6 +134,8 @@ func (c *Controller) moveInner(
return fmt.Errorf("failed to update the space in the db: %w", err) return fmt.Errorf("failed to update the space in the db: %w", err)
} }
c.spaceFinder.MarkChanged(ctx, space.ID)
return nil return nil
}) })
} }

View File

@ -30,7 +30,7 @@ func (c *Controller) ListPullReqs(
includeSubspaces bool, includeSubspaces bool,
filter *types.PullReqFilter, filter *types.PullReqFilter,
) ([]types.PullReqRepo, error) { ) ([]types.PullReqRepo, error) {
space, err := c.spaceCache.Get(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("space not found: %w", err) return nil, fmt.Errorf("space not found: %w", err)
} }

View File

@ -43,7 +43,7 @@ func (c *Controller) Purge(
// authz will check the permission within the first existing parent since space was deleted. // authz will check the permission within the first existing parent since space was deleted.
// purge top level space is limited to admin only. // purge top level space is limited to admin only.
err = apiauth.CheckSpace(ctx, c.authorizer, session, space, enum.PermissionSpaceDelete) err = apiauth.CheckSpace(ctx, c.authorizer, session, space.Core(), enum.PermissionSpaceDelete)
if err != nil { if err != nil {
return fmt.Errorf("failed to authorize on space purge: %w", err) return fmt.Errorf("failed to authorize on space purge: %w", err)
} }

View File

@ -56,7 +56,7 @@ func (c *Controller) Restore(
} }
// check view permission on the original ref. // check view permission on the original ref.
err = apiauth.CheckSpace(ctx, c.authorizer, session, space, enum.PermissionSpaceView) err = apiauth.CheckSpace(ctx, c.authorizer, session, space.Core(), enum.PermissionSpaceView)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to authorize on space restore: %w", err) return nil, fmt.Errorf("failed to authorize on space restore: %w", err)
} }
@ -71,7 +71,7 @@ func (c *Controller) Restore(
ctx, ctx,
c.authorizer, c.authorizer,
session, session,
parentSpace, parentSpace.Core(),
enum.ResourceTypeSpace, enum.ResourceTypeSpace,
enum.PermissionSpaceEdit, enum.PermissionSpaceEdit,
); err != nil { ); err != nil {

View File

@ -35,11 +35,16 @@ func (c *Controller) SoftDelete(
session *auth.Session, session *auth.Session,
spaceRef string, spaceRef string,
) (*SoftDeleteResponse, error) { ) (*SoftDeleteResponse, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceDelete) spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceDelete)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err) return nil, fmt.Errorf("failed to acquire access to space: %w", err)
} }
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
return c.SoftDeleteNoAuth(ctx, session, space) return c.SoftDeleteNoAuth(ctx, session, space)
} }

View File

@ -41,11 +41,16 @@ func (c *Controller) Update(
spaceRef string, spaceRef string,
in *UpdateInput, in *UpdateInput,
) (*SpaceOutput, error) { ) (*SpaceOutput, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err) return nil, fmt.Errorf("failed to acquire access to space: %w", err)
} }
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
if !in.hasChanges(space) { if !in.hasChanges(space) {
return GetSpaceOutput(ctx, c.publicAccess, space) return GetSpaceOutput(ctx, c.publicAccess, space)
} }

View File

@ -32,14 +32,21 @@ func (c *Controller) UpdatePublicAccess(ctx context.Context,
spaceRef string, spaceRef string,
in *UpdatePublicAccessInput, in *UpdatePublicAccessInput,
) (*SpaceOutput, error) { ) (*SpaceOutput, error) {
space, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit) spaceCore, err := c.getSpaceCheckAuth(ctx, session, spaceRef, enum.PermissionSpaceEdit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to acquire access to space: %w", err) return nil, fmt.Errorf("failed to acquire access to space: %w", err)
} }
space, err := c.spaceStore.Find(ctx, spaceCore.ID)
if err != nil {
return nil, fmt.Errorf("failed to find space by ID: %w", err)
}
parentPath, _, err := paths.DisectLeaf(space.Path) parentPath, _, err := paths.DisectLeaf(space.Path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to disect path %q: %w", space.Path, err) return nil, fmt.Errorf("failed to disect path %q: %w", space.Path, err)
} }
isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, parentPath) isPublicAccessSupported, err := c.publicAccess.IsPublicAccessSupported(ctx, parentPath)
if err != nil { if err != nil {
return nil, fmt.Errorf( return nil, fmt.Errorf(

View File

@ -49,7 +49,7 @@ func ProvideController(config *types.Config, tx dbtx.Transactor, urlProvider url
connectorStore store.ConnectorStore, templateStore store.TemplateStore, connectorStore store.ConnectorStore, templateStore store.TemplateStore,
spaceStore store.SpaceStore, repoStore store.RepoStore, principalStore store.PrincipalStore, spaceStore store.SpaceStore, repoStore store.RepoStore, principalStore store.PrincipalStore,
repoCtrl *repo.Controller, membershipStore store.MembershipStore, prListService *pullreq.ListService, repoCtrl *repo.Controller, membershipStore store.MembershipStore, prListService *pullreq.ListService,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
importer *importer.Repository, exporter *exporter.Repository, importer *importer.Repository, exporter *exporter.Repository,
limiter limiter.ResourceLimiter, publicAccess publicaccess.Service, limiter limiter.ResourceLimiter, publicAccess publicaccess.Service,
auditService audit.Service, gitspaceService *gitspace.Service, auditService audit.Service, gitspaceService *gitspace.Service,
@ -62,7 +62,7 @@ func ProvideController(config *types.Config, tx dbtx.Transactor, urlProvider url
connectorStore, templateStore, connectorStore, templateStore,
spaceStore, repoStore, principalStore, spaceStore, repoStore, principalStore,
repoCtrl, membershipStore, prListService, repoCtrl, membershipStore, prListService,
spaceCache, spaceFinder,
importer, exporter, limiter, publicAccess, importer, exporter, limiter, publicAccess,
auditService, gitspaceService, auditService, gitspaceService,
labelSvc, instrumentation, executionStore, labelSvc, instrumentation, executionStore,

View File

@ -16,23 +16,24 @@ package template
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
) )
type Controller struct { type Controller struct {
templateStore store.TemplateStore templateStore store.TemplateStore
authorizer authz.Authorizer authorizer authz.Authorizer
spaceStore store.SpaceStore spaceFinder refcache.SpaceFinder
} }
func NewController( func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
templateStore store.TemplateStore, templateStore store.TemplateStore,
spaceStore store.SpaceStore, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return &Controller{ return &Controller{
templateStore: templateStore, templateStore: templateStore,
authorizer: authorizer, authorizer: authorizer,
spaceStore: spaceStore, spaceFinder: spaceFinder,
} }
} }

View File

@ -49,7 +49,7 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
parentSpace, err := c.spaceStore.FindByRef(ctx, in.SpaceRef) parentSpace, err := c.spaceFinder.FindByRef(ctx, in.SpaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find parent by ref: %w", err) return nil, fmt.Errorf("failed to find parent by ref: %w", err)
} }

View File

@ -30,7 +30,7 @@ func (c *Controller) Delete(
identifier string, identifier string,
resolverType enum.ResolverType, resolverType enum.ResolverType,
) error { ) error {
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return fmt.Errorf("failed to find space: %w", err) return fmt.Errorf("failed to find space: %w", err)
} }
@ -39,9 +39,11 @@ func (c *Controller) Delete(
if err != nil { if err != nil {
return fmt.Errorf("failed to authorize: %w", err) return fmt.Errorf("failed to authorize: %w", err)
} }
err = c.templateStore.DeleteByIdentifierAndType(ctx, space.ID, identifier, resolverType) err = c.templateStore.DeleteByIdentifierAndType(ctx, space.ID, identifier, resolverType)
if err != nil { if err != nil {
return fmt.Errorf("could not delete template: %w", err) return fmt.Errorf("could not delete template: %w", err)
} }
return nil return nil
} }

View File

@ -31,17 +31,20 @@ func (c *Controller) Find(
identifier string, identifier string,
resolverType enum.ResolverType, resolverType enum.ResolverType,
) (*types.Template, error) { ) (*types.Template, error) {
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }
err = apiauth.CheckTemplate(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionTemplateView) err = apiauth.CheckTemplate(ctx, c.authorizer, session, space.Path, identifier, enum.PermissionTemplateView)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to authorize: %w", err) return nil, fmt.Errorf("failed to authorize: %w", err)
} }
template, err := c.templateStore.FindByIdentifierAndType(ctx, space.ID, identifier, resolverType) template, err := c.templateStore.FindByIdentifierAndType(ctx, space.ID, identifier, resolverType)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find template: %w", err) return nil, fmt.Errorf("failed to find template: %w", err)
} }
return template, nil return template, nil
} }

View File

@ -47,7 +47,7 @@ func (c *Controller) Update(
return nil, fmt.Errorf("failed to sanitize input: %w", err) return nil, fmt.Errorf("failed to sanitize input: %w", err)
} }
space, err := c.spaceStore.FindByRef(ctx, spaceRef) space, err := c.spaceFinder.FindByRef(ctx, spaceRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find space: %w", err) return nil, fmt.Errorf("failed to find space: %w", err)
} }

View File

@ -30,9 +30,11 @@ func parseResolverType(data string) (enum.ResolverType, error) {
if err != nil { if err != nil {
return "", check.NewValidationError(fmt.Sprintf("could not parse template data: %s", err)) return "", check.NewValidationError(fmt.Sprintf("could not parse template data: %s", err))
} }
resolverTypeEnum, err := enum.ParseResolverType(config.Type) resolverTypeEnum, err := enum.ParseResolverType(config.Type)
if err != nil { if err != nil {
return "", check.NewValidationError(fmt.Sprintf("could not parse template type: %s", config.Type)) return "", check.NewValidationError(fmt.Sprintf("could not parse template type: %s", config.Type))
} }
return resolverTypeEnum, nil return resolverTypeEnum, nil
} }

View File

@ -16,6 +16,7 @@ package template
import ( import (
"github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/auth/authz"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store"
"github.com/google/wire" "github.com/google/wire"
@ -29,7 +30,7 @@ var WireSet = wire.NewSet(
func ProvideController( func ProvideController(
templateStore store.TemplateStore, templateStore store.TemplateStore,
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceStore store.SpaceStore, spaceFinder refcache.SpaceFinder,
) *Controller { ) *Controller {
return NewController(authorizer, templateStore, spaceStore) return NewController(authorizer, templateStore, spaceFinder)
} }

View File

@ -59,7 +59,7 @@ func (c *Controller) getRepoCheckPipelineAccess(
pipelineIdentifier string, pipelineIdentifier string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
repo, err := c.repoFinder.FindByRef(ctx, repoRef) repo, err := c.repoFinder.FindByRef(ctx, repoRef)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to find repo by ref: %w", err) return nil, fmt.Errorf("failed to find repo by ref: %w", err)

View File

@ -68,7 +68,7 @@ func (c *Controller) getRepoCheckAccess(ctx context.Context,
repoRef string, repoRef string,
permission enum.Permission, permission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, usererror.BadRequest("A valid repository reference must be provided.") return nil, usererror.BadRequest("A valid repository reference must be provided.")
} }

View File

@ -32,7 +32,7 @@ func createRPCWriteParams(
ctx context.Context, ctx context.Context,
urlProvider url.Provider, urlProvider url.Provider,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
isInternal bool, isInternal bool,
) (git.WriteParams, error) { ) (git.WriteParams, error) {
// generate envars (add everything githook CLI needs for execution) // generate envars (add everything githook CLI needs for execution)
@ -64,7 +64,7 @@ func CreateRPCExternalWriteParams(
ctx context.Context, ctx context.Context,
urlProvider url.Provider, urlProvider url.Provider,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
) (git.WriteParams, error) { ) (git.WriteParams, error) {
return createRPCWriteParams(ctx, urlProvider, session, repo, false) return createRPCWriteParams(ctx, urlProvider, session, repo, false)
} }
@ -75,7 +75,7 @@ func CreateRPCInternalWriteParams(
ctx context.Context, ctx context.Context,
urlProvider url.Provider, urlProvider url.Provider,
session *auth.Session, session *auth.Session,
repo *types.Repository, repo *types.RepositoryCore,
) (git.WriteParams, error) { ) (git.WriteParams, error) {
return createRPCWriteParams(ctx, urlProvider, session, repo, true) return createRPCWriteParams(ctx, urlProvider, session, repo, true)
} }

View File

@ -32,7 +32,7 @@ import (
type Controller struct { type Controller struct {
authorizer authz.Authorizer authorizer authz.Authorizer
spaceCache refcache.SpaceCache spaceFinder refcache.SpaceFinder
repoFinder refcache.RepoFinder repoFinder refcache.RepoFinder
webhookService *webhook.Service webhookService *webhook.Service
encrypter encrypt.Encrypter encrypter encrypt.Encrypter
@ -41,7 +41,7 @@ type Controller struct {
func NewController( func NewController(
authorizer authz.Authorizer, authorizer authz.Authorizer,
spaceCache refcache.SpaceCache, spaceFinder refcache.SpaceFinder,
repoFinder refcache.RepoFinder, repoFinder refcache.RepoFinder,
webhookService *webhook.Service, webhookService *webhook.Service,
encrypter encrypt.Encrypter, encrypter encrypt.Encrypter,
@ -49,7 +49,7 @@ func NewController(
) *Controller { ) *Controller {
return &Controller{ return &Controller{
authorizer: authorizer, authorizer: authorizer,
spaceCache: spaceCache, spaceFinder: spaceFinder,
repoFinder: repoFinder, repoFinder: repoFinder,
webhookService: webhookService, webhookService: webhookService,
encrypter: encrypter, encrypter: encrypter,
@ -64,7 +64,7 @@ func (c *Controller) getRepoCheckAccess(
repoRef string, repoRef string,
reqPermission enum.Permission, reqPermission enum.Permission,
allowedRepoStates ...enum.RepoState, allowedRepoStates ...enum.RepoState,
) (*types.Repository, error) { ) (*types.RepositoryCore, error) {
if repoRef == "" { if repoRef == "" {
return nil, errors.InvalidArgument("A valid repository reference must be provided.") return nil, errors.InvalidArgument("A valid repository reference must be provided.")
} }
@ -90,6 +90,6 @@ func (c *Controller) getSpaceCheckAccess(
session *auth.Session, session *auth.Session,
spaceRef string, spaceRef string,
permission enum.Permission, permission enum.Permission,
) (*types.Space, error) { ) (*types.SpaceCore, error) {
return space.GetSpaceCheckAuth(ctx, c.spaceCache, c.authorizer, session, spaceRef, permission) return space.GetSpaceCheckAuth(ctx, c.spaceFinder, c.authorizer, session, spaceRef, permission)
} }

View File

@ -29,12 +29,12 @@ var WireSet = wire.NewSet(
) )
func ProvideController(authorizer authz.Authorizer, func ProvideController(authorizer authz.Authorizer,
spaceCache refcache.SpaceCache, repoFinder refcache.RepoFinder, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder,
webhookService *webhook.Service, encrypter encrypt.Encrypter, webhookService *webhook.Service, encrypter encrypt.Encrypter,
preprocessor Preprocessor, preprocessor Preprocessor,
) *Controller { ) *Controller {
return NewController( return NewController(
authorizer, spaceCache, repoFinder, webhookService, encrypter, preprocessor) authorizer, spaceFinder, repoFinder, webhookService, encrypter, preprocessor)
} }
func ProvidePreprocessor() Preprocessor { func ProvidePreprocessor() Preprocessor {

Some files were not shown because too many files have changed in this diff Show More