-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
260 lines (234 loc) · 5.63 KB
/
client.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
253
254
255
256
257
258
259
260
package main
import (
"cmp"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"slices"
"strconv"
"time"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/gorilla/websocket"
"github.com/abennett/ttt/pkg"
)
var ErrTooManyRedirects = errors.New("too many redirects")
var baseStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
Align(lipgloss.Center)
var columns = []table.Column{
{Title: "User", Width: 10},
{Title: "Result", Width: 6},
}
type client struct {
user string
endpoint string
table table.Model
updates chan []pkg.RollResult
done chan struct{}
err error
}
func connectLoop(wsUrl string) (*websocket.Conn, error) {
for x := 0; x < 3; x++ {
slog.Debug("attempting connection", "url", wsUrl)
conn, resp, err := websocket.DefaultDialer.Dial(wsUrl, nil)
slog.Debug("connection attempted",
"resp", resp,
"error", err)
if err != nil {
if resp != nil {
_, _ = io.Copy(os.Stderr, resp.Body)
}
return nil, err
}
if resp != nil && resp.StatusCode >= 300 && resp.StatusCode < 400 {
wsUrl = resp.Header.Get("Location")
slog.Debug("redirecting", "location", wsUrl)
continue
}
return conn, nil
}
return nil, ErrTooManyRedirects
}
func hostUrl(endpoint, room string) (string, error) {
parsed, err := url.Parse(endpoint)
if err != nil {
return "", err
}
var scheme string
switch parsed.Scheme {
case "https", "wss":
scheme = "wss"
case "http", "ws":
scheme = "ws"
default:
return "", fmt.Errorf("%s is not a valid protocol", parsed.Scheme)
}
parsed.Scheme = scheme
parsed.Path = room
return parsed.String(), nil
}
func setupLogger(user string, logFile *string) error {
logWriter := io.Discard
if logFile != nil && *logFile != "" {
f, err := os.OpenFile(*logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
return err
}
logWriter = f
}
h := slog.NewTextHandler(logWriter, &slog.HandlerOptions{Level: slog.LevelDebug})
logger := slog.New(h)
logger = logger.With("user", user)
slog.SetDefault(logger)
return nil
}
func newClient(host, room, user string) (*client, error) {
err := setupLogger(user, logFile)
if err != nil {
return nil, fmt.Errorf("unable to setup log file: %w", err)
}
endpoint, err := hostUrl(host, room)
if err != nil {
return nil, err
}
slog.Debug("using endpoint", "endpoint", endpoint)
t := table.New(
table.WithColumns(columns),
table.WithHeight(0),
table.WithFocused(false),
)
s := table.DefaultStyles()
s.Header = s.Header.Foreground(lipgloss.Color("#01c5d1"))
s.Selected = s.Selected.Foreground(lipgloss.NoColor{}).Bold(false)
t.SetStyles(s)
return &client{
user: user,
table: t,
endpoint: endpoint,
updates: make(chan []pkg.RollResult),
done: make(chan struct{}),
}, nil
}
func errorCmd(err error) tea.Cmd {
return func() tea.Msg {
return err
}
}
func (c client) Init() tea.Cmd {
slog.Debug("running Init")
conn, err := connectLoop(c.endpoint)
if err != nil {
return errorCmd(err)
}
req := pkg.RollRequest{
User: c.user,
}
err = conn.WriteJSON(req)
if err != nil {
return errorCmd(fmt.Errorf("unable to write json: %w", err))
}
go waitClose(conn, c.done)
go updateLoop(conn, c.updates)
return c.readUpdate()
}
func resultsToRows(rrs []pkg.RollResult) []table.Row {
rows := make([]table.Row, len(rrs))
for idx, rr := range rrs {
rows[idx] = table.Row{rr.User, strconv.Itoa(rr.Result)}
}
return rows
}
func (c *client) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
slog.Debug("updating model", "msg", msg)
switch msg := msg.(type) {
case []pkg.RollResult:
slog.Debug("roll result")
c.table.SetHeight(len(msg))
c.table.SetRows(resultsToRows(msg))
return c, c.readUpdate()
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
c.done <- struct{}{}
return c, tea.Quit
}
case error:
slog.Error("exiting for error", "error", msg)
c.err = msg
return c, tea.Quit
}
slog.Debug("no update")
return c, nil
}
func (c client) View() string {
slog.Debug("rerendering view")
if c.err != nil {
return fmt.Sprintln(c.err)
}
return baseStyle.Render(c.table.View()) + "\n"
}
func (c client) readUpdate() tea.Cmd {
slog.Debug("reading update")
return func() tea.Msg {
slog.Debug("reading from channel")
update := <-c.updates
slog.Debug("read from channel")
return update
}
}
func waitClose(conn *websocket.Conn, done <-chan struct{}) {
<-done
slog.Debug("closing connection")
err := conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
time.Now().Add(time.Second),
)
if err != nil {
slog.Error("close control message failed", "error", err)
}
}
func updateLoop(conn *websocket.Conn, updates chan<- []pkg.RollResult) {
slog.Debug("running update loop")
var currentVersion int
for {
var room pkg.Room
err := conn.ReadJSON(&room)
if err != nil {
slog.Error(err.Error())
return
}
slog.Debug("message recieved", "version", room.Version)
if currentVersion == room.Version {
slog.Debug("version hasn't changed, continuing")
continue
}
slog.Debug("new version")
rolls := make([]pkg.RollResult, len(room.Rolls))
var idx int
for _, rr := range room.Rolls {
rolls[idx] = rr
idx++
}
slices.SortFunc(rolls, func(a, b pkg.RollResult) int {
return cmp.Compare(b.Result, a.Result)
})
slog.Debug("pushing rolls on channel")
updates <- rolls
currentVersion = room.Version
}
}
func rollRemote(ctx context.Context, args []string) error {
c, err := newClient(args[0], args[1], args[2])
if err != nil {
return err
}
_, err = tea.NewProgram(c).Run()
return err
}