forked from bolt-observer/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_unix.go
99 lines (80 loc) · 2.13 KB
/
connection_unix.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
package lightning
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
r "net/rpc"
"os"
"time"
"github.com/golang/glog"
rpc "github.com/powerman/rpc-codec/jsonrpc2"
)
// ClnUnixConnection represents a UNIX domain socket.
type ClnUnixConnection struct {
Client *rpc.Client
ClnConnection
}
// Compile time check for the interface.
var _ ClnConnectionAPI = &ClnUnixConnection{}
// NewUnixConnection create a new CLN connection.
func NewUnixConnection(socketType string, address string) *ClnUnixConnection {
ret := &ClnUnixConnection{}
client, err := rpc.Dial(socketType, address)
if err != nil {
glog.Warningf("Got error: %v", err)
return nil
}
if client == nil {
glog.Warningf("Got nil client")
return nil
}
ret.Client = client
return ret
}
// Call calls serviceMethod with args and fills reply with response.
func (l *ClnUnixConnection) Call(ctx context.Context, serviceMethod string, args any, reply any, timeout time.Duration) error {
if l.Client == nil {
return fmt.Errorf("no client")
}
c := make(chan *r.Call, 1)
go l.Client.Go(serviceMethod, args, reply, c)
select {
case call := <-c:
return call.Error
case <-ctx.Done():
return os.ErrDeadlineExceeded
case <-time.After(timeout):
return os.ErrDeadlineExceeded
}
}
// StreamResponse is meant for streaming responses it calls serviceMethod with args and returns an io.Reader.
func (l *ClnUnixConnection) StreamResponse(ctx context.Context, serviceMethod string, args any) (io.Reader, error) {
if l.Client == nil {
return nil, fmt.Errorf("no client")
}
c := make(chan *r.Call, 1)
var reply json.RawMessage
go l.Client.Go(serviceMethod, args, &reply, c)
select {
case call := <-c:
if call.Error != nil {
return nil, call.Error
}
// TODO: currently we are cheating a bit here by serializing and unserializing
// since rpc.Client does not allow us to directly get response as io.Reader
b, err := json.Marshal(reply)
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
case <-ctx.Done():
return nil, os.ErrDeadlineExceeded
}
}
// Cleanup does the cleanup.
func (l *ClnUnixConnection) Cleanup() {
// Noop
return
}