-
Notifications
You must be signed in to change notification settings - Fork 55
/
client.go
693 lines (560 loc) · 14.2 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Package rendezvous provides a client for magic wormhole rendezvous servers.
package rendezvous
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"sync/atomic"
"github.com/psanford/wormhole-william/internal/crypto"
"github.com/psanford/wormhole-william/rendezvous/internal/msgs"
"github.com/psanford/wormhole-william/version"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
// NewClient returns a Rendezvous client. URL is the websocket
// url of Rendezvous server. SideID is the id for the client to
// use to distinguish messages in a mailbox from the other client.
// AppID is the application identity string of the client.
//
// Two clients can only communicate if they have the same AppID.
func NewClient(url, sideID, appID string, opts ...ClientOption) *Client {
c := &Client{
url: url,
sideID: sideID,
appID: appID,
pendingMsgs: make([]pendingMsg, 0, 2),
mailboxMsgs: make([]MailboxEvent, 0),
pendingMailboxWaiters: make(map[uint32]chan int),
pendingMsgWaiters: make(map[uint32]chan uint32),
}
for _, opt := range opts {
opt.setValue(c)
}
return c
}
type pendingMsg struct {
// id will be monotonically increasing for each received
// message so waiters can know if they have seen all the
// pending messages or not
id uint32
msgType string
raw []byte
}
type Client struct {
url string
appID string
sideID string
mailboxID string
nameplate string
agentString string
agentVersion string
wsClient *websocket.Conn
mailboxMsgs []MailboxEvent
pendingMailboxWaiters map[uint32]chan int
pendingMsgIDCntr uint32
pendingMsgWaiterCntr uint32
sendCmdMu sync.Mutex
pendingMsgMu sync.Mutex
pendingMsgs []pendingMsg
pendingMsgWaiters map[uint32]chan uint32
clientState clientState
err error
}
type MailboxEvent struct {
// Error will be non nil if an error occurred
// while waiting for messages
Error error
Side string
Phase string
Body string
}
type clientState int32
const (
statePending clientState = iota
stateOpen
stateError
stateClosed
)
func (c clientState) String() string {
switch c {
case statePending:
return "Pending"
case stateOpen:
return "Open"
case stateError:
return "Error"
case stateClosed:
return "Closed"
default:
return fmt.Sprintf("Unknown client state: %d", c)
}
}
func (c *Client) closeWithError(err error) {
atomic.StoreInt32((*int32)(&c.clientState), int32(stateError))
c.err = err
}
type ConnectInfo struct {
MOTD string
CurrentCLIVersion string
}
// Connect opens a connection and binds to the rendezvous server. It
// returns the Welcome information the server responds with.
func (c *Client) Connect(ctx context.Context) (*ConnectInfo, error) {
swapped := atomic.CompareAndSwapInt32((*int32)(&c.clientState), int32(statePending), int32(stateOpen))
if !swapped {
return nil, fmt.Errorf("current client state %s != pending, cannot connect", c.clientState)
}
var err error
c.wsClient, _, err = websocket.Dial(ctx, c.url, nil)
if err != nil {
wrappedErr := fmt.Errorf("dial %s: %s", c.url, err)
c.closeWithError(wrappedErr)
return nil, wrappedErr
}
go c.readMessages(ctx)
var welcome msgs.Welcome
err = c.readMsg(ctx, &welcome)
if err != nil {
c.closeWithError(err)
return nil, err
}
if welcome.Welcome.Error != "" {
err := fmt.Errorf("server error: %s", err)
c.closeWithError(err)
return nil, err
}
if err := c.bind(ctx, c.sideID, c.appID); err != nil {
c.closeWithError(err)
return nil, err
}
info := ConnectInfo{
MOTD: welcome.Welcome.MOTD,
CurrentCLIVersion: welcome.Welcome.CurrentCLIVersion,
}
return &info, nil
}
func (c *Client) searchPendingMsgs(ctx context.Context, msgType string) *pendingMsg {
c.pendingMsgMu.Lock()
defer c.pendingMsgMu.Unlock()
for i, pending := range c.pendingMsgs {
if pending.msgType == msgType {
copyMsg := pending
orig := c.pendingMsgs
c.pendingMsgs = c.pendingMsgs[:i]
c.pendingMsgs = append(c.pendingMsgs, orig[i+1:]...)
return ©Msg
}
}
return nil
}
func (c *Client) registerWaiter() (uint32, <-chan uint32) {
nextID := atomic.AddUint32(&c.pendingMsgWaiterCntr, 1)
ch := make(chan uint32, 1)
c.pendingMsgMu.Lock()
defer c.pendingMsgMu.Unlock()
c.pendingMsgWaiters[nextID] = ch
if len(c.pendingMsgs) > 0 {
ch <- c.pendingMsgs[len(c.pendingMsgs)-1].id
}
return nextID, ch
}
func (c *Client) deregisterWaiter(id uint32) {
c.pendingMsgMu.Lock()
defer c.pendingMsgMu.Unlock()
delete(c.pendingMsgWaiters, id)
}
func (c *Client) readMsg(ctx context.Context, m interface{}) error {
expectMsgType := msgType(m)
waiterID, ch := c.registerWaiter()
defer c.deregisterWaiter(waiterID)
for {
select {
case <-ch:
case <-ctx.Done():
return ctx.Err()
}
msg := c.searchPendingMsgs(ctx, expectMsgType)
if msg != nil {
err := json.Unmarshal(msg.raw, m)
if err != nil {
wrappedErr := fmt.Errorf("JSON unmarshal: %s", err)
return wrappedErr
}
return nil
}
}
}
func msgType(msg interface{}) string {
ptr := reflect.TypeOf(msg)
if ptr.Kind() != reflect.Ptr {
panic("msg must be a pointer")
}
structType := ptr.Elem()
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
if field.Tag.Get("json") == "type" {
return field.Tag.Get("rendezvous_value")
}
}
return ""
}
// CreateMailbox allocates a nameplate, claims it, and then opens
// the associated mailbox. It returns the nameplate id string.
func (c *Client) CreateMailbox(ctx context.Context) (string, error) {
nameplateResp, err := c.allocateNameplate(ctx)
if err != nil {
c.closeWithError(err)
return "", err
}
claimed, err := c.claimNameplate(ctx, nameplateResp.Nameplate)
if err != nil {
c.closeWithError(err)
return "", err
}
c.nameplate = nameplateResp.Nameplate
err = c.openMailbox(ctx, claimed.Mailbox)
if err != nil {
c.closeWithError(err)
return "", err
}
return nameplateResp.Nameplate, nil
}
// AttachMailbox opens an existing mailbox and releases the associated
// nameplate.
func (c *Client) AttachMailbox(ctx context.Context, nameplate string) error {
claimed, err := c.claimNameplate(ctx, nameplate)
if err != nil {
c.closeWithError(err)
return err
}
c.nameplate = nameplate
err = c.openMailbox(ctx, claimed.Mailbox)
if err != nil {
c.closeWithError(err)
return err
}
return nil
}
// ListNameplates returns a list of active nameplates on the
// rendezvous server.
func (c *Client) ListNameplates(ctx context.Context) ([]string, error) {
var (
nameplatesResp msgs.Nameplates
listReq msgs.List
)
_, err := c.sendAndWait(ctx, &listReq)
if err != nil {
return nil, err
}
err = c.readMsg(ctx, &nameplatesResp)
if err != nil {
return nil, err
}
outNameplates := make([]string, len(nameplatesResp.Nameplates))
for i, np := range nameplatesResp.Nameplates {
outNameplates[i] = np.ID
}
return outNameplates, nil
}
// AddMessage adds a message to the opened mailbox. This must be called after
// either CreateMailbox or AttachMailbox.
func (c *Client) AddMessage(ctx context.Context, phase, body string) error {
addReq := msgs.Add{
Phase: phase,
Body: body,
}
_, err := c.sendAndWait(ctx, &addReq)
return err
}
// MsgChan returns a channel of Mailbox message events.
// Each message from the other side will be published to this channel.
func (c *Client) MsgChan(ctx context.Context) <-chan MailboxEvent {
resultChan := make(chan MailboxEvent)
go c.recvMailboxMsgs(ctx, resultChan)
return resultChan
}
func (c *Client) recvMailboxMsgs(ctx context.Context, outCh chan MailboxEvent) {
id, notified := c.registerMailboxWaiter()
defer c.deregisterMailboxWaiter(id)
nextOffset := 0
var nextMsg *MailboxEvent
OUTER:
for {
// loop over all pending messages we haven't sent
// to outCh yet
for {
c.pendingMsgMu.Lock()
if len(c.mailboxMsgs)-1 >= nextOffset {
nextMsg = &c.mailboxMsgs[nextOffset]
}
c.pendingMsgMu.Unlock()
if nextMsg == nil {
break
}
nextOffset++
if nextMsg.Side != c.sideID {
// Only send messages from the other side
outCh <- *nextMsg
if c.nameplate != "" {
// release the nameplate when we get a response from the other side
c.releaseNameplate(ctx, c.nameplate)
c.nameplate = ""
}
}
nextMsg = nil
}
// wait for any new mailbox messages
_, ok := <-notified
if !ok {
break OUTER
}
}
close(outCh)
}
func (c *Client) registerMailboxWaiter() (uint32, <-chan int) {
nextID := atomic.AddUint32(&c.pendingMsgWaiterCntr, 1)
ch := make(chan int, 1)
c.pendingMsgMu.Lock()
defer c.pendingMsgMu.Unlock()
c.pendingMailboxWaiters[nextID] = ch
return nextID, ch
}
func (c *Client) deregisterMailboxWaiter(id uint32) {
c.pendingMsgMu.Lock()
defer c.pendingMsgMu.Unlock()
delete(c.pendingMailboxWaiters, id)
}
type Mood string
const (
Happy Mood = "happy"
Lonely Mood = "lonely"
Scary Mood = "scary"
Errory Mood = "errory"
)
// Close sends mood to server and then tears down the connection.
func (c *Client) Close(ctx context.Context, mood Mood) error {
if mood == "" {
mood = Happy
}
if c.wsClient == nil {
return errors.New("Close called on non-open rendezvous connection")
}
defer func() {
if c.wsClient != nil {
c.wsClient.Close(websocket.StatusNormalClosure, "")
c.wsClient = nil
}
}()
var closedResp msgs.ClosedResp
closeReq := msgs.Close{
Mood: string(mood),
Mailbox: c.mailboxID,
}
_, err := c.sendAndWait(ctx, &closeReq)
if err != nil {
return err
}
err = c.readMsg(ctx, &closedResp)
return err
}
// sendAndWait sends a message to the rendezvous server and waits
// for an ack response.
func (c *Client) sendAndWait(ctx context.Context, msg interface{}) (*msgs.Ack, error) {
id, err := c.prepareMsg(msg)
if err != nil {
return nil, err
}
c.sendCmdMu.Lock()
err = wsjson.Write(ctx, c.wsClient, msg)
if err != nil {
c.sendCmdMu.Unlock()
return nil, err
}
var ack msgs.Ack
err = c.readMsg(ctx, &ack)
if err != nil {
c.sendCmdMu.Unlock()
return nil, err
}
c.sendCmdMu.Unlock()
if ack.ID != id {
return nil, fmt.Errorf("got ack for different message. got %s send: %+v", ack.ID, msg)
}
return &ack, nil
}
// prepareMsg populates the ID and Type fields for a message.
// It returns the ID string or an error.
func (c *Client) prepareMsg(msg interface{}) (string, error) {
id := crypto.RandHex(2)
ptr := reflect.TypeOf(msg)
if ptr.Kind() != reflect.Ptr {
return "", errors.New("msg must be a pointer")
}
st := ptr.Elem()
val := reflect.ValueOf(msg).Elem()
var (
foundType bool
foundID bool
)
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
if field.Name == "Type" {
msgType, _ := field.Tag.Lookup("rendezvous_value")
if msgType == "" {
return "", errors.New("type filed missing rendezvous_value struct tag")
}
ff := val.Field(i)
ff.SetString(msgType)
foundType = true
} else if field.Name == "ID" {
ff := val.Field(i)
ff.SetString(id)
foundID = true
}
}
if !foundID || !foundType {
return id, errors.New("msg type missing required field(s): Type and/or ID")
}
return id, nil
}
func (c *Client) agentID() (string, string) {
agent := c.agentString
if agent == "" {
agent = version.AgentString
}
v := c.agentVersion
if v == "" {
v = version.AgentVersion
}
return agent, v
}
func (c *Client) bind(ctx context.Context, side, appID string) error {
agent, version := c.agentID()
bind := msgs.Bind{
Side: side,
AppID: appID,
ClientVersion: []string{agent, version},
}
_, err := c.sendAndWait(ctx, &bind)
return err
}
func (c *Client) allocateNameplate(ctx context.Context) (*msgs.AllocatedResp, error) {
var (
allocReq msgs.Allocate
allocedResp msgs.AllocatedResp
)
_, err := c.sendAndWait(ctx, &allocReq)
if err != nil {
return nil, err
}
err = c.readMsg(ctx, &allocedResp)
if err != nil {
return nil, err
}
return &allocedResp, nil
}
func (c *Client) claimNameplate(ctx context.Context, nameplate string) (*msgs.ClaimedResp, error) {
var claimResp msgs.ClaimedResp
claimReq := msgs.Claim{
Nameplate: nameplate,
}
_, err := c.sendAndWait(ctx, &claimReq)
if err != nil {
return nil, err
}
err = c.readMsg(ctx, &claimResp)
if err != nil {
return nil, err
}
return &claimResp, nil
}
func (c *Client) releaseNameplate(ctx context.Context, nameplate string) error {
var releasedResp msgs.ReleasedResp
releaseReq := msgs.Release{
Nameplate: nameplate,
}
_, err := c.sendAndWait(ctx, &releaseReq)
if err != nil {
return err
}
err = c.readMsg(ctx, &releasedResp)
if err != nil {
return err
}
return nil
}
func (c *Client) openMailbox(ctx context.Context, mailbox string) error {
c.pendingMsgMu.Lock()
c.mailboxID = mailbox
c.pendingMsgMu.Unlock()
open := msgs.Open{
Mailbox: mailbox,
}
_, err := c.sendAndWait(ctx, &open)
return err
}
// readMessages reads off the websocket and dispatches messages
// to either pendingMsg or pendingMailboxMsg.
func (c *Client) readMessages(ctx context.Context) {
for {
if err := ctx.Err(); err != nil {
c.closeWithError(err)
break
}
_, msg, err := c.wsClient.Read(ctx)
if err != nil {
wrappedErr := fmt.Errorf("WS Read: %s", err)
c.closeWithError(wrappedErr)
break
}
var genericMsg msgs.GenericServerMsg
err = json.Unmarshal(msg, &genericMsg)
if err != nil {
wrappedErr := fmt.Errorf("JSON unmarshal: %s", err)
c.closeWithError(wrappedErr)
break
}
if genericMsg.Type == "message" {
var mm msgs.Message
err := json.Unmarshal(msg, &mm)
if err != nil {
wrappedErr := fmt.Errorf("JSON unmarshal: %s", err)
c.closeWithError(wrappedErr)
break
}
mboxMsg := MailboxEvent{
Side: mm.Side,
Phase: mm.Phase,
Body: mm.Body,
}
c.pendingMsgMu.Lock()
c.mailboxMsgs = append(c.mailboxMsgs, mboxMsg)
maxOffset := len(c.mailboxMsgs) - 1
for _, waiter := range c.pendingMailboxWaiters {
select {
case waiter <- maxOffset:
default:
}
}
c.pendingMsgMu.Unlock()
} else {
nextID := atomic.AddUint32(&c.pendingMsgIDCntr, 1)
c.pendingMsgMu.Lock()
c.pendingMsgs = append(c.pendingMsgs, pendingMsg{
id: nextID,
msgType: genericMsg.Type,
raw: msg,
})
for _, waiter := range c.pendingMsgWaiters {
select {
case waiter <- nextID:
default:
}
}
c.pendingMsgMu.Unlock()
}
}
}