-
Notifications
You must be signed in to change notification settings - Fork 0
/
observeResource.go
309 lines (273 loc) · 7.54 KB
/
observeResource.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
package client
import (
"context"
"fmt"
"io"
"strings"
"sync"
"sync/atomic"
"github.com/google/uuid"
"github.com/plgd-dev/device/client/core"
pkgError "github.com/plgd-dev/device/pkg/error"
"github.com/plgd-dev/device/pkg/net/coap"
"github.com/plgd-dev/go-coap/v2/message"
codecOcf "github.com/plgd-dev/kit/v2/codec/ocf"
kitSync "github.com/plgd-dev/kit/v2/sync"
)
type observerCodec struct {
contentFormat message.MediaType
}
// ContentFormat propagates the CoAP media type.
func (c observerCodec) ContentFormat() message.MediaType { return c.contentFormat }
// Encode propagates the payload without any conversions.
func (c observerCodec) Encode(v interface{}) ([]byte, error) {
return nil, pkgError.NotSupported()
}
// Decode validates the content format and
// propagates the payload to v as *[]byte without any conversions.
func (c observerCodec) Decode(m *message.Message, v interface{}) error {
if v == nil {
return nil
}
if m.Body == nil {
return fmt.Errorf("unexpected empty body")
}
p, ok := v.(**message.Message)
if !ok {
return fmt.Errorf("expected **message.Message instead of %T", v)
}
*p = m
return nil
}
type observationsHandler struct {
client *Client
device *core.Device
id string
sync.Mutex
observationID string
lastMessage atomic.Value
observations *kitSync.Map
}
type decodeFunc = func(v interface{}, codec coap.Codec) error
type observationHandler struct {
handler core.ObservationHandler
codec coap.Codec
lock sync.Mutex
isClosed bool
firstMessage decodeFunc
}
func createDecodeFunc(message *message.Message) decodeFunc {
var l sync.Mutex
return func(v interface{}, codec coap.Codec) error {
l.Lock()
defer l.Unlock()
_, err := message.Body.Seek(0, io.SeekStart)
if err != nil {
return err
}
return codec.Decode(message, v)
}
}
func (h *observationHandler) handleMessageLocked(ctx context.Context, decode decodeFunc) {
if decode == nil {
return
}
if h.isClosed {
return
}
h.handler.Handle(ctx, func(v interface{}) error {
return decode(v, h.codec)
})
}
func (h *observationHandler) HandleMessage(ctx context.Context, decode decodeFunc) {
h.lock.Lock()
defer h.lock.Unlock()
h.firstMessage = nil
h.handleMessageLocked(ctx, decode)
}
func (h *observationHandler) HandleFirstMessage() {
h.lock.Lock()
defer h.lock.Unlock()
if h.firstMessage == nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
h.handleMessageLocked(ctx, h.firstMessage)
}
func (h *observationHandler) OnClose() {
h.lock.Lock()
defer h.lock.Unlock()
if h.isClosed {
return
}
h.isClosed = true
h.handler.OnClose()
}
func (h *observationHandler) Error(err error) {
h.lock.Lock()
defer h.lock.Unlock()
if h.isClosed {
return
}
h.isClosed = true
h.handler.Error(err)
}
func getObservationID(resourceCacheID, resourceObservationID string) string {
return strings.Join([]string{resourceCacheID, resourceObservationID}, "/")
}
func parseIDs(id string) (string, string, error) {
v := strings.Split(id, "/")
if len(v) != 2 {
return "", "", fmt.Errorf("invalid ID")
}
return v[0], v[1], nil
}
func (c *Client) ObserveResource(
ctx context.Context,
deviceID string,
href string,
handler core.ObservationHandler,
opts ...ObserveOption,
) (observationID string, _ error) {
cfg := observeOptions{
codec: codecOcf.VNDOCFCBORCodec{},
discoveryConfiguration: core.DefaultDiscoveryConfiguration(),
}
for _, o := range opts {
cfg = o.applyOnObserve(cfg)
}
resourceObservationID, err := uuid.NewRandom()
if err != nil {
return "", err
}
key := uuid.NewSHA1(uuid.NameSpaceURL, []byte(deviceID+href+"?if="+cfg.resourceInterface)).String()
val, loaded := c.observeResourceCache.LoadOrStoreWithFunc(key, func(value interface{}) interface{} {
h := value.(*observationsHandler)
h.Lock()
return h
}, func() interface{} {
h := observationsHandler{
observations: kitSync.NewMap(),
client: c,
id: key,
}
h.Lock()
return &h
})
h := val.(*observationsHandler)
defer h.Unlock()
lastMessage := h.lastMessage.Load()
var firstMessage decodeFunc
if lastMessage != nil {
firstMessage = lastMessage.(decodeFunc)
}
obsHandler := observationHandler{
handler: handler,
codec: cfg.codec,
firstMessage: firstMessage,
}
h.observations.Store(resourceObservationID.String(), &obsHandler)
if loaded {
go obsHandler.HandleFirstMessage()
return getObservationID(key, resourceObservationID.String()), nil
}
d, links, err := c.GetDevice(ctx, deviceID, WithDiscoveryConfiguration(cfg.discoveryConfiguration))
if err != nil {
return "", err
}
link, err := core.GetResourceLink(links, href)
if err != nil {
return "", err
}
observationID, err = d.ObserveResourceWithCodec(ctx, link, observerCodec{contentFormat: cfg.codec.ContentFormat()}, h, cfg.opts...)
if err != nil {
return "", err
}
dev, _ := c.deviceCache.UpdateOrStoreDevice(d)
h.observationID = observationID
h.device = dev
return getObservationID(key, resourceObservationID.String()), err
}
func (c *Client) StopObservingResource(ctx context.Context, observationID string) (bool, error) {
resourceCacheID, internalResourceObservationID, err := parseIDs(observationID)
if err != nil {
return false, err
}
var resourceObservationID string
var dev *core.Device
c.observeResourceCache.ReplaceWithFunc(resourceCacheID, func(oldValue interface{}, oldLoaded bool) (newValue interface{}, doDelete bool) {
if !oldLoaded {
return nil, true
}
h := oldValue.(*observationsHandler)
resourceObservationID = h.observationID
_, ok := h.observations.PullOut(internalResourceObservationID)
if !ok {
return h, false
}
if h.observations.Length() == 0 {
dev = h.device
return nil, true
}
return h, false
})
if dev == nil {
return false, nil
}
_ = c.deviceCache.TryToChangeDeviceExpirationToDefault(dev.DeviceID())
ok, err := dev.StopObservingResource(ctx, resourceObservationID)
if err != nil {
return false, fmt.Errorf("failed to stop resource observation(%s) in device(%s): %w", observationID, dev.DeviceID(), err)
}
return ok, nil
}
func (c *Client) closeObservingResource(ctx context.Context, o *observationsHandler) {
_, ok := c.observeResourceCache.PullOut(o.id)
if !ok {
return
}
o.Lock()
defer o.Unlock()
if o.device != nil {
deviceID := o.device.DeviceID()
if _, err := o.device.StopObservingResource(ctx, o.observationID); err != nil {
c.errors(fmt.Errorf("failed to stop resources observation in device(%s): %w", deviceID, err))
}
_ = c.deviceCache.TryToChangeDeviceExpirationToDefault(deviceID)
}
}
func (o *observationsHandler) Handle(ctx context.Context, body coap.DecodeFunc) {
var message *message.Message
err := body(&message)
if err != nil {
o.Error(err)
return
}
decode := createDecodeFunc(message)
o.lastMessage.Store(decode)
observations := make([]*observationHandler, 0, 4)
o.observations.Range(func(key, value interface{}) bool {
observations = append(observations, value.(*observationHandler))
return true
})
for _, h := range observations {
h.HandleMessage(ctx, decode)
}
}
func (o *observationsHandler) OnClose() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
o.client.closeObservingResource(ctx, o)
for _, h := range o.observations.PullOutAll() {
h.(*observationHandler).handler.OnClose()
}
}
func (o *observationsHandler) Error(err error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
o.client.closeObservingResource(ctx, o)
for _, h := range o.observations.PullOutAll() {
h.(*observationHandler).handler.Error(err)
}
}