/
controller.go
228 lines (192 loc) · 4.88 KB
/
controller.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
package liveview
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/andybalholm/brotli"
"github.com/andybalholm/escaper"
"github.com/gorilla/websocket"
"github.com/segmentio/ksuid"
)
// A channel links a View, and ID, and a websocket.
type channel struct {
view View
id string
socket *synchronizedWebsocket
created time.Time
}
// A Controller manages a collection of live views and their associated
// websockets.
type Controller struct {
channels map[string]*channel
byView map[View]*channel
lastGC time.Time
m sync.RWMutex
}
func (c *Controller) channelForView(v View) *channel {
c.m.RLock()
defer c.m.RUnlock()
return c.byView[v]
}
func (c *Controller) channelByID(id string) *channel {
c.m.RLock()
defer c.m.RUnlock()
return c.channels[id]
}
func (c *Controller) removeChannel(ch *channel) {
c.m.Lock()
defer c.m.Unlock()
delete(c.channels, ch.id)
delete(c.byView, ch.view)
}
// Register registers Views with c, and prepares to receive websocket
// connections for them.
func (c *Controller) Register(views ...View) {
c.m.Lock()
defer c.m.Unlock()
if c.channels == nil {
c.channels = make(map[string]*channel)
c.byView = make(map[View]*channel)
c.lastGC = time.Now()
} else {
// Clean up any channels that have been waiting too long.
gcThreshold := time.Now().Add(-30 * time.Second)
if c.lastGC.Before(gcThreshold) {
for id, ch := range c.channels {
if ch.socket == nil && ch.created.Before(gcThreshold) {
delete(c.channels, id)
delete(c.byView, ch.view)
}
}
c.lastGC = time.Now()
}
}
for _, v := range views {
ch := &channel{
view: v,
created: time.Now(),
id: ksuid.New().String(),
}
c.channels[ch.id] = ch
c.byView[v] = ch
}
}
var upgrader = websocket.Upgrader{
EnableCompression: true,
}
type subscription struct {
Channel string `json:"subscribe"`
}
// ServeHTTP implements the http.Handler interface, to accept incoming
// websocket connections and serve the necessary JavaScript file. The
// Controller should be set up to handle the "/live-view/" path.
func (c *Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/live-view/socket":
s, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
subscriptions := make(map[string]*channel)
ss := &synchronizedWebsocket{Conn: s}
for {
_, p, err := s.ReadMessage()
if err != nil {
s.Close()
break
}
var sub subscription
err = json.Unmarshal(p, &sub)
if err == nil && sub.Channel != "" {
ch := c.channelByID(sub.Channel)
if ch != nil && ch.socket == nil {
subscriptions[sub.Channel] = ch
ch.socket = ss
ch.view.HandleEvent(Event{Event: "connect"})
}
continue
}
var evt Event
err = json.Unmarshal(p, &evt)
if err == nil && evt.Event != "" {
ch := subscriptions[evt.ChannelID]
if ch != nil {
ch.view.HandleEvent(evt)
}
continue
}
}
// The socket has shut down. Notify views, and clean up.
for _, ch := range subscriptions {
c.removeChannel(ch)
ch.view.HandleEvent(Event{Event: "disconnect"})
}
case "/live-view/live-view.js":
w.Header().Set("Content-Type", "application/javascript")
w.Header().Set("Cache-Control", "max-age=86400")
c := brotli.HTTPCompressor(w, r)
defer c.Close()
c.Write(liveViewJS)
default:
http.NotFound(w, r)
}
}
// Render renders v to e, wrapped in a div that makes it a live view. The View
// is automatically Registered if it was not registered already.
func (c *Controller) Render(w io.Writer, v View) {
ch := c.channelForView(v)
if ch == nil {
c.Register(v)
ch = c.channelForView(v)
}
fmt.Fprintf(w, `<div data-live-view="%s"><div>`, ch.id)
v.Render(w)
io.WriteString(w, `</div></div>`)
}
// JSTag is the script tags that should be included in pages that use live
// views.
const JSTag template.HTML = `<script src="https://cdn.jsdelivr.net/gh/patrick-steele-idem/morphdom/dist/morphdom-umd.js"></script>
<script src="/live-view/live-view.js"></script>`
type update struct {
Render string `json:"render"`
ID string `json:"id"`
}
// Update re-renders v and sends the updated HTML to the client.
func (c *Controller) Update(v View) error {
ch := c.channelForView(v)
if ch == nil {
return errors.New("channel not found")
}
if ch.socket == nil {
return fmt.Errorf("channel %s not connected yet", ch.id)
}
b := new(strings.Builder)
e := escaper.New(b)
v.Render(e)
u := update{
Render: b.String(),
ID: ch.id,
}
p, err := json.Marshal(u)
if err != nil {
return err
}
return ch.socket.WriteMessage(websocket.TextMessage, p)
}
type synchronizedWebsocket struct {
*websocket.Conn
m sync.Mutex
}
func (s *synchronizedWebsocket) WriteMessage(messageType int, data []byte) error {
s.m.Lock()
defer s.m.Unlock()
return s.Conn.WriteMessage(messageType, data)
}