forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editorState.go
103 lines (96 loc) · 2.38 KB
/
editorState.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
package main
import (
"context"
"io"
"net/http"
"time"
"github.com/google/uuid"
ws "nhooyr.io/websocket"
)
func (a *goBlog) serveEditorStateSync(w http.ResponseWriter, r *http.Request) {
// Get blog
blog, bc := a.getBlog(r)
// Open websocket connection
c, err := ws.Accept(w, r, &ws.AcceptOptions{CompressionMode: ws.CompressionContextTakeover})
if err != nil {
return
}
c.SetReadLimit(1 << 20) // 1MB
defer c.Close(ws.StatusNormalClosure, "")
// Store connection to be able to send updates
connectionId := uuid.NewString()
bc.esws.Store(connectionId, c)
defer bc.esws.Delete(connectionId)
// Set cancel context
ctx, cancel := context.WithTimeout(r.Context(), time.Hour*6)
defer cancel()
// Send initial content
if r.URL.Query().Get("initial") == "1" {
initialState, err := a.getEditorStateFromDatabase(ctx, blog)
if err != nil {
return
}
if initialState != nil {
w, err := c.Writer(ctx, ws.MessageText)
if err != nil {
return
}
_, err = w.Write(initialState)
if err != nil {
return
}
_ = w.Close()
}
}
// Listen for new messages
for {
// Retrieve content
mt, message, err := c.Reader(ctx)
if err != nil {
break
}
if mt != ws.MessageText {
continue
}
messageBytes, err := io.ReadAll(message)
if err != nil {
break
}
// Save editor state
bc.esm.Lock()
a.updateEditorStateInDatabase(ctx, blog, messageBytes)
bc.esm.Unlock()
// Send editor state to other connections
a.sendNewEditorStateToAllConnections(ctx, bc, connectionId, messageBytes)
}
}
func (a *goBlog) sendNewEditorStateToAllConnections(ctx context.Context, bc *configBlog, origin string, state []byte) {
bc.esws.Range(func(key, value any) bool {
if key == origin {
return true
}
c, ok := value.(*ws.Conn)
if !ok {
return true
}
w, err := c.Writer(ctx, ws.MessageText)
if err != nil {
bc.esws.Delete(key)
return true
}
defer w.Close()
_, err = w.Write(state)
if err != nil {
bc.esws.Delete(key)
return true
}
return true
})
}
const editorStateCacheKey = "editorstate_"
func (a *goBlog) updateEditorStateInDatabase(ctx context.Context, blog string, state []byte) {
_ = a.db.cachePersistentlyContext(ctx, editorStateCacheKey+blog, state)
}
func (a *goBlog) getEditorStateFromDatabase(ctx context.Context, blog string) ([]byte, error) {
return a.db.retrievePersistentCacheContext(ctx, editorStateCacheKey+blog)
}