...
1 package cushion
2
3 import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8
9 "edge-infra.dev/pkg/edge/apis/meta"
10 "edge-infra.dev/pkg/edge/datasync/couchdb"
11 )
12
13 var (
14 couchdbValidName = regexp.MustCompile(`^[a-z][a-z0-9_$()+/-]*$`)
15 )
16
17 const (
18 OperationCreate = "CREATE"
19 OperationDelete = "DELETE"
20 )
21
22
23 type Request struct {
24
25
26 TenantID string `json:"tenant_id"`
27
28
29 DBName string `json:"db_name"`
30
31 EntityID string `json:"entity_id"`
32
33 Deleted bool `json:"deleted"`
34
35 Provider string `json:"provider"`
36
37 SiteID string `json:"site_id"`
38
39 TouchpointID string `json:"touchpoint_id"`
40
41
42 EnterpriseUnitID string `json:"enterprise_unit_id"`
43
44
45
46
47
48 ParentID string `json:"parent_id"`
49
50 EntityType string `json:"entity_type"`
51
52 Version string `json:"version"`
53
54
55 Credentials string `json:"credentials"`
56 }
57
58
59
60
61 func (r *Request) Validate() error {
62
63
64
65
66
67
68
69
70
71
72
73
74 if r.TenantID == "" {
75 return fmt.Errorf("tenant_id message attribute must not be empty")
76 }
77
78 if r.DBName == "" {
79 return fmt.Errorf("db_name message attribute must not be empty")
80 }
81 r.DBName = normalizeDBName(r.DBName)
82 if !couchdbValidName.MatchString(r.DBName) {
83 return fmt.Errorf("db name: %s not matching regex: ^[a-z][a-z0-9_$()+/-]*$", r.DBName)
84 }
85
86 if r.EntityID == "" {
87 return fmt.Errorf("entity_id message attribute must not be empty")
88 }
89 return nil
90 }
91
92 func (r *Request) FromAttributes(attrs map[string]string) error {
93
94
95
96 r.TenantID = attrs["tenant_id"]
97 r.DBName = attrs["db_name"]
98 r.EntityID = attrs["entity_id"]
99
100 deletedStr := attrs["deleted"]
101 if deletedStr == "" {
102 r.Deleted = false
103 } else {
104 var err error
105 r.Deleted, err = strconv.ParseBool(deletedStr)
106 if err != nil {
107 return err
108 }
109 }
110
111 r.ParentID = attrs["parent_id"]
112 r.EntityType = attrs["entity_type"]
113 r.Version = attrs["version"]
114 r.Provider = attrs["provider"]
115 r.SiteID = attrs["site_id"]
116 r.TouchpointID = attrs["touchpoint_id"]
117 r.EnterpriseUnitID = attrs["enterprise_unit_id"]
118
119 return r.Validate()
120 }
121
122
123 func (r *Request) K8sDBName() string {
124 return K8sDBName(r.DBName)
125 }
126
127
128
129 func normalizeDBName(dbname string) string {
130 return strings.ToLower(dbname)
131 }
132
133
134 func K8sDBName(name string) string {
135 return fmt.Sprintf("%s-%s", couchdb.CouchDBName, meta.Hash(normalizeDBName(name)))
136 }
137
View as plain text