forked from cloudwan/gohan
/
schema.go
545 lines (480 loc) · 15.5 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (C) 2015 NTT Innovation Institute, 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
//
// http://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 schema
import (
"fmt"
"strings"
"github.com/cloudwan/gohan/util"
"github.com/flosch/pongo2"
"github.com/xeipuuv/gojsonschema"
)
//Schema type for defining data type
type Schema struct {
ID, Plural, Title, Description string
Type string
Extends []string
ParentSchema *Schema
Parent string
NamespaceID string
Namespace *Namespace
Metadata map[string]interface{}
Prefix string
Properties []Property
JSONSchema map[string]interface{}
JSONSchemaOnCreate map[string]interface{}
JSONSchemaOnUpdate map[string]interface{}
Actions []Action
Singular string
URL string
URLWithParents string
RawData interface{}
IsolationLevel map[string]interface{}
OnParentDeleteCascade bool
}
const (
abstract string = "abstract"
)
//Schemas is a list of schema
//This struct is needed for json decode
type Schemas struct {
Schemas []*Schema
}
//Map is a map of schema
type Map map[string]*Schema
type typeAssertionError struct {
field string
}
func (e *typeAssertionError) Error() string {
return fmt.Sprintf("Type Assertion Error: invalid schema %v field", e.field)
}
//NewSchema is a constructor for a schema
func NewSchema(id, plural, title, description, singular string) *Schema {
schema := &Schema{
ID: id,
Title: title,
Plural: plural,
Description: description,
Singular: singular,
Extends: []string{},
}
return schema
}
//NewSchemaFromObj is a constructor for a schema by obj
func NewSchemaFromObj(rawTypeData interface{}) (*Schema, error) {
metaschema, _ := GetManager().Schema("schema")
return newSchemaFromObj(rawTypeData, metaschema)
}
func newSchemaFromObj(rawTypeData interface{}, metaschema *Schema) (*Schema, error) {
typeData := rawTypeData.(map[string]interface{})
if metaschema != nil {
err := metaschema.Validate(metaschema.JSONSchema, typeData)
if err != nil {
return nil, err
}
}
id := util.MaybeString(typeData["id"])
if id == "" {
return nil, &typeAssertionError{"id"}
}
plural := util.MaybeString(typeData["plural"])
if plural == "" {
return nil, &typeAssertionError{"plural"}
}
title := util.MaybeString(typeData["title"])
if title == "" {
return nil, &typeAssertionError{"title"}
}
description := util.MaybeString(typeData["description"])
if description == "" {
return nil, &typeAssertionError{"description"}
}
singular := util.MaybeString(typeData["singular"])
if singular == "" {
return nil, &typeAssertionError{"singular"}
}
schema := NewSchema(id, plural, title, description, singular)
schema.Prefix = util.MaybeString(typeData["prefix"])
schema.URL = util.MaybeString(typeData["url"])
schema.Type = util.MaybeString(typeData["type"])
schema.Parent = util.MaybeString(typeData["parent"])
schema.OnParentDeleteCascade, _ = typeData["on_parent_delete_cascade"].(bool)
schema.NamespaceID = util.MaybeString(typeData["namespace"])
schema.IsolationLevel = util.MaybeMap(typeData["isolation_level"])
jsonSchema, ok := typeData["schema"].(map[string]interface{})
if !ok {
return nil, &typeAssertionError{"schema"}
}
schema.JSONSchema = jsonSchema
schema.Metadata = util.MaybeMap(typeData["metadata"])
schema.Extends = util.MaybeStringList(typeData["extends"])
actions := util.MaybeMap(typeData["actions"])
schema.Actions = []Action{}
for actionID, actionBody := range actions {
action, err := NewActionFromObject(actionID, actionBody)
if err != nil {
return nil, err
}
schema.Actions = append(schema.Actions, action)
}
if err := schema.Init(); err != nil {
return nil, err
}
return schema, nil
}
// Init initializes schema
func (schema *Schema) Init() error {
if schema.IsAbstract() {
return nil
}
jsonSchema := schema.JSONSchema
parent := schema.Parent
required := util.MaybeStringList(jsonSchema["required"])
properties := util.MaybeMap(jsonSchema["properties"])
propertiesOrder := util.MaybeStringList(jsonSchema["propertiesOrder"])
if parent != "" && properties[FormatParentID(parent)] == nil {
properties[FormatParentID(parent)] = getParentPropertyObj(parent, parent)
propertiesOrder = append(propertiesOrder, FormatParentID(parent))
required = append(required, FormatParentID(parent))
}
jsonSchema["required"] = required
schema.JSONSchemaOnCreate = filterSchemaByPermission(jsonSchema, "create")
schema.JSONSchemaOnUpdate = filterSchemaByPermission(jsonSchema, "update")
schema.Properties = []Property{}
for key := range properties {
if !util.ContainsString(propertiesOrder, key) {
propertiesOrder = append(propertiesOrder, key)
}
}
jsonSchema["propertiesOrder"] = propertiesOrder
for _, id := range propertiesOrder {
property, ok := properties[id]
if !ok {
continue
}
propertyRequired := util.ContainsString(required, id)
propertyObj, err := NewPropertyFromObj(id, property, propertyRequired)
if err != nil {
return fmt.Errorf("Invalid schema: Properties is missing %v", err)
}
schema.Properties = append(schema.Properties, *propertyObj)
}
return nil
}
// IsAbstract checks if this schema is abstract or not
func (schema *Schema) IsAbstract() bool {
return schema.Type == abstract
}
// ParentID returns parent property ID
func (schema *Schema) ParentID() string {
if schema.Parent == "" {
return ""
}
return FormatParentID(schema.Parent)
}
// GetSingleURL returns a URL for access to a single schema object
func (schema *Schema) GetSingleURL() string {
return fmt.Sprintf("%s/:id", schema.URL)
}
// GetActionURL returns a URL for access to resources actions
func (schema *Schema) GetActionURL(path string) string {
return schema.URL + path
}
// GetActionURLWithParents returns a URL for access to resources actions with parent suffix
func (schema *Schema) GetActionURLWithParents(path string) string {
return schema.URLWithParents + path
}
// GetPluralURL returns a URL for access to all schema objects
func (schema *Schema) GetPluralURL() string {
return schema.URL
}
// GetSingleURLWithParents returns a URL for access to a single schema object
func (schema *Schema) GetSingleURLWithParents() string {
return fmt.Sprintf("%s/:id", schema.URLWithParents)
}
// GetPluralURLWithParents returns a URL for access to all schema objects
func (schema *Schema) GetPluralURLWithParents() string {
return schema.URLWithParents
}
// GetDbTableName returns a name of DB table used for storing schema instances
func (schema *Schema) GetDbTableName() string {
return schema.ID + "s"
}
// GetParentURL returns Parent URL
func (schema *Schema) GetParentURL() string {
if schema.Parent == "" {
return ""
}
return schema.ParentSchema.GetParentURL() + "/" + schema.ParentSchema.Plural + "/:" + schema.Parent
}
func filterSchemaByPermission(schema map[string]interface{}, permission string) map[string]interface{} {
filteredSchema := map[string]interface{}{"type": "object"}
filteredProperties := map[string]map[string]interface{}{}
filteredRequirements := []string{}
for id, property := range util.MaybeMap(schema["properties"]) {
propertyMap := util.MaybeMap(property)
allowedList := util.MaybeStringList(propertyMap["permission"])
for _, allowed := range allowedList {
if allowed == permission {
filteredProperties[id] = propertyMap
}
}
}
filteredSchema["properties"] = filteredProperties
requirements := util.MaybeStringList(schema["required"])
if permission != "create" {
// required property is used on only create event
requirements = []string{}
}
for _, requirement := range requirements {
if _, ok := filteredProperties[requirement]; ok {
filteredRequirements = append(filteredRequirements, requirement)
}
}
filteredSchema["required"] = filteredRequirements
filteredSchema["additionalProperties"] = false
return filteredSchema
}
func getParentPropertyObj(title, parent string) map[string]interface{} {
return map[string]interface{}{
"type": "string",
"relation": parent,
"title": title,
"description": "parent object",
"unique": false,
"permission": []interface{}{"create"},
}
}
//ValidateOnCreate validates json object using jsoncschema on object creation
func (schema *Schema) ValidateOnCreate(object interface{}) error {
return schema.Validate(schema.JSONSchemaOnCreate, object)
}
//ValidateOnUpdate validates json object using jsoncschema on object update
func (schema *Schema) ValidateOnUpdate(object interface{}) error {
return schema.Validate(schema.JSONSchemaOnUpdate, object)
}
//Validate validates json object using jsoncschema
func (schema *Schema) Validate(jsonSchema interface{}, object interface{}) error {
schemaLoader := gojsonschema.NewGoLoader(jsonSchema)
documentLoader := gojsonschema.NewGoLoader(object)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return err
}
if result.Valid() {
return nil
}
errDescription := "Json validation error:"
for _, err := range result.Errors() {
errDescription += fmt.Sprintf("\n\t%v,", err)
}
return fmt.Errorf(errDescription)
}
//SetParentSchema sets parent schema
func (schema *Schema) SetParentSchema(parentSchema *Schema) {
schema.ParentSchema = parentSchema
}
// SetNamespace sets namespace
func (schema *Schema) SetNamespace(namespace *Namespace) {
schema.Namespace = namespace
}
//ParentSchemaPropertyID get property id for parent relation
func (schema *Schema) ParentSchemaPropertyID() string {
if schema.Parent == "" {
return ""
}
return FormatParentID(schema.Parent)
}
//GetPropertyByID get a property object using ID
func (schema *Schema) GetPropertyByID(id string) (*Property, error) {
for _, p := range schema.Properties {
if p.ID == id {
return &p, nil
}
}
return nil, fmt.Errorf("Property with ID %s not found", id)
}
//StateVersioning whether resources created from this schema should track state and config versions
func (schema *Schema) StateVersioning() bool {
statefulRaw, ok := schema.Metadata["state_versioning"]
if !ok {
return false
}
stateful, ok := statefulRaw.(bool)
if !ok {
return false
}
return stateful
}
//SyncKeyTemplate - for custom paths in etcd
func (schema *Schema) SyncKeyTemplate() (syncKeyTemplate string, ok bool) {
syncKeyTemplateRaw, ok := schema.Metadata["sync_key_template"]
if !ok {
return
}
syncKeyTemplate, ok = syncKeyTemplateRaw.(string)
return
}
//GenerateCustomPath - returns custom path based on sync_key_template
func (schema *Schema) GenerateCustomPath(data map[string]interface{}) (path string, err error) {
syncKeyTemplate, ok := schema.SyncKeyTemplate()
if !ok {
err = fmt.Errorf("Failed to read sync_key_template from schema %v", schema.URL)
return
}
tpl, err := pongo2.FromString(syncKeyTemplate)
if err != nil {
return
}
path, err = tpl.Execute(pongo2.Context{}.Update(data))
return
}
//GetResourceIDFromPath - parse path and gets resourceID from it
func (schema *Schema) GetResourceIDFromPath(schemaPath string) string {
syncKeyTemplate, ok := schema.SyncKeyTemplate()
if !ok {
return strings.TrimPrefix(schemaPath, schema.URL+"/")
}
syncKeyTemplateSplit := strings.Split(syncKeyTemplate, "/")
schemaPathSplit := strings.Split(schemaPath, "/")
if len(schemaPathSplit) >= len(syncKeyTemplateSplit) {
resourceID := ""
for k, v := range syncKeyTemplateSplit {
if v == "{{id}}" {
resourceID = schemaPathSplit[k]
break
}
}
return resourceID
}
return strings.TrimPrefix(schemaPath, schema.URL+"/")
}
//GetSchemaByURLPath - gets schema by resource path (from API)
func GetSchemaByURLPath(path string) *Schema {
for _, schema := range GetManager().Schemas() {
if strings.HasPrefix(path+"/", schema.URL+"/") {
return schema
}
}
return nil
}
//GetSchemaByPath - gets schema by sync_key_template path
func GetSchemaByPath(path string) *Schema {
for _, schema := range GetManager().Schemas() {
syncKeyTemplate, ok := schema.SyncKeyTemplate()
if ok {
if checkIfPathMatchesSyncKeyTemplate(path, syncKeyTemplate) {
return schema
}
} else if strings.HasPrefix(path, schema.URL) {
return schema
}
}
return nil
}
func checkIfPathMatchesSyncKeyTemplate(path string, syncKeyTemplate string) bool {
syncKeyTemplateSplit := strings.Split(syncKeyTemplate, "/")
schemaPathSplit := strings.Split(path, "/")
if len(schemaPathSplit) == len(syncKeyTemplateSplit) {
for k, v := range syncKeyTemplateSplit {
if strings.HasPrefix(v, "{{") {
continue
} else if schemaPathSplit[k] != syncKeyTemplateSplit[k] {
return false
}
}
return true
}
return false
}
// FormatParentID ...
func FormatParentID(parent string) string {
return fmt.Sprintf("%s_id", parent)
}
func (schema *Schema) relatedSchemas() []string {
schemas := []string{}
for _, p := range schema.Properties {
if p.Relation != "" {
schemas = append(schemas, p.Relation)
}
}
schemas = util.ExtendStringList(schemas, schema.Extends)
return schemas
}
// Extend extends target schema
func (schema *Schema) Extend(fromSchema *Schema) error {
if schema.Parent == "" {
schema.Parent = fromSchema.Parent
}
if schema.Prefix == "" {
schema.Prefix = fromSchema.Prefix
}
if schema.URL == "" {
schema.URL = fromSchema.URL
}
if schema.NamespaceID == "" {
schema.NamespaceID = fromSchema.NamespaceID
}
schema.JSONSchema["properties"] = util.ExtendMap(
util.MaybeMap(schema.JSONSchema["properties"]),
util.MaybeMap(fromSchema.JSONSchema["properties"]))
schema.JSONSchema["propertiesOrder"] = util.ExtendStringList(
util.MaybeStringList(fromSchema.JSONSchema["propertiesOrder"]),
util.MaybeStringList(schema.JSONSchema["propertiesOrder"]))
MergeAction:
for _, action := range fromSchema.Actions {
for _, existingAction := range schema.Actions {
if action.ID == existingAction.ID {
continue MergeAction
}
}
schema.Actions = append(schema.Actions, action)
}
schema.Metadata = util.ExtendMap(schema.Metadata, fromSchema.Metadata)
return schema.Init()
}
//Titles returns list of Titles
func (schema *Schema) Titles() []string {
titles := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
titles = append(titles, property.Title)
}
return titles
}
//JSON returns json format of schema
func (schema *Schema) JSON() map[string]interface{} {
actions := map[string]interface{}{}
for _, a := range schema.Actions {
actions[a.ID] = map[string]interface{}{
"method": a.Method,
"path": a.Path,
"input": a.InputSchema,
"output": a.OutputSchema,
}
}
return map[string]interface{}{
"id": schema.ID,
"plural": schema.Plural,
"title": schema.Title,
"description": schema.Description,
"parent": schema.Parent,
"singular": schema.Singular,
"prefix": schema.Prefix,
"url": schema.URL,
"namespace": schema.NamespaceID,
"schema": schema.JSONSchema,
"actions": actions,
"metadata": schema.Metadata,
}
}