/
service.go
177 lines (148 loc) · 5.55 KB
/
service.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
package tenant
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
"github.com/kyma-incubator/compass/components/director/pkg/log"
tenantEntity "github.com/kyma-incubator/compass/components/director/pkg/tenant"
"github.com/tidwall/gjson"
"github.com/kyma-incubator/compass/components/director/pkg/persistence"
"github.com/kyma-incubator/compass/components/tenant-fetcher/internal/model"
"github.com/pkg/errors"
)
//go:generate mockery --name=TenantService --output=automock --outpkg=automock --case=underscore
type TenantService interface {
Create(ctx context.Context, item model.TenantModel) error
DeleteByExternalID(ctx context.Context, tenantId string) error
}
//go:generate mockery --name=UIDService --output=automock --outpkg=automock --case=underscore
type UIDService interface {
Generate() string
}
type service struct {
repository TenantRepository
transact persistence.Transactioner
uidService UIDService
config Config
}
func NewService(tenant TenantRepository, transact persistence.Transactioner, uidService UIDService, config Config) *service {
return &service{
repository: tenant,
transact: transact,
uidService: uidService,
config: config,
}
}
func (s *service) Create(writer http.ResponseWriter, request *http.Request) {
ctx := request.Context()
logger := log.C(ctx)
body, err := extractBody(request, writer)
if err != nil {
logger.WithError(err).Errorf("while extracting request body: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
tenantId := gjson.GetBytes(body, s.config.TenantProviderTenantIdProperty)
if !tenantId.Exists() || tenantId.Type != gjson.String || len(tenantId.String()) == 0 {
logger.Errorf("Property %q not found in body or it is not of String type", s.config.TenantProviderTenantIdProperty)
http.Error(writer, fmt.Sprintf("Property %q not found in body or it is not of String type", s.config.TenantProviderTenantIdProperty), http.StatusInternalServerError)
return
}
tenant := model.TenantModel{
ID: s.uidService.Generate(),
TenantId: tenantId.String(),
TenantProvider: s.config.TenantProvider,
Status: tenantEntity.Active,
}
tx, err := s.transact.Begin()
if err != nil {
logger.WithError(err).Errorf("while beginning db transaction: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
defer s.transact.RollbackUnlessCommitted(ctx, tx)
ctx = persistence.SaveToContext(ctx, tx)
if err := s.repository.Create(ctx, tenant); err != nil {
if !apperrors.IsNotUniqueError(err) {
logger.WithError(err).Errorf("while creating tenant: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
} else {
if err := tx.Commit(); err != nil {
logger.WithError(err).Errorf("while committing transaction : %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
}
writer.Header().Set("Content-Type", "text/plain")
writer.WriteHeader(http.StatusOK)
if _, err := writer.Write([]byte(compassURL)); err != nil {
logger.WithError(err).Errorf("while writing response body: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
}
func (s *service) DeleteByExternalID(writer http.ResponseWriter, request *http.Request) {
ctx := request.Context()
logger := log.C(ctx)
body, err := extractBody(request, writer)
if err != nil {
logger.WithError(err).Errorf("while extracting request body: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
tenantId := gjson.GetBytes(body, s.config.TenantProviderTenantIdProperty)
if !tenantId.Exists() || tenantId.Type != gjson.String || len(tenantId.String()) == 0 {
logger.Errorf("Property %q not found in body or it is not of String type", s.config.TenantProviderTenantIdProperty)
http.Error(writer, fmt.Sprintf("Property %q not found in body or it is not of String type", s.config.TenantProviderTenantIdProperty), http.StatusInternalServerError)
return
}
tx, err := s.transact.Begin()
if err != nil {
logger.WithError(err).Errorf("while beginning db transaction: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
defer s.transact.RollbackUnlessCommitted(ctx, tx)
ctx = persistence.SaveToContext(ctx, tx)
if err := s.repository.DeleteByExternalID(ctx, tenantId.String()); err != nil {
if !apperrors.IsNotFoundError(err) {
logger.WithError(err).Errorf("while deleting tenant: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
} else {
if err := tx.Commit(); err != nil {
logger.WithError(err).Errorf("while committing transaction: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
}
writer.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(writer).Encode(map[string]interface{}{})
if err != nil {
logger.WithError(err).Errorf("while writing to response body: %v", err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
}
func extractBody(r *http.Request, w http.ResponseWriter) ([]byte, error) {
logger := log.C(r.Context())
buf, bodyErr := ioutil.ReadAll(r.Body)
if bodyErr != nil {
logger.Error(errors.Wrap(bodyErr, "while reading request body"))
http.Error(w, bodyErr.Error(), http.StatusInternalServerError)
return nil, bodyErr
}
defer func() {
err := r.Body.Close()
if err != nil {
logger.Warnf("Unable to close request body. Cause: %v", err)
}
}()
return buf, nil
}