This repository has been archived by the owner on Aug 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathserver.go
252 lines (191 loc) · 5.58 KB
/
server.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
package golive
import (
"context"
"fmt"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
type LiveServer struct {
// Wire ...
Wire *LiveWire
// CookieName ...
CookieName string
Log Log
}
type LiveResponse struct {
Rendered string
Session string
}
func NewServer() *LiveServer {
logger := NewLoggerBasic()
return &LiveServer{
Wire: NewWire(),
CookieName: "_csrf_token",
Log: logger.Log,
}
}
func (s *LiveServer) HandleFirstRequest(lc *LiveComponent, c PageContent) (*LiveResponse, error) {
/* Create session to the new user */
sessionKey, session, err := s.Wire.CreateSession()
if err != nil {
return nil, err
}
s.Log(LogInfo, "http request", logEx{"Component": lc.Name, "session": sessionKey})
session.log = s.Log
// Instantiate a page to attach to a session
p := NewLivePage(lc)
// Set page content
p.SetContent(c)
// activation should be before mount,
// because in activation will setup page channels
// that will be needed in mount
session.ActivatePage(p)
// Mount page
p.Mount()
// Render page
rendered, err := p.Render()
if err != nil {
return &LiveResponse{
Rendered: "<h1> Page with error </h1>",
Session: "",
}, err
}
return &LiveResponse{Rendered: rendered, Session: sessionKey}, nil
}
func (s *LiveServer) HandleHTMLRequest(ctx *fiber.Ctx, lc *LiveComponent, c PageContent) {
lr, err := s.HandleFirstRequest(lc, c)
if lr == nil {
s.Log(LogPanic, "no live page", logEx{"error": err})
return
}
if err != nil {
s.Log(LogError, "handle html request", logEx{"error": err})
ctx.Response().SetStatusCode(500)
return
}
ctx.Cookie(&fiber.Cookie{
Name: s.CookieName,
Value: lr.Session,
Expires: time.Now().Add(24 * time.Hour),
})
ctx.Response().Header.SetContentType("text/html")
ctx.Response().AppendBodyString(lr.Rendered)
}
func (s *LiveServer) CreateHTMLHandler(f func() *LiveComponent, c PageContent) func(ctx *fiber.Ctx) error {
return func(ctx *fiber.Ctx) error {
lc := f()
lc.log = s.Log
s.HandleHTMLRequest(ctx, lc, c)
return nil
}
}
// HTTPMiddleware Middleware to run on HTTP requests.
type HTTPMiddleware func(next HTTPHandlerCtx) HTTPHandlerCtx
// HTTPHandlerCtx HTTP Handler with a page level context.
type HTTPHandlerCtx func(ctx *fiber.Ctx, pageCtx context.Context)
func (s *LiveServer) CreateHTMLHandlerWithMiddleware(f func(ctx context.Context) *LiveComponent, content PageContent,
middlewares ...HTTPMiddleware) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
ctx := context.Background()
// TODO: move chain building out so it only happens once - Sam H.
if len(middlewares) != 0 {
// Reassign the context back to this scope to capture changes to it
end := func(_ *fiber.Ctx, pCtx context.Context) {
ctx = pCtx
}
h := middlewares[len(middlewares)-1](end)
// build chain
for i := len(middlewares) - 2; i >= 0; i-- {
h = middlewares[i](h)
}
// trigger chain
h(c, ctx)
}
lc := f(ctx)
lc.log = s.Log
s.HandleHTMLRequest(c, lc, content)
return nil
}
}
func (s *LiveServer) HandleWSRequest(c *websocket.Conn) {
defer func() {
payload := recover()
if payload != nil {
s.Log(LogWarn, fmt.Sprintf("ws request panic recovered: %v", payload), nil)
}
}()
c.EnableWriteCompression(true)
sessionKey := c.Cookies(s.CookieName)
s.Log(LogInfo, "websocket open", logEx{"session": sessionKey})
session := s.Wire.GetSession(sessionKey)
if session == nil || session.Status != SessionNew {
s.Log(LogWarn, "session not found", logEx{"session": sessionKey})
var msg PatchBrowser
msg.Type = EventLiveError
msg.Message = LiveErrorSessionNotFound
if err := c.WriteJSON(msg); err != nil {
s.Log(LogError, "handle ws request: write json", logEx{"error": err})
}
if err := c.Close(); err != nil {
s.Log(LogError, "close websocket connection", logEx{"error": err})
}
s.Log(LogInfo, "websocket close", logEx{"session": sessionKey})
return
}
session.Status = SessionOpen
exit := make(chan int)
exited := false
go func() {
for {
select {
case msg := <-session.OutChannel:
s.Log(LogDebug, "message out", logEx{"msg": msg, "session": sessionKey})
if err := c.WriteJSON(msg); err != nil {
s.Log(LogError, "handle ws request: write json", logEx{"error": err})
}
case <-exit:
exited = true
session.Status = SessionClosed
if err := c.Close(); err != nil {
s.Log(LogError, "close websocket connection", logEx{"error": err})
}
if err := session.LivePage.entryComponent.Kill(); err != nil {
s.Log(LogError, "handle ws request: kill page", logEx{"error": err})
}
s.Wire.DeleteSession(sessionKey)
s.Log(LogInfo, "websocket close", logEx{"session": sessionKey})
return
}
}
}()
c.SetCloseHandler(func(code int, text string) error {
// Close codes defined in RFC 6455, section 11.7.
s.Log(LogTrace, "ws close handler", logEx{"code": code, "text": text})
exit <- 1
return nil
})
for {
if exited {
return
}
inMsg := BrowserEvent{}
// Loop blocks here
if err := c.ReadJSON(&inMsg); err != nil {
if websocket.IsUnexpectedCloseError(err) {
// This seems to happen when running in Docker
if !exited {
s.Log(LogWarn, "handle ws request: unexpected connection close", nil)
exit <- 1
}
return
}
s.Log(LogError, "handle ws request: read json", logEx{"error": err})
continue
}
s.Log(LogDebug, "message in", logEx{"msg": inMsg, "session": sessionKey})
if err := session.IngestMessage(inMsg); err != nil {
s.Log(LogError, "handle ws request: ingest message", logEx{"error": err})
}
}
}