forked from keybase/kbfs
/
shared_keybase_transport.go
80 lines (68 loc) · 2.42 KB
/
shared_keybase_transport.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"sync"
"github.com/keybase/backoff"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
"golang.org/x/net/context"
)
// NewSharedKeybaseConnection returns a connection that tries to
// connect to the local keybase daemon.
func NewSharedKeybaseConnection(kbCtx Context, config Config,
handler rpc.ConnectionHandler) *rpc.Connection {
transport := &SharedKeybaseTransport{kbCtx: kbCtx}
constBackoff := backoff.NewConstantBackOff(RPCReconnectInterval)
opts := rpc.ConnectionOpts{
WrapErrorFunc: libkb.WrapError,
TagsFunc: libkb.LogTagsFromContext,
ReconnectBackoff: func() backoff.BackOff { return constBackoff },
}
return rpc.NewConnectionWithTransport(
handler, transport, libkb.ErrorUnwrapper{},
logger.LogOutputWithDepthAdder{Logger: config.MakeLogger("")}, opts)
}
// SharedKeybaseTransport is a ConnectionTransport implementation that
// uses a shared local socket to a keybase daemon.
type SharedKeybaseTransport struct {
kbCtx Context
// Protects everything below.
mutex sync.Mutex
transport rpc.Transporter
stagedTransport rpc.Transporter
}
// Test that SharedKeybaseTransport fully implements the
// ConnectionTransport interface.
var _ rpc.ConnectionTransport = (*SharedKeybaseTransport)(nil)
// Dial is an implementation of the ConnectionTransport interface.
func (kt *SharedKeybaseTransport) Dial(ctx context.Context) (
rpc.Transporter, error) {
_, transport, _, err := kt.kbCtx.GetSocket(true)
if err != nil {
return nil, err
}
kt.mutex.Lock()
defer kt.mutex.Unlock()
kt.stagedTransport = transport
return transport, nil
}
// IsConnected is an implementation of the ConnectionTransport interface.
func (kt *SharedKeybaseTransport) IsConnected() bool {
kt.mutex.Lock()
defer kt.mutex.Unlock()
return kt.transport != nil && kt.transport.IsConnected()
}
// Finalize is an implementation of the ConnectionTransport interface.
func (kt *SharedKeybaseTransport) Finalize() {
kt.mutex.Lock()
defer kt.mutex.Unlock()
kt.transport = kt.stagedTransport
kt.stagedTransport = nil
}
// Close is an implementation of the ConnectionTransport interface.
func (kt *SharedKeybaseTransport) Close() {
// Since this is a shared connection, do nothing.
}