icingadb/pkg/common/sync_subject.go

73 lines
2 KiB
Go
Raw Permalink Normal View History

2021-04-21 05:26:05 -04:00
package common
import (
2024-05-22 05:47:44 -04:00
"github.com/icinga/icinga-go-library/database"
"github.com/icinga/icinga-go-library/types"
2021-04-21 05:26:05 -04:00
"github.com/icinga/icingadb/pkg/contracts"
v1 "github.com/icinga/icingadb/pkg/icingadb/v1"
2021-04-21 05:26:05 -04:00
)
// SyncSubject defines information about entities to be synchronized.
type SyncSubject struct {
entity database.Entity
factory database.EntityFactoryFunc
2021-04-21 05:26:05 -04:00
withChecksum bool
}
// NewSyncSubject returns a new SyncSubject.
func NewSyncSubject(factoryFunc database.EntityFactoryFunc) *SyncSubject {
2021-04-21 05:26:05 -04:00
e := factoryFunc()
var factory database.EntityFactoryFunc
if _, ok := e.(contracts.Initer); ok {
factory = func() database.Entity {
e := factoryFunc()
e.(contracts.Initer).Init()
return e
}
} else {
factory = factoryFunc
}
2021-04-21 05:26:05 -04:00
_, withChecksum := e.(contracts.Checksumer)
return &SyncSubject{
entity: e,
factory: factory,
2021-04-21 05:26:05 -04:00
withChecksum: withChecksum,
}
}
// Entity returns one value from the factory. Always returns the same entity.
func (s SyncSubject) Entity() database.Entity {
2021-04-21 05:26:05 -04:00
return s.entity
}
// Factory returns the entity factory function that calls Init() on the created contracts.Entity if applicable.
func (s SyncSubject) Factory() database.EntityFactoryFunc {
2021-04-21 05:26:05 -04:00
return s.factory
}
// FactoryForDelta behaves like Factory() unless s is WithChecksum().
// In the latter case it returns a factory for EntityWithChecksum instead.
// Rationale: Sync#ApplyDelta() uses its input entities which are WithChecksum() only for the delta itself
// and not for insertion into the database, so EntityWithChecksum is enough. And it consumes less memory.
func (s SyncSubject) FactoryForDelta() database.EntityFactoryFunc {
if s.withChecksum {
return v1.NewEntityWithChecksum
}
return s.factory
}
2021-10-04 07:54:26 -04:00
// Name returns the declared name of the entity.
func (s SyncSubject) Name() string {
2024-05-21 05:49:34 -04:00
return types.Name(s.entity)
2021-10-04 07:54:26 -04:00
}
2021-04-21 05:26:05 -04:00
// WithChecksum returns whether entities from the factory implement contracts.Checksumer.
func (s SyncSubject) WithChecksum() bool {
return s.withChecksum
}