/
server.go
214 lines (182 loc) · 4.87 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
package main
import (
"context"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/rotisserie/eris"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"google.golang.org/protobuf/proto"
"github.com/ngld/knossos/packages/api/client"
"github.com/ngld/knossos/packages/libknossos/pkg/api"
"github.com/ngld/knossos/packages/libknossos/pkg/storage"
"github.com/ngld/knossos/packages/libknossos/pkg/twirp"
)
var (
wsLock = sync.Mutex{}
wsConnections = make([]*websocket.Conn, 0)
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return strings.HasPrefix(r.Header.Get("Origin"), "http://localhost")
},
}
)
func main() {
log.Logger = log.Output(getConsoleWriter(os.Stdout))
zerolog.ErrorStackMarshaler = func(err error) interface{} {
return eris.ToString(err, true)
}
log.Logger = log.Logger.With().Caller().Stack().Logger()
profilePath := ""
switch runtime.GOOS {
case "windows":
profilePath = filepath.Join(os.Getenv("AppData"), "Knossos")
case "darwin":
profilePath = filepath.Join(os.Getenv("HOME"), "Library/Application Support/Knossos")
case "linux":
profilePath = os.Getenv("XDG_STATE_HOME")
if profilePath == "" {
profilePath = os.Getenv("XDG_CONFIG_HOME")
}
if profilePath == "" {
profilePath = filepath.Join(os.Getenv("HOME"), ".knossos")
} else {
profilePath = filepath.Join(profilePath, "knossos")
}
}
if profilePath == "" {
log.Fatal().Msg("Failed to determine profile path")
}
log.Info().Msg("Initialising libknossos")
ctx := context.Background()
knParams := api.KnossosCtxParams{
LogCallback: logCallback,
MessageCallback: msgDispatcher,
SettingsPath: profilePath,
ResourcePath: "/does/not/exist",
}
ctx = api.WithKnossosContext(ctx, knParams)
err := storage.Open(ctx)
if err != nil {
log.Fatal().Err(err).Msg("Failed to open database")
}
log.Info().Msg("Starting server")
twirpServer, err := twirp.NewServer()
if err != nil {
log.Fatal().Err(err).Msg("Failed to start server")
}
//nolint:forcetypeassert // We know the result type of twirp.NewServer()
twirpPrefix := twirpServer.(client.TwirpServer).PathPrefix()
router := mux.NewRouter()
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Access-Control-Allow-Origin", "*")
rw.Header().Set("Access-Control-Allow-Headers", "content-type")
if r.Method == "OPTIONS" {
rw.WriteHeader(200)
return
}
ctx := api.WithKnossosContext(r.Context(), knParams)
next.ServeHTTP(rw, r.WithContext(ctx))
})
})
router.PathPrefix(twirpPrefix).Handler(twirpServer)
router.PathPrefix("/ws").HandlerFunc(wsHandler)
router.PathPrefix("/ref").HandlerFunc(refHandler)
muxServer := http.Server{
Handler: router,
Addr: "localhost:8100",
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
}
err = muxServer.ListenAndServe()
if err != nil {
log.Fatal().Err(err).Msg("Failed to listen")
}
}
func wsHandler(rw http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(rw, r, nil)
if err != nil {
log.Error().Err(err).Msg("Failed to accept incoming WS connection")
rw.WriteHeader(500)
return
}
go func() {
for {
_, _, err := conn.NextReader()
if err != nil {
conn.Close()
wsLock.Lock()
for idx, c := range wsConnections {
if c == conn {
wsConnections = append(wsConnections[0:idx], wsConnections[idx+1:]...)
break
}
}
wsLock.Unlock()
break
}
}
}()
wsLock.Lock()
wsConnections = append(wsConnections, conn)
wsLock.Unlock()
}
func refHandler(rw http.ResponseWriter, r *http.Request) {
// /ref/
fileID := r.URL.Path[5:]
fileRef, err := storage.GetFile(r.Context(), fileID)
if err != nil {
log.Error().Err(err).Msgf("Failed to look up file ref %s", fileID)
rw.WriteHeader(500)
return
}
localPath := ""
for _, item := range fileRef.Urls {
if strings.HasPrefix(item, "file://") {
localPath = filepath.FromSlash(item[7:])
break
}
}
if localPath == "" {
rw.WriteHeader(404)
return
}
f, err := os.Open(localPath)
if err != nil {
log.Error().Err(err).Msgf("Failed to open %s", localPath)
rw.WriteHeader(500)
return
}
_, err = io.Copy(rw, f)
if err != nil {
log.Error().Err(err).Msgf("Failed to read %s", localPath)
rw.WriteHeader(500)
return
}
}
func msgDispatcher(cse *client.ClientSentEvent) error {
encoded, err := proto.Marshal(cse)
if err != nil {
return eris.Wrap(err, "failed to serialise client message")
}
wsLock.Lock()
defer wsLock.Unlock()
for _, conn := range wsConnections {
err = conn.WriteMessage(websocket.BinaryMessage, encoded)
if err != nil {
log.Error().Err(err).Msg("Failed to send on a WS connection")
}
}
return nil
}