/
api_polyfea_service.go
399 lines (323 loc) · 13.5 KB
/
api_polyfea_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
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
package polyfea
import (
"context"
"encoding/json"
"errors"
"net/http"
"regexp"
"slices"
"sort"
"strings"
"github.com/polyfea/polyfea-controller/api/v1alpha1"
"github.com/polyfea/polyfea-controller/repository"
"github.com/polyfea/polyfea-controller/web-server/internal/polyfea/generated"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type PolyfeaApiService struct {
webComponentRepository repository.PolyfeaRepository[*v1alpha1.WebComponent]
microFrontendRepository repository.PolyfeaRepository[*v1alpha1.MicroFrontend]
microFrontendClassRepository repository.PolyfeaRepository[*v1alpha1.MicroFrontendClass]
logger *zerolog.Logger
}
func NewPolyfeaAPIService(
webComponentRepository repository.PolyfeaRepository[*v1alpha1.WebComponent],
microFrontendRepository repository.PolyfeaRepository[*v1alpha1.MicroFrontend],
microFrontendClassRepository repository.PolyfeaRepository[*v1alpha1.MicroFrontendClass],
logger *zerolog.Logger,
) *PolyfeaApiService {
l := logger.With().Str("component", "PolyfeaApiService").Logger()
return &PolyfeaApiService{
webComponentRepository: webComponentRepository,
microFrontendRepository: microFrontendRepository,
microFrontendClassRepository: microFrontendClassRepository,
logger: &l,
}
}
func (s *PolyfeaApiService) GetContextArea(ctx context.Context, name string, path string, take int32, headers http.Header) (generated.ImplResponse, error) {
logger := s.logger.With().
Str("function", "GetContextArea").
Str("context-area", name).
Str("path", path).
Int32("take", take).
Logger()
ctx, span := telemetry().tracer.Start(ctx, "get_context_area", trace.WithAttributes(
attribute.String("context-area", name),
attribute.String("path", path),
attribute.Int("take", int(take)),
))
defer span.End()
result := generated.ContextArea{
Elements: []generated.ElementSpec{},
Microfrontends: map[string]generated.MicrofrontendSpec{},
}
// Get base path from context or use default
basePathValue := ctx.Value(PolyfeaContextKeyBasePath)
var basePath string
if basePathValue == nil {
basePath = "/"
} else {
basePath = basePathValue.(string)
}
logger = logger.With().Str("base-path", basePath).Logger()
span.SetAttributes(attribute.String("base-path", basePath))
// Get frontend class for base path
frontendClasses, err := s.microFrontendClassRepository.GetItems(func(mfc *v1alpha1.MicroFrontendClass) bool {
frontendClassBasePath := *mfc.Spec.BaseUri
if frontendClassBasePath[0] != '/' {
frontendClassBasePath = "/" + frontendClassBasePath
}
if frontendClassBasePath[len(frontendClassBasePath)-1] != '/' {
frontendClassBasePath += "/"
}
return basePath == frontendClassBasePath
})
if err != nil {
logger.Err(err).Msg("Error while getting frontend class")
span.SetStatus(codes.Error, "microfrontend_class_repository_error")
return generated.Response(http.StatusInternalServerError, "Internal Server Error"), err
}
if len(frontendClasses) == 0 {
logger.Info().Msg("No frontend class found for base path")
telemetry().not_found.Add(ctx, 1)
span.SetStatus(codes.Error, "microfrontend_class_not_found")
return generated.Response(http.StatusNotFound, "No frontend class found for base path "+basePath), nil
}
if len(frontendClasses) > 1 {
logger.Warn().Msg("Multiple frontend classes found for base path")
span.SetStatus(codes.Error, "multiple_frontend_classes_found")
return generated.Response(http.StatusBadRequest, "Multiple frontend classes found for base path "+basePath), nil
}
frontendClass := frontendClasses[0]
// Read user roles from header
userRoleHeaders := headers.Values(frontendClass.Spec.UserRolesHeader)
userRoles := []string{}
for _, userRoleHeader := range userRoleHeaders {
for _, userRole := range strings.Split(userRoleHeader, ",") {
userRoles = append(userRoles, strings.TrimSpace(userRole))
}
}
logger = logger.With().
Str("frontend-class", frontendClass.Name).
Strs("user-roles", userRoles).
Logger()
span.SetAttributes(
attribute.String("frontend-class", frontendClass.Name),
attribute.String("user-roles", strings.Join(userRoles, ",")),
)
// Get microfrontends for frontend class
microFrontendsForClass, err := s.microFrontendRepository.GetItems(func(mf *v1alpha1.MicroFrontend) bool {
return *mf.Spec.FrontendClass == frontendClass.Name
})
if err != nil {
logger.Err(err).Msg("Error while getting microfrontends for frontend class")
span.SetStatus(codes.Error, "microfrontend_repository_error")
return addExtraHeaders(generated.Response(http.StatusInternalServerError, "Internal Server Error"), frontendClass.Spec.ExtraHeaders), err
}
// Get names of microfrontends for frontend class for query
microFrontendsNamesForClass := []string{}
for _, mf := range microFrontendsForClass {
microFrontendsNamesForClass = append(microFrontendsNamesForClass, mf.Name)
}
// Get webcomponents for given query and frontend class
webComponents, err := s.webComponentRepository.GetItems(func(mf *v1alpha1.WebComponent) bool {
return selectMatchingWebComponents(mf, name, path, userRoles) && (len(microFrontendsNamesForClass) == 0 || mf.Spec.MicroFrontend == nil || slices.Contains(microFrontendsNamesForClass, *mf.Spec.MicroFrontend))
})
if err != nil {
logger.Err(err).Msg("Error while getting webcomponents for query")
span.SetStatus(codes.Error, "webcomponent_repository_error")
return addExtraHeaders(generated.Response(http.StatusInternalServerError, "Internal Server Error"), frontendClass.Spec.ExtraHeaders), err
}
if len(webComponents) == 0 {
logger.Info().Msg("No webcomponents found for query")
telemetry().not_found.Add(ctx, 1)
span.SetStatus(codes.Ok, "webcomponent_not_found") // this is possible situation when context is simply not filled
return addExtraHeaders(generated.Response(http.StatusOK, result), frontendClass.Spec.ExtraHeaders), nil
}
sort.Slice(webComponents, func(i, j int) bool {
return *webComponents[i].Spec.Priority > *webComponents[j].Spec.Priority
})
// Limit number of webcomponents by take parameter
if take > 0 && int(take) < len(webComponents) {
logger.Info().Msg("Limiting number of webcomponents by take parameter")
webComponents = webComponents[:take]
}
// Chek which microfrontends are needed for selected webcomponents and convert webcomponents to response
microFrontendsToLoad := []string{}
for _, webComponent := range webComponents {
var microfrontendName string
if webComponent.Spec.MicroFrontend != nil {
microFrontendsToLoad = append(microFrontendsToLoad, *webComponent.Spec.MicroFrontend)
microfrontendName = *webComponent.Spec.MicroFrontend
}
result.Elements = append(result.Elements, generated.ElementSpec{
Microfrontend: microfrontendName,
TagName: *webComponent.Spec.Element,
Attributes: convertAttributes(webComponent.Spec.Attributes),
Style: convertStyles(webComponent.Spec.Style),
})
}
// Load all needed microfrontends with dependencies
allMicroFrontends, err := s.loadAllMicroFrontends(microFrontendsToLoad, s.microFrontendRepository, []string{})
if err != nil {
logger.Err(err).Msg("Error while loading microfrontends")
span.SetStatus(codes.Error, "microfrontend_load_error")
return addExtraHeaders(generated.Response(http.StatusInternalServerError, "Internal Server Error"+err.Error()), frontendClass.Spec.ExtraHeaders), err
}
// Convert microfrontends to response
for _, microFrontend := range allMicroFrontends {
result.Microfrontends[microFrontend.Name] = generated.MicrofrontendSpec{
DependsOn: microFrontend.Spec.DependsOn,
Module: buildModulePath(microFrontend.Namespace, microFrontend.Name, *microFrontend.Spec.ModulePath, *microFrontend.Spec.Proxy),
Resources: convertMicrofrontendResources(microFrontend.Namespace, microFrontend.Name, microFrontend.Spec.StaticResources),
}
}
logger.Info().Msg("Context area successfully generated")
span.SetStatus(codes.Ok, "ok")
telemetry().context_areas.Add(ctx, 1)
return addExtraHeaders(generated.Response(http.StatusOK, result), frontendClass.Spec.ExtraHeaders), nil
}
func (s *PolyfeaApiService) GetStaticConfig(ctx context.Context, headers http.Header) (generated.ImplResponse, error) {
_, span := telemetry().tracer.Start(ctx, "get_static_config")
defer span.End()
s.logger.Error().Str("function", "GetStaticConfig").Msg("Static config is not implemented by the controller")
span.SetStatus(codes.Error, "not_implemented")
return generated.Response(http.StatusNotImplemented, "Not implemented"), nil
}
func selectMatchingWebComponents(webComponent *v1alpha1.WebComponent, name string, path string, userRoles []string) bool {
// Check if any of display rules matches
for _, displayRule := range webComponent.Spec.DisplayRules {
var pathRegex *regexp.Regexp
selectCurrent := true
// If any of noneOf rules matches, we can evaluate to false
for _, matcher := range displayRule.NoneOf {
if len(matcher.Path) != 0 {
pathRegex = regexp.MustCompile(matcher.Path)
}
if len(matcher.ContextName) > 0 && matcher.ContextName == name ||
len(matcher.Path) > 0 && pathRegex.MatchString(path) ||
len(matcher.Role) > 0 && slices.Contains(userRoles, matcher.Role) {
selectCurrent = false
break
}
}
if !selectCurrent {
continue
}
// If any of allOf rules does not match, we can evaluate to false
for _, matcher := range displayRule.AllOf {
if len(matcher.Path) != 0 {
pathRegex = regexp.MustCompile(matcher.Path)
}
if len(matcher.ContextName) > 0 && matcher.ContextName != name ||
len(matcher.Path) > 0 && !pathRegex.MatchString(path) ||
len(matcher.Role) > 0 && !slices.Contains(userRoles, matcher.Role) {
selectCurrent = false
break
}
}
if !selectCurrent {
continue
}
// If any of anyOf rules matches, we can evaluate to true therfore we need to set to false first
if len(displayRule.AnyOf) > 0 {
selectCurrent = false
}
// If any of anyOf rules matches, we can evaluate to true
for _, matcher := range displayRule.AnyOf {
if len(matcher.Path) != 0 {
pathRegex = regexp.MustCompile(matcher.Path)
}
if len(matcher.ContextName) > 0 && matcher.ContextName == name ||
len(matcher.Path) > 0 && pathRegex.MatchString(path) ||
len(matcher.Role) > 0 && slices.Contains(userRoles, matcher.Role) {
selectCurrent = true
break
}
}
// If any of display rules matches, we can evaluate to true
if selectCurrent {
return true
}
}
return false
}
func convertAttributes(attributes []v1alpha1.Attribute) map[string]string {
result := map[string]string{}
for _, attribute := range attributes {
var value string
json.Unmarshal(attribute.Value.Raw, &value)
result[attribute.Name] = value
}
return result
}
func convertStyles(styles []v1alpha1.Style) map[string]string {
result := map[string]string{}
for _, style := range styles {
result[style.Name] = style.Value
}
return result
}
func convertMicrofrontendResources(microFrontendNamespace string, microFrontendName string, resources []v1alpha1.StaticResources) []generated.MicrofrontendResource {
result := []generated.MicrofrontendResource{}
for _, resource := range resources {
result = append(result, generated.MicrofrontendResource{
Kind: resource.Kind,
Href: buildModulePath(microFrontendNamespace, microFrontendName, resource.Path, *resource.Proxy),
Attributes: convertAttributes(resource.Attributes),
WaitOnLoad: resource.WaitOnLoad,
})
}
return result
}
func (s *PolyfeaApiService) loadAllMicroFrontends(microFrontendsToLoad []string, microFrontendRepository repository.PolyfeaRepository[*v1alpha1.MicroFrontend], loadPath []string) ([]*v1alpha1.MicroFrontend, error) {
logger := s.logger.With().Str("function", "loadAllMicroFrontends").Logger()
result := []*v1alpha1.MicroFrontend{}
for _, microFrontendName := range microFrontendsToLoad {
if slices.Contains(loadPath, microFrontendName) {
dependencyPath := strings.Join(append(loadPath, microFrontendName), " -> ")
logger.Error().Str("dependency-path", dependencyPath).Str("microfrontend", microFrontendName).Msg("Circular dependency detected")
return nil, errors.New("Circular dependency detected: " + dependencyPath)
}
microFrontend, err := microFrontendRepository.GetItems(func(mf *v1alpha1.MicroFrontend) bool {
return mf.Name == microFrontendName
})
if err != nil {
return nil, err
}
if len(microFrontend) == 0 {
logger.Error().Str("microfrontend", microFrontendName).Msg("Microfrontend not found")
return nil, errors.New("Microfrontend " + microFrontendName + " not found")
}
result = append(result, microFrontend[0])
if len(microFrontend[0].Spec.DependsOn) > 0 {
dependsOn, err := s.loadAllMicroFrontends(microFrontend[0].Spec.DependsOn, microFrontendRepository, append(loadPath, microFrontendName))
if err != nil {
return nil, err
}
result = append(result, dependsOn...)
}
}
return result, nil
}
func buildModulePath(microFrontendNamespace string, microFrontendName string, path string, proxy bool) string {
if proxy {
return "./polyfea/proxy/" + microFrontendNamespace + "/" + microFrontendName + "/" + path
} else {
return path
}
}
func addExtraHeaders(response generated.ImplResponse, extraHeaders []v1alpha1.Header) generated.ImplResponse {
if extraHeaders == nil {
return response
}
if response.Headers == nil {
response.Headers = map[string][]string{}
}
for _, header := range extraHeaders {
response.Headers[header.Name] = []string{header.Value}
}
return response
}