-
Notifications
You must be signed in to change notification settings - Fork 159
/
base_model.go
306 lines (253 loc) · 8.64 KB
/
base_model.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
Copyright NetFoundry Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
import (
"github.com/michaelquigley/pfxlog"
"github.com/openziti/foundation/v2/errorz"
"github.com/openziti/storage/ast"
"github.com/openziti/storage/boltz"
"github.com/pkg/errors"
"go.etcd.io/bbolt"
"reflect"
"time"
)
const (
ListLimitMax = 500
ListOffsetMax = 100000
ListLimitDefault = 10
ListOffsetDefault = 0
)
type EntityRetriever[T Entity] interface {
BaseLoad(id string) (T, error)
BaseLoadInTx(tx *bbolt.Tx, id string) (T, error)
BaseList(query string) (*EntityListResult[T], error)
BasePreparedList(query ast.Query) (*EntityListResult[T], error)
ListWithHandler(query string, handler ListResultHandler) error
PreparedListWithHandler(query ast.Query, handler ListResultHandler) error
PreparedListAssociatedWithHandler(id string, association string, query ast.Query, handler ListResultHandler) error
GetListStore() boltz.Store
// GetEntityTypeId returns a unique id for the entity type. Some entities may share a storage type, such
// as fabric and edge services, and fabric and edge routers. However, they should have distinct entity type
// ids, so we can figure out to which controller to route commands
GetEntityTypeId() string
}
type Entity interface {
GetId() string
SetId(string)
GetCreatedAt() time.Time
GetUpdatedAt() time.Time
GetTags() map[string]interface{}
IsSystemEntity() bool
}
type NameIndexedStore interface {
boltz.Store
GetNameIndex() boltz.ReadIndex
}
type BaseEntity struct {
Id string
CreatedAt time.Time
UpdatedAt time.Time
Tags map[string]interface{}
IsSystem bool
}
func (entity *BaseEntity) GetId() string {
return entity.Id
}
func (entity *BaseEntity) SetId(id string) {
entity.Id = id
}
func (entity *BaseEntity) GetCreatedAt() time.Time {
return entity.CreatedAt
}
func (entity *BaseEntity) GetUpdatedAt() time.Time {
return entity.UpdatedAt
}
func (entity *BaseEntity) GetTags() map[string]interface{} {
return entity.Tags
}
func (entity *BaseEntity) IsSystemEntity() bool {
return entity.IsSystem
}
func (entity *BaseEntity) FillCommon(boltEntity boltz.ExtEntity) {
entity.Id = boltEntity.GetId()
entity.CreatedAt = boltEntity.GetCreatedAt()
entity.UpdatedAt = boltEntity.GetUpdatedAt()
entity.Tags = boltEntity.GetTags()
entity.IsSystem = boltEntity.IsSystemEntity()
}
func (entity *BaseEntity) ToBoltBaseExtEntity() *boltz.BaseExtEntity {
return &boltz.BaseExtEntity{
Id: entity.Id,
CreatedAt: entity.CreatedAt,
UpdatedAt: entity.UpdatedAt,
Tags: entity.Tags,
IsSystem: entity.IsSystem,
}
}
type EntityListResult[T Entity] struct {
Loader interface {
BaseLoadInTx(tx *bbolt.Tx, id string) (T, error)
}
Entities []T
QueryMetaData
}
func (result *EntityListResult[T]) GetEntities() []T {
return result.Entities
}
func (result *EntityListResult[T]) GetMetaData() *QueryMetaData {
return &result.QueryMetaData
}
func (result *EntityListResult[T]) Collect(tx *bbolt.Tx, ids []string, queryMetaData *QueryMetaData) error {
result.QueryMetaData = *queryMetaData
for _, key := range ids {
entity, err := result.Loader.BaseLoadInTx(tx, key)
if err != nil {
return err
}
result.Entities = append(result.Entities, entity)
}
return nil
}
type QueryMetaData struct {
Count int64
Limit int64
Offset int64
FilterableFields []string
}
type BaseEntityManager[E boltz.ExtEntity] struct {
Store boltz.EntityStore[E]
}
func (ctrl *BaseEntityManager[E]) GetStore() boltz.EntityStore[E] {
return ctrl.Store
}
func (ctrl *BaseEntityManager[E]) GetListStore() boltz.Store {
return ctrl.Store
}
type ListResultHandler func(tx *bbolt.Tx, ids []string, qmd *QueryMetaData) error
func (ctrl *BaseEntityManager[E]) checkLimits(query ast.Query) {
if query.GetLimit() == nil || *query.GetLimit() < -1 || *query.GetLimit() == 0 {
query.SetLimit(ListLimitDefault)
} else if *query.GetLimit() > ListLimitMax {
query.SetLimit(ListLimitMax)
}
if query.GetSkip() == nil || *query.GetSkip() < 0 {
query.SetSkip(ListOffsetDefault)
} else if *query.GetSkip() > ListOffsetMax {
query.SetSkip(ListOffsetMax)
}
}
func (ctrl *BaseEntityManager[E]) ListWithTx(tx *bbolt.Tx, queryString string, resultHandler ListResultHandler) error {
query, err := ast.Parse(ctrl.Store, queryString)
if err != nil {
return err
}
return ctrl.PreparedListWithTx(tx, query, resultHandler)
}
func (ctrl *BaseEntityManager[E]) PreparedListWithTx(tx *bbolt.Tx, query ast.Query, resultHandler ListResultHandler) error {
ctrl.checkLimits(query)
keys, count, err := ctrl.Store.QueryIdsC(tx, query)
if err != nil {
return err
}
qmd := &QueryMetaData{
Count: count,
Limit: *query.GetLimit(),
Offset: *query.GetSkip(),
FilterableFields: ctrl.Store.GetPublicSymbols(),
}
return resultHandler(tx, keys, qmd)
}
func (ctrl *BaseEntityManager[E]) PreparedListAssociatedWithTx(tx *bbolt.Tx, id, association string, query ast.Query, resultHandler ListResultHandler) error {
ctrl.checkLimits(query)
var count int64
var keys []string
var err error
symbol := ctrl.GetStore().GetSymbol(association)
if symbol == nil {
return errors.Errorf("invalid association: '%v'", association)
}
linkedType := symbol.GetLinkedType()
if linkedType == nil {
return errors.Errorf("invalid association: '%v'", association)
}
cursorProvider := func(tx *bbolt.Tx, forward bool) ast.SetCursor {
return symbol.GetStore().GetRelatedEntitiesCursor(tx, id, association, forward)
}
if keys, count, err = linkedType.QueryWithCursorC(tx, cursorProvider, query); err != nil {
return err
}
qmd := &QueryMetaData{
Count: count,
Limit: *query.GetLimit(),
Offset: *query.GetSkip(),
FilterableFields: linkedType.GetPublicSymbols(),
}
return resultHandler(tx, keys, qmd)
}
func (ctrl *BaseEntityManager[E]) PreparedListIndexedWithTx(tx *bbolt.Tx, cursorProvider ast.SetCursorProvider, query ast.Query, resultHandler ListResultHandler) error {
ctrl.checkLimits(query)
keys, count, err := ctrl.Store.QueryWithCursorC(tx, cursorProvider, query)
if err != nil {
return err
}
qmd := &QueryMetaData{
Count: count,
Limit: *query.GetLimit(),
Offset: *query.GetSkip(),
FilterableFields: ctrl.Store.GetPublicSymbols(),
}
return resultHandler(tx, keys, qmd)
}
type Named interface {
GetName() string
}
func (ctrl *BaseEntityManager[E]) ValidateNameOnUpdate(ctx boltz.MutateContext, updatedEntity, existingEntity boltz.Entity, checker boltz.FieldChecker) error {
// validate name for named entities
if namedEntity, ok := updatedEntity.(boltz.NamedExtEntity); ok {
existingNamed := existingEntity.(boltz.NamedExtEntity)
if (checker == nil || checker.IsUpdated("name")) && namedEntity.GetName() != existingNamed.GetName() {
if namedEntity.GetName() == "" {
return errorz.NewFieldError("name is required", "name", namedEntity.GetName())
}
if nameIndexStore, ok := ctrl.GetStore().(NameIndexedStore); ok {
if nameIndexStore.GetNameIndex().Read(ctx.Tx(), []byte(namedEntity.GetName())) != nil {
return errorz.NewFieldError("name is must be unique", "name", namedEntity.GetName())
}
} else {
pfxlog.Logger().Errorf("entity of type %v is named, but store doesn't have name index", reflect.TypeOf(updatedEntity))
}
}
}
return nil
}
func (handler *BaseEntityManager[E]) ValidateName(db boltz.Db, boltEntity Named) error {
return db.View(func(tx *bbolt.Tx) error {
return handler.ValidateNameOnCreate(tx, boltEntity)
})
}
func (handler *BaseEntityManager[E]) ValidateNameOnCreate(tx *bbolt.Tx, entity interface{}) error {
// validate name for named entities
if namedEntity, ok := entity.(Named); ok {
if namedEntity.GetName() == "" {
return errorz.NewFieldError("name is required", "name", namedEntity.GetName())
}
if nameIndexStore, ok := handler.GetStore().(NameIndexedStore); ok {
if nameIndexStore.GetNameIndex().Read(tx, []byte(namedEntity.GetName())) != nil {
return errorz.NewFieldError("name is must be unique", "name", namedEntity.GetName())
}
} else {
pfxlog.Logger().Errorf("entity of type %v is named, but store doesn't have name index", reflect.TypeOf(entity))
}
}
return nil
}