store

package
v1.3.0-rc2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ConstraintAuthProviderOIDCUnique   = "idx_authproviders_oidc_unique"
	ConstraintAuthProviderOAuth2Unique = "idx_authproviders_oauth2_unique"
)

AuthProvider database constraint names

View Source
const (
	SortByName      SortColumn = "name"
	SortByCreatedAt SortColumn = "created_at"

	// Sort columns for vulnerability queries.
	SortByOwner          SortColumn = "owner"
	SortByDeviceAffected SortColumn = "device_affected"
	SortBySeverity       SortColumn = "severity"
	SortByCvssScore      SortColumn = "cvss_score"
	SortByPublishedAt    SortColumn = "published_at"
	SortByCveId          SortColumn = "cve_id"

	SortAsc  SortOrder = "asc"
	SortDesc SortOrder = "desc"
)

Variables

View Source
var (
	NullOrgId              = org.DefaultID
	CurrentContinueVersion = 1
)
View Source
var ErrMutateSkipWrite = errors.New("mutate skip write")

ErrMutateSkipWrite tells a store Mutate implementation to return success without persisting, when a handler's apply closure determines there is nothing to write.

Functions

func AddPaginationToQuery

func AddPaginationToQuery(query *gorm.DB, limit int, cont *Continue, listParams ListParams) *gorm.DB

func ApplyObjectMetaUpdate added in v1.3.0

func ApplyObjectMetaUpdate(current, resource *domain.ObjectMeta, fieldsToUnset []string)

ApplyObjectMetaUpdate copies labels/annotations/owner from resource onto current, preserving nil fields unless listed in fieldsToUnset. Generation and ResourceVersion are server-managed and are not copied; callers that need RV preconditions should use CheckResourceVersionConflict (or equivalent) before applying.

func BuildContinueString added in v0.8.1

func BuildContinueString(names []string, count int64) *string

func CallEventCallback added in v0.9.0

func CallEventCallback(resourceKind domain.ResourceKind, log logrus.FieldLogger) func(ctx context.Context, callbackEvent EventCallback, orgId uuid.UUID, name string, oldResource, newResource interface{}, created bool, err error)

func CheckHealth added in v1.3.0

func CheckHealth(ctx context.Context, db *gorm.DB) error

CheckHealth verifies database connectivity and basic read capability. It depends only on *gorm.DB, not on any per-resource store, so composition roots that no longer construct the monolithic Store can still perform a DB health check.

func CloneJSON added in v1.3.0

func CloneJSON[A any](v *A) (*A, error)

CloneJSON deep-copies v via JSON marshal/unmarshal. Fields tagged json:"-" are not preserved.

func CountRemainingItems

func CountRemainingItems(query *gorm.DB, nextValues []string, listParams ListParams) int64

func ErrorFromGormError added in v0.3.0

func ErrorFromGormError(err error) error

ErrorFromGormError translates well-known gorm errors into domain-specific errors. Delegated to storeutil so that packages outside internal/store can reuse the logic.

func GetNonNilFieldsFromResource

func GetNonNilFieldsFromResource(resource model.Resource) []string

func InitDB

func InitDB(cfg *config.Config, log *logrus.Logger) (*gorm.DB, error)

func InitMigrationDB added in v0.9.0

func InitMigrationDB(cfg *config.Config, log *logrus.Logger) (*gorm.DB, error)

func ListQuery added in v0.3.0

func ListQuery(dest any, opts ...ListQueryOption) *listQuery

func MergeAnnotations added in v1.3.0

func MergeAnnotations(current *map[string]string, annotations map[string]string, deleteKeys []string) map[string]string

MergeAnnotations merges annotations and applies deleteKeys.

func NewTraceContextEnforcer added in v0.8.1

func NewTraceContextEnforcer() gorm.Plugin

func RetryUpdate added in v1.3.0

func RetryUpdate(fn func() (bool, error)) error

RetryUpdate runs fn until it returns retry=false or retryIterations is exhausted.

func SafeEventCallback added in v0.9.0

func SafeEventCallback(log logrus.FieldLogger, callback func())

Call callback if provided (but don't fail the operation if callback fails) with panic recovery to prevent callback failures from affecting the main operation

func WithBypassSpanCheck added in v0.8.1

func WithBypassSpanCheck(ctx context.Context) context.Context

WithBypassSpanCheck returns a child context that disables span enforcement.

Types

type ApplyFunc added in v1.3.0

type ApplyFunc[A any] func(m ResourceMutation[A]) error

ApplyFunc mutates m on every Mutate attempt.

type Continue

type Continue struct {
	Version int
	Names   []string
	Count   int64
}

func ParseContinueString

func ParseContinueString(contStr *string) (*Continue, error)

type CountByOrgResult added in v0.10.0

type CountByOrgResult struct {
	OrgID string
	Count int64
}

CountByOrgResult holds the result of the group by query for organization.

type CreateOrUpdateMode added in v0.2.0

type CreateOrUpdateMode string
const (
	ModeCreateOnly     CreateOrUpdateMode = "create-only"
	ModeUpdateOnly     CreateOrUpdateMode = "update-only"
	ModeCreateOrUpdate CreateOrUpdateMode = "create-or-update"
)

type DBHealthChecker added in v1.3.0

type DBHealthChecker struct {
	DB *gorm.DB
}

DBHealthChecker adapts CheckHealth to the api_server.HealthChecker interface without requiring a full Store.

func (*DBHealthChecker) CheckHealth added in v1.3.0

func (h *DBHealthChecker) CheckHealth(ctx context.Context) error

type EventCallback added in v0.9.0

type EventCallback func(ctx context.Context, resourceKind domain.ResourceKind, orgId uuid.UUID, name string, oldResource, newResource interface{}, created bool, err error)

type EventCallbackCaller added in v0.9.0

type EventCallbackCaller func(ctx context.Context, callbackEvent EventCallback, orgId uuid.UUID, name string, oldResource, newResource interface{}, created bool, err error)

type GenericStore added in v0.4.0

type GenericStore[P extInt[M], M any, A any, AL any] struct {

	// Callback for integration tests to inject logic
	IntegrationTestCreateOrUpdateCallback IntegrationTestCallback
	// contains filtered or unexported fields
}

GenericStore provides generic CRUD operations for resources P is a pointer to a model, for example: *model.Device M is the model, for example: model.Device A is the API resource, for example: domain.Device AL is the API list, for example: domain.DeviceList

func NewGenericStore added in v0.4.0

func NewGenericStore[P extInt[M], M any, A any, AL any](
	db *gorm.DB,
	log logrus.FieldLogger,
	apiToModelPtr func(*A) (P, error),
	modelPtrToAPI func(P, ...model.APIResourceOption) (*A, error),
	listModelToAPI func([]M, *string, *int64) (AL, error),
) *GenericStore[P, M, A, AL]

func (*GenericStore[P, M, A, AL]) Create added in v0.4.0

func (s *GenericStore[P, M, A, AL]) Create(ctx context.Context, orgId uuid.UUID, resource *A) (*A, error)

func (*GenericStore[P, M, A, AL]) CreateOrUpdate added in v0.4.0

func (s *GenericStore[P, M, A, AL]) CreateOrUpdate(ctx context.Context, orgId uuid.UUID, resource *A, fieldsToUnset []string, validationCallback func(ctx context.Context, before, after *A) error) (*A, *A, bool, error)

func (*GenericStore[P, M, A, AL]) Delete added in v0.4.0

func (s *GenericStore[P, M, A, AL]) Delete(ctx context.Context, resource M, associatedResources ...Resource) (bool, error)

func (*GenericStore[P, M, A, AL]) Get added in v0.4.0

func (s *GenericStore[P, M, A, AL]) Get(ctx context.Context, orgId uuid.UUID, name string) (*A, error)

func (*GenericStore[P, M, A, AL]) List added in v0.4.0

func (s *GenericStore[P, M, A, AL]) List(ctx context.Context, orgId uuid.UUID, listParams ListParams) (*AL, error)

func (*GenericStore[P, M, A, AL]) Mutate added in v1.3.0

func (s *GenericStore[P, M, A, AL]) Mutate(
	ctx context.Context,
	orgId uuid.UUID,
	name string,
	previous *A,
	hooks MutateHooks[A],
	apply ApplyFunc[A],
) (updated *A, before *A, created bool, err error)

Mutate runs the shared read-modify-write loop: load (or use previous once), Wrap into ResourceMutation, Clone on update, apply, then PersistCreate or PersistUpdate. Handlers should call type-store Mutate wrappers, not this method directly.

func (*GenericStore[P, M, A, AL]) Update added in v0.4.0

func (s *GenericStore[P, M, A, AL]) Update(ctx context.Context, orgId uuid.UUID, resource *A, fieldsToUnset []string, validationCallback func(ctx context.Context, before, after *A) error) (*A, *A, error)

func (*GenericStore[P, M, A, AL]) UpdateStatus added in v0.4.0

func (s *GenericStore[P, M, A, AL]) UpdateStatus(ctx context.Context, orgId uuid.UUID, resource *A) (*A, error)

type IntegrationTestCallback

type IntegrationTestCallback func()

type ListParams

type ListParams struct {
	Limit              int
	Continue           *Continue
	FieldSelector      *selector.FieldSelector
	LabelSelector      *selector.LabelSelector
	AnnotationSelector *selector.AnnotationSelector
	SortOrder          *SortOrder
	SortColumns        []SortColumn
}

type ListQueryOption added in v0.5.0

type ListQueryOption func(*listQuery)

func WithSelectorResolver added in v0.5.0

func WithSelectorResolver(resolver selector.Resolver) ListQueryOption

type MutateHooks added in v1.3.0

type MutateHooks[A any] struct {
	// Wrap turns a loaded API object into the typed mutation. Wrap(nil) is the create path.
	// Required.
	Wrap func(*A) ResourceMutation[A]
	// Load fetches the current resource when previous is unset / on retry.
	// Return (nil, nil) when not found (create path). When nil, GenericStore uses loadByName.
	Load func(ctx context.Context, orgId uuid.UUID, name string) (*A, error)
	// PersistCreate inserts after apply on the create path.
	// Defaults to GenericStore.Create on m.Resource().
	PersistCreate func(ctx context.Context, orgId uuid.UUID, m ResourceMutation[A]) (*A, error)
	// PersistUpdate writes after apply on the update path. Required.
	// Returns retry=true on conflict / deadlock so Mutate can reload and retry.
	PersistUpdate func(ctx context.Context, orgId uuid.UUID, name string, before *A, m ResourceMutation[A]) (retry bool, err error)
}

MutateHooks customizes wrap and persist for a resource type. GenericStore.Mutate owns only the load/apply/retry control loop.

type Mutation added in v1.3.0

type Mutation[A any] struct {
	// contains filtered or unexported fields
}

Mutation is a ResourceMutation that only carries the API resource.

func (*Mutation[A]) Clone added in v1.3.0

func (m *Mutation[A]) Clone() (ResourceMutation[A], error)

func (*Mutation[A]) RequireExisting added in v1.3.0

func (m *Mutation[A]) RequireExisting() error

RequireExisting returns ErrResourceNotFound when Resource is nil (create path).

func (*Mutation[A]) Resource added in v1.3.0

func (m *Mutation[A]) Resource() *A

func (*Mutation[A]) SetResource added in v1.3.0

func (m *Mutation[A]) SetResource(resource *A)

type RemoveOwnerCallback added in v0.10.0

type RemoveOwnerCallback func(ctx context.Context, tx *gorm.DB, orgId uuid.UUID, owner string) error

type Resource added in v0.4.0

type Resource struct {
	Table string
	OrgID string
	Name  string
}

type ResourceMutation added in v1.3.0

type ResourceMutation[A any] interface {
	Resource() *A
	SetResource(*A)
	Clone() (ResourceMutation[A], error)
}

ResourceMutation is the unit GenericStore.Mutate applies and persists. It may be richer than A (e.g. device rendered_* side channel). Resource is nil on the create path until apply assigns it.

type SortColumn added in v0.8.1

type SortColumn string

type SortOrder added in v0.3.0

type SortOrder string

type StatusCount

type StatusCount struct {
	Category      string
	StatusSummary string
	Count         int64
}

type StatusCountList added in v0.3.0

type StatusCountList []StatusCount

func CountStatusList added in v0.3.0

func CountStatusList(ctx context.Context, query *gorm.DB, status ...string) (StatusCountList, error)

func (StatusCountList) List added in v0.3.0

func (s StatusCountList) List(status string) map[string]int64

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL