-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
316 lines (262 loc) · 7.18 KB
/
schema.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
307
308
309
310
311
312
313
314
315
316
package sod
import (
"encoding/json"
"errors"
"fmt"
"os"
"reflect"
"time"
)
const (
SchemaFilename = "schema.json"
)
var (
ErrIndexCorrupted = errors.New("index is corrupted")
ErrBadSchema = errors.New("schema must be a file")
ErrMissingObjIndex = errors.New("schema is missing object index")
ErrStructureChanged = errors.New("object structure changed")
ErrExtensionMismatch = errors.New("extension mismatch")
ErrUnindexedField = errors.New("field is not indexed")
DefaultExtension = ".json"
DefaultCompression = false
DefaultSchema = Schema{
Extension: DefaultExtension,
Compress: DefaultCompression}
DefaultSchemaCompress = Schema{
Extension: DefaultExtension,
Compress: true}
compressedExtension = ".gz"
)
func IsIndexCorrupted(err error) bool {
return errors.Is(err, ErrIndexCorrupted)
}
type jsonAsync struct {
Enable bool `json:"enable"`
Threshold int `json:"threshold"`
Timeout string `json:"timeout"`
}
type Async struct {
routineStarted bool
Enable bool
Threshold int
Timeout time.Duration
}
func (a *Async) MarshalJSON() ([]byte, error) {
t := jsonAsync{
a.Enable,
a.Threshold,
a.Timeout.String(),
}
return json.Marshal(&t)
}
func (a *Async) UnmarshalJSON(b []byte) (err error) {
t := jsonAsync{}
if err = json.Unmarshal(b, &t); err != nil {
return
}
// copying fields
a.Enable = t.Enable
a.Threshold = t.Threshold
if a.Timeout, err = time.ParseDuration(t.Timeout); err != nil {
return
}
return
}
type Schema struct {
db *DB
object Object
transformers []FieldDescriptor
Fields FieldDescMap `json:"fields"`
Extension string `json:"extension"`
Compress bool `json:"compress"`
Cache bool `json:"cache"`
AsyncWrites *Async `json:"async-writes,omitempty"`
ObjectIndex *objIndex `json:"index"`
}
func NewCustomSchema(fields FieldDescMap, ext string) (s Schema) {
return Schema{
Extension: ext,
Fields: fields,
ObjectIndex: newIndex(fields),
}
}
// Asynchrone makes the data described by this schema managed asynchronously
// Objects will be written either if more than threshold events are modified
// or at every timeout
func (s *Schema) Asynchrone(threshold int, timeout time.Duration) {
s.AsyncWrites = &Async{
Enable: true,
Threshold: threshold,
Timeout: timeout}
}
// Indexed returns the FieldDescriptors of indexed fields
func (s *Schema) Indexed() (desc []FieldDescriptor) {
desc = make([]FieldDescriptor, 0)
for fpath := range s.ObjectIndex.Fields {
desc = append(desc, s.Fields[fpath])
}
return
}
func (s *Schema) initialize(db *DB, o Object) (err error) {
// initialize db using this schema
s.db = db
// initialize object associtated to the schema
s.object = o
// initialize fields
if s.Fields == nil {
s.Fields = FieldDescriptors(o)
}
// initializes the list of tranformers
s.transformers = s.Fields.Transformers()
// initializes ObjectsIndex if needed
if s.ObjectIndex == nil {
s.ObjectIndex = newIndex(s.Fields)
}
return
}
// prepare applies transform on search value
func (s *Schema) prepare(fpath string, value interface{}) {
if fd, ok := s.Fields[fpath]; ok {
// we transform search value only if we have a transformer constraint
if fd.Constraints.Transformer() {
fd.Transform(value)
}
}
}
// transform applies transform constraints defined in Schema
func (s *Schema) transform(o Object) {
// transform Object
for _, t := range s.transformers {
t.Transform(o)
}
}
func (s *Schema) makeTmpIndex() *objIndex {
return newIndex(s.Fields)
}
// index indexes an Object
func (s *Schema) index(o Object) error {
return s.ObjectIndex.insertOrUpdate(o)
}
func (s *Schema) isUUIDIndexed(uuid string) bool {
_, ok := s.ObjectIndex.uuids[uuid]
return ok
}
func (s *Schema) unindexByUUID(uuid string) {
s.ObjectIndex.deleteByUUID(uuid)
}
// Index un-indexes an Object
func (s *Schema) unindex(o Object) {
s.ObjectIndex.deleteByUUID(o.UUID())
}
func (s *Schema) filenameFromUUID(uuid string) string {
if s.Compress {
return fmt.Sprintf("%s%s%s", uuid, s.Extension, compressedExtension)
}
return fmt.Sprintf("%s%s", uuid, s.Extension)
}
func (s *Schema) filename(o Object) string {
return s.filenameFromUUID(o.UUID())
}
func (s *Schema) isCompatibleWith(other *Schema) (err error) {
// check if extension are compatible
if s.Extension != other.Extension {
return ErrExtensionMismatch
}
// check if FieldDescriptors are compatible
if err = s.Fields.CompatibleWith(other.Fields); err != nil {
return
}
return
}
func (s *Schema) update(from *Schema) (err error) {
// we check if both the schema are compatible
if err = s.isCompatibleWith(from); err != nil {
return
}
s.Cache = from.Cache
s.AsyncWrites = from.AsyncWrites
return
}
func (s *Schema) mustCache() bool {
return s.Cache || s.asyncWritesEnabled()
}
func (s *Schema) asyncWritesEnabled() bool {
if s.AsyncWrites != nil {
return s.AsyncWrites.Enable
}
return false
}
func (s *Schema) assignIndex(of Object, field string, target interface{}) (err error) {
var fi *fieldIndex
var ok bool
if fi, ok = s.ObjectIndex.Fields[field]; !ok {
return fmt.Errorf("%s %w", field, ErrUnindexedField)
}
index := fi.Index
vTarget := reflect.ValueOf(target)
if vTarget.Kind() == reflect.Ptr && !vTarget.IsZero() {
vTarget = vTarget.Elem()
t := reflect.TypeOf(target)
if vTarget.Kind() != reflect.Slice {
goto panic
}
// making a new slice for value pointed by target
vTarget.Set(reflect.MakeSlice(t.Elem(), len(index), len(index)))
for i := 0; i < len(index); i++ {
ov := reflect.ValueOf(index[i].Value)
switch {
case ov.CanFloat():
vTarget.Index(i).SetFloat(ov.Float())
continue
case ov.CanInt():
if t.Elem().Elem().AssignableTo(timeType) {
// time is currently encoded as int64 from UnixNano
vTarget.Index(i).Set(reflect.ValueOf(time.Unix(0, ov.Int())))
} else {
vTarget.Index(i).SetInt(ov.Int())
}
continue
case ov.CanUint():
vTarget.Index(i).SetUint(ov.Uint())
continue
default:
vTarget.Index(i).Set(ov)
}
}
return
}
panic:
panic("target must be a slice pointer")
}
func (s *Schema) control() (err error) {
var uuids map[string]bool
dir := s.db.oDir(s.object)
// control that object structure did not change
if err := s.Fields.FieldsCompatibleWith(FieldDescriptors(s.object)); err != nil {
return fmt.Errorf("%T %w: %s", s.object, ErrStructureChanged, err)
}
// controlling index in memory
if err = s.ObjectIndex.control(); err != nil {
return
}
// verifying index integrity (longer process so done at last)
// we control any index corruption
if uuids, err = uuidsFromDir(dir); err != nil && !os.IsNotExist(err) {
return
}
// we iterate over all the uuids found on disk
for uuid := range uuids {
// if file is on disk but not indexed
if !s.isUUIDIndexed(uuid) {
return fmt.Errorf("%s %w: schema index is missing entry", typeof(s.object), ErrIndexCorrupted)
}
}
// we de-index missing objects
for uuid := range s.ObjectIndex.uuids {
if !uuids[uuid] {
return fmt.Errorf("%s %w: object deleted but still indexed", typeof(s.object), ErrIndexCorrupted)
}
}
// force nil otherwise takes NoExist error skipped above
return nil
}