/
client.go
318 lines (277 loc) · 8.36 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
package client
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net/url"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"github.com/plgd-dev/cloud/grpc-gateway/pb"
"github.com/plgd-dev/cloud/resource-aggregate/cqrs"
kitNetGrpc "github.com/plgd-dev/kit/net/grpc"
"github.com/plgd-dev/kit/strings"
)
type ApplicationCallback interface {
GetRootCertificateAuthorities() ([]*x509.Certificate, error)
}
type OnboardOption = func() interface{}
type subscription = interface {
Cancel() (wait func(), err error)
}
type Config struct {
GatewayAddress string
AccessTokenURL string
}
func validateURL(URL string) error {
if URL == "" {
return fmt.Errorf("empty url")
}
_, err := url.Parse(URL)
if err != nil {
return err
}
return nil
}
// NewClient constructs a new client client. For every call there is expected jwt token for grpc stored in context.
func NewClient(accessTokenURL string, client pb.GrpcGatewayClient) (*Client, error) {
err := validateURL(accessTokenURL)
if err != nil {
return nil, fmt.Errorf("invalid AccessTokenURL: %w", err)
}
cl := Client{
gateway: client,
subscriptions: make(map[string]subscription),
accessTokenURL: accessTokenURL,
}
return &cl, nil
}
// NewClientFromConfig constructs a new client client. For every call there is expected jwt token for grpc stored in context.
func NewClientFromConfig(cfg *Config, tlsCfg *tls.Config) (*Client, error) {
if cfg == nil || cfg.GatewayAddress == "" {
return nil, fmt.Errorf("missing client client config")
}
keepAlive := keepalive.ClientParameters{
Time: 10 * time.Second,
PermitWithoutStream: true,
}
conn, err := grpc.Dial(cfg.GatewayAddress, grpc.WithKeepaliveParams(keepAlive), grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)))
if err != nil {
return nil, fmt.Errorf("cannot create certificate authority client: %w", err)
}
ocfGW := pb.NewGrpcGatewayClient(conn)
client, err := NewClient(cfg.AccessTokenURL, ocfGW)
if err != nil {
conn.Close()
return nil, err
}
client.conn = conn
return client, nil
}
// Client for interacting with the client.
type Client struct {
gateway pb.GrpcGatewayClient
conn *grpc.ClientConn
accessTokenURL string
subscriptionsLock sync.Mutex
subscriptions map[string]subscription
}
func (c *Client) GrpcGatewayClient() pb.GrpcGatewayClient {
return c.gateway
}
func (c *Client) popSubscriptions() map[string]subscription {
c.subscriptionsLock.Lock()
defer c.subscriptionsLock.Unlock()
s := c.subscriptions
c.subscriptions = make(map[string]subscription)
return s
}
func (c *Client) popSubscription(ID string) (subscription, error) {
c.subscriptionsLock.Lock()
defer c.subscriptionsLock.Unlock()
v, ok := c.subscriptions[ID]
if !ok {
return nil, fmt.Errorf("cannot find observation %v", ID)
}
delete(c.subscriptions, ID)
return v, nil
}
func (c *Client) insertSubscription(ID string, s subscription) {
c.subscriptionsLock.Lock()
defer c.subscriptionsLock.Unlock()
c.subscriptions[ID] = s
}
func (c *Client) Close(ctx context.Context) error {
var errors []error
for _, s := range c.popSubscriptions() {
wait, err := s.Cancel()
if err != nil {
errors = append(errors, err)
continue
}
wait()
}
if c.conn != nil {
err := c.conn.Close()
if err != nil {
errors = append(errors, err)
}
}
if len(errors) != 0 {
return fmt.Errorf("%v", errors)
}
return nil
}
func (c *Client) GetAccessTokenURL(ctx context.Context) (string, error) {
return c.accessTokenURL, nil
}
// GetDevicesViaCallback returns devices. JWT token must be stored in context for grpc call.
func (c *Client) GetDevicesViaCallback(ctx context.Context, deviceIDs, resourceTypes []string, callback func(pb.Device)) error {
it := c.GetDevicesIterator(ctx, deviceIDs, resourceTypes...)
defer it.Close()
for {
var v pb.Device
if !it.Next(&v) {
break
}
callback(v)
}
return it.Err
}
// GetResourceLinksViaCallback returns resource links of devices. JWT token must be stored in context for grpc call.
func (c *Client) GetResourceLinksViaCallback(ctx context.Context, deviceIDs, resourceTypes []string, callback func(*pb.ResourceLink)) error {
it := c.GetResourceLinksIterator(ctx, deviceIDs, resourceTypes...)
defer it.Close()
for {
var v pb.ResourceLink
if !it.Next(&v) {
break
}
callback(&v)
}
return it.Err
}
type TypeCallback struct {
Type string
Callback func(pb.ResourceValue)
}
func MakeTypeCallback(resourceType string, callback func(pb.ResourceValue)) TypeCallback {
return TypeCallback{Type: resourceType, Callback: callback}
}
// RetrieveResourcesByType gets contents of resources by resource types. JWT token must be stored in context for grpc call.
func (c *Client) RetrieveResourcesByType(
ctx context.Context,
deviceIDs []string,
typeCallbacks ...TypeCallback,
) error {
tc := make(map[string]func(pb.ResourceValue), len(typeCallbacks))
resourceTypes := make([]string, 0, len(typeCallbacks))
for _, c := range typeCallbacks {
tc[c.Type] = c.Callback
resourceTypes = append(resourceTypes, c.Type)
}
it := c.RetrieveResourcesIterator(ctx, nil, deviceIDs, resourceTypes...)
defer it.Close()
for {
var v pb.ResourceValue
if !it.Next(&v) {
break
}
for _, rt := range resourceTypes {
if strings.SliceContains(v.Types, rt) {
tc[rt](v)
break
}
}
}
return it.Err
}
// GetDevicesIterator gets devices. JWT token must be stored in context for grpc call.
// Next queries the next resource value.
// Returns false when failed or having no more items.
// Check it.Err for errors.
// Usage:
// for {
// var v MyStruct
// if !it.Next(ctx, &v) {
// break
// }
// }
// if it.Err != nil {
// }
func (c *Client) GetDevicesIterator(ctx context.Context, deviceIDs []string, resourceTypes ...string) *kitNetGrpc.Iterator {
r := pb.GetDevicesRequest{DeviceIdsFilter: deviceIDs, TypeFilter: resourceTypes}
return kitNetGrpc.NewIterator(c.gateway.GetDevices(ctx, &r))
}
// GetResourceLinksIterator gets devices. JWT token must be stored in context for grpc call.
// Next queries the next resource value.
// Returns false when failed or having no more items.
// Check it.Err for errors.
// Usage:
// for {
// var v MyStruct
// if !it.Next(ctx, &v) {
// break
// }
// }
// if it.Err != nil {
// }
func (c *Client) GetResourceLinksIterator(ctx context.Context, deviceIDs []string, resourceTypes ...string) *kitNetGrpc.Iterator {
r := pb.GetResourceLinksRequest{DeviceIdsFilter: deviceIDs, TypeFilter: resourceTypes}
return kitNetGrpc.NewIterator(c.gateway.GetResourceLinks(ctx, &r))
}
// RetrieveResourcesIterator gets resources contents. JWT token must be stored in context for grpc call.
// Next queries the next resource value.
// Returns false when failed or having no more items.
// Check it.Err for errors.
// Usage:
// for {
// var v MyStruct
// if !it.Next(ctx, &v) {
// break
// }
// }
// if it.Err != nil {
// }
func (c *Client) RetrieveResourcesIterator(ctx context.Context, resourceIDs []*pb.ResourceId, deviceIDs []string, resourceTypes ...string) *kitNetGrpc.Iterator {
r := pb.RetrieveResourcesValuesRequest{ResourceIdsFilter: resourceIDs, DeviceIdsFilter: deviceIDs, TypeFilter: resourceTypes}
return kitNetGrpc.NewIterator(c.gateway.RetrieveResourcesValues(ctx, &r))
}
type ResourceIDCallback struct {
ResourceID *pb.ResourceId
Callback func(pb.ResourceValue)
}
func MakeResourceIDCallback(deviceID, href string, callback func(pb.ResourceValue)) ResourceIDCallback {
return ResourceIDCallback{ResourceID: &pb.ResourceId{
DeviceId: deviceID,
Href: href,
}, Callback: callback}
}
// RetrieveResourcesByResourceIDs gets resources contents by resourceIDs. JWT token must be stored in context for grpc call.
func (c *Client) RetrieveResourcesByResourceIDs(
ctx context.Context,
resourceIDsCallbacks ...ResourceIDCallback,
) error {
tc := make(map[string]func(pb.ResourceValue), len(resourceIDsCallbacks))
resourceIDs := make([]*pb.ResourceId, 0, len(resourceIDsCallbacks))
for _, c := range resourceIDsCallbacks {
tc[cqrs.MakeResourceId(c.ResourceID.DeviceId, c.ResourceID.Href)] = c.Callback
resourceIDs = append(resourceIDs, c.ResourceID)
}
it := c.RetrieveResourcesIterator(ctx, resourceIDs, nil)
defer it.Close()
var v pb.ResourceValue
for {
if !it.Next(&v) {
break
}
c, ok := tc[cqrs.MakeResourceId(v.GetResourceId().GetDeviceId(), v.GetResourceId().GetHref())]
if ok {
c(v)
}
}
return it.Err
}