/
content_manager.go
executable file
·212 lines (179 loc) · 6.06 KB
/
content_manager.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
/*
* Copyright (c) 2019 VMware, Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package api
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
"github.com/kubenext/lissio/internal/controllers"
"github.com/kubenext/lissio/internal/event"
"github.com/kubenext/lissio/internal/log"
"github.com/kubenext/lissio/internal/module"
"github.com/kubenext/lissio/pkg/action"
"github.com/kubenext/lissio/pkg/view/component"
)
const (
RequestSetContentPath = "setContentPath"
RequestSetNamespace = "setNamespace"
)
// ContentManagerOption is an option for configuring ContentManager.
type ContentManagerOption func(manager *ContentManager)
// ContentGenerateFunc is a function that generates content. It returns `rerun=true`
// if the action should be be immediately rerun.
type ContentGenerateFunc func(ctx context.Context, state controllers.State) (component.ContentResponse, bool, error)
// WithContentGenerator configures the content generate function.
func WithContentGenerator(fn ContentGenerateFunc) ContentManagerOption {
return func(manager *ContentManager) {
manager.contentGenerateFunc = fn
}
}
// WithContentGeneratorPoller configures the poller.
func WithContentGeneratorPoller(poller Poller) ContentManagerOption {
return func(manager *ContentManager) {
manager.poller = poller
}
}
// ContentManager manages content for websockets.
type ContentManager struct {
moduleManager module.ManagerInterface
logger log.Logger
contentGenerateFunc ContentGenerateFunc
poller Poller
updateContentCh chan struct{}
}
// NewContentManager creates an instance of ContentManager.
func NewContentManager(moduleManager module.ManagerInterface, logger log.Logger, options ...ContentManagerOption) *ContentManager {
cm := &ContentManager{
moduleManager: moduleManager,
logger: logger,
poller: NewInterruptiblePoller("content"),
updateContentCh: make(chan struct{}, 1),
}
cm.contentGenerateFunc = cm.generateContent
for _, option := range options {
option(cm)
}
return cm
}
var _ StateManager = (*ContentManager)(nil)
// Start starts the manager.
func (cm *ContentManager) Start(ctx context.Context, state controllers.State, s LissioClient) {
defer func() {
close(cm.updateContentCh)
}()
updateCancel := state.OnContentPathUpdate(func(contentPath string) {
cm.updateContentCh <- struct{}{}
})
defer updateCancel()
cm.poller.Run(ctx, cm.updateContentCh, cm.runUpdate(state, s), event.DefaultScheduleDelay)
}
func (cm *ContentManager) runUpdate(state controllers.State, s LissioClient) PollerFunc {
return func(ctx context.Context) bool {
contentPath := state.GetContentPath()
if contentPath == "" {
return false
}
contentResponse, _, err := cm.contentGenerateFunc(ctx, state)
if err != nil {
return false
}
if ctx.Err() == nil {
s.Send(CreateContentEvent(contentResponse, state.GetNamespace(), contentPath, state.GetQueryParams()))
}
return false
}
}
func (cm *ContentManager) generateContent(ctx context.Context, state controllers.State) (component.ContentResponse, bool, error) {
contentPath := state.GetContentPath()
logger := cm.logger.With("contentPath", contentPath)
now := time.Now()
defer func() {
logger.With("elapsed", time.Since(now)).Debugf("generating content")
}()
m, ok := cm.moduleManager.ModuleForContentPath(contentPath)
if !ok {
return component.EmptyContentResponse, false, errors.Errorf("unable to find module for content path %q", contentPath)
}
modulePath := strings.TrimPrefix(contentPath, m.Name())
options := module.ContentOptions{
LabelSet: FiltersToLabelSet(state.GetFilters()),
}
contentResponse, err := m.Content(ctx, modulePath, options)
if err != nil {
if nfe, ok := err.(notFound); ok && nfe.NotFound() {
logger.Debugf("path not found, redirecting to parent")
state.SetContentPath(notFoundRedirectPath(contentPath))
return component.EmptyContentResponse, true, nil
} else {
return component.EmptyContentResponse, false, errors.Wrap(err, "generate content")
}
}
return contentResponse, false, nil
}
// Handlers returns a slice of client request handlers.
func (cm *ContentManager) Handlers() []controllers.ClientRequestHandler {
return []controllers.ClientRequestHandler{
{
RequestType: RequestSetContentPath,
Handler: cm.SetContentPath,
},
{
RequestType: RequestSetNamespace,
Handler: cm.SetNamespace,
},
}
}
// SetQueryParams sets the current query params.
func (cm *ContentManager) SetQueryParams(state controllers.State, payload action.Payload) error {
if params, ok := payload["params"].(map[string]interface{}); ok {
// handle filters
if filters, ok := params["filters"]; ok {
list, err := FiltersFromQueryParams(filters)
if err != nil {
return errors.Wrap(err, "extract filters from query params")
}
state.SetFilters(list)
}
}
return nil
}
// SetNamespace sets the current namespace.
func (cm *ContentManager) SetNamespace(state controllers.State, payload action.Payload) error {
namespace, err := payload.String("namespace")
if err != nil {
return errors.Wrap(err, "extract namespace from payload")
}
state.SetNamespace(namespace)
return nil
}
// SetContentPath sets the current content path.
func (cm *ContentManager) SetContentPath(state controllers.State, payload action.Payload) error {
contentPath, err := payload.String("contentPath")
if err != nil {
return errors.Wrap(err, "extract contentPath from payload")
}
if err := cm.SetQueryParams(state, payload); err != nil {
return errors.Wrap(err, "extract query params from payload")
}
state.SetContentPath(contentPath)
return nil
}
type notFound interface {
NotFound() bool
Path() string
}
// CreateContentEvent creates a content event.
func CreateContentEvent(contentResponse component.ContentResponse, namespace, contentPath string, queryParams map[string][]string) controllers.Event {
return controllers.Event{
Type: controllers.EventTypeContent,
Data: map[string]interface{}{
"content": contentResponse,
"namespace": namespace,
"contentPath": contentPath,
"queryParams": queryParams,
},
}
}