store

package
v1.4.0-rc3 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

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

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"
)
View Source
const OsModeStatusSelector = "status.systemInfo.osMode" + StatusCountCoalesceSeparator + "status.capabilities.osMode"

OsModeStatusSelector is the CountStatusList selector for device OS-mode breakdowns. It prefers status.systemInfo.osMode and falls back to the deprecated status.capabilities.osMode for devices reported by older agents, mirroring domain.DeviceStatusOsMode.

View Source
const StatusCountCoalesceSeparator = "||"

StatusCountCoalesceSeparator joins the JSON paths that make up a compound CountStatusList selector such as OsModeStatusSelector. It keeps the selector key self-documenting about which paths it coalesces; the SQL that a selector resolves to is taken from the statusCountSelectorSQL allowlist, never parsed or built from the key at runtime.

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 DB added in v1.4.0

func DB(ctx context.Context, fallback *gorm.DB) *gorm.DB

DB returns the transaction from ctx when one is active; otherwise fallback.WithContext(ctx).

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 InTransaction added in v1.4.0

func InTransaction(ctx context.Context) bool

InTransaction reports whether ctx carries an active store transaction.

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 RunInTransaction added in v1.4.0

func RunInTransaction(ctx context.Context, db *gorm.DB, fn func(tx *gorm.DB) error) error

RunInTransaction runs fn on the active TX from ctx when present; otherwise starts a new transaction on db. This preserves caller-owned TX semantics (e.g. service delete + owner cleanup) without nesting a committing inner TX.

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.

func WithTransaction added in v1.4.0

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

WithTransaction starts a DB transaction, stores it in ctx, and runs fn. Store methods that use DB(ctx, ...) or RunInTransaction join this TX.

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]) ListWithQuery added in v1.4.0

func (s *GenericStore[P, M, A, AL]) ListWithQuery(ctx context.Context, orgId uuid.UUID, listParams ListParams, modify ListQueryModifier) (*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 ListQueryModifier added in v1.4.0

type ListQueryModifier func(*gorm.DB) *gorm.DB

ListQueryModifier adds resource-specific predicates to a generic list query. The modifier is applied to both the result query and the count query used for continuation tokens.

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 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

Directories

Path Synopsis
Package enrollmenthooknotifysecrets is a generated GoMock package.
Package enrollmenthooknotifysecrets is a generated GoMock package.
Package labelsyncmapping is a generated GoMock package.
Package labelsyncmapping is a generated GoMock package.

Jump to

Keyboard shortcuts

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