summaryrefslogtreecommitdiffstats
path: root/pkg/common/sync_subject.go
blob: a39d6df6dc97f648f58034ff35995581bc2b1152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package common

import (
	"github.com/icinga/icingadb/pkg/contracts"
	v1 "github.com/icinga/icingadb/pkg/icingadb/v1"
	"github.com/icinga/icingadb/pkg/utils"
)

// SyncSubject defines information about entities to be synchronized.
type SyncSubject struct {
	entity       contracts.Entity
	factory      contracts.EntityFactoryFunc
	withChecksum bool
}

// NewSyncSubject returns a new SyncSubject.
func NewSyncSubject(factoryFunc contracts.EntityFactoryFunc) *SyncSubject {
	e := factoryFunc()

	var factory contracts.EntityFactoryFunc
	if _, ok := e.(contracts.Initer); ok {
		factory = func() contracts.Entity {
			e := factoryFunc()
			e.(contracts.Initer).Init()

			return e
		}
	} else {
		factory = factoryFunc
	}

	_, withChecksum := e.(contracts.Checksumer)

	return &SyncSubject{
		entity:       e,
		factory:      factory,
		withChecksum: withChecksum,
	}
}

// Entity returns one value from the factory. Always returns the same entity.
func (s SyncSubject) Entity() contracts.Entity {
	return s.entity
}

// Factory returns the entity factory function that calls Init() on the created contracts.Entity if applicable.
func (s SyncSubject) Factory() contracts.EntityFactoryFunc {
	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() contracts.EntityFactoryFunc {
	if s.withChecksum {
		return v1.NewEntityWithChecksum
	}

	return s.factory
}

// Name returns the declared name of the entity.
func (s SyncSubject) Name() string {
	return utils.Name(s.entity)
}

// WithChecksum returns whether entities from the factory implement contracts.Checksumer.
func (s SyncSubject) WithChecksum() bool {
	return s.withChecksum
}