-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
syncUpdateDeviceMetadata.go
77 lines (68 loc) · 2.14 KB
/
syncUpdateDeviceMetadata.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
package client
import (
"context"
"fmt"
"github.com/plgd-dev/hub/v2/pkg/log"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
"github.com/plgd-dev/hub/v2/resource-aggregate/cqrs/eventbus"
"github.com/plgd-dev/hub/v2/resource-aggregate/cqrs/utils"
"github.com/plgd-dev/hub/v2/resource-aggregate/events"
)
type updateDeviceMetadataHandler struct {
correlationID string
res chan *events.DeviceMetadataUpdated
}
func newUpdateDeviceMetadataHandler(correlationID string) *updateDeviceMetadataHandler {
return &updateDeviceMetadataHandler{
correlationID: correlationID,
res: make(chan *events.DeviceMetadataUpdated, 1),
}
}
func (h *updateDeviceMetadataHandler) Handle(ctx context.Context, iter eventbus.Iter) (err error) {
for {
ev, ok := iter.Next(ctx)
if !ok {
return iter.Err()
}
var s events.DeviceMetadataUpdated
if ev.EventType() == s.EventType() {
if err := ev.Unmarshal(&s); err != nil {
return err
}
if s.GetAuditContext().GetCorrelationId() == h.correlationID {
select {
case h.res <- &s:
default:
}
return nil
}
}
}
}
func (h *updateDeviceMetadataHandler) recv(ctx context.Context) (*events.DeviceMetadataUpdated, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case v := <-h.res:
return v, nil
}
}
// SyncUpdateDeviceMetadata sends update device metadata command to resource aggregate and wait for metadata updated event from eventbus.
func (c *Client) SyncUpdateDeviceMetadata(ctx context.Context, owner string, req *commands.UpdateDeviceMetadataRequest) (*events.DeviceMetadataUpdated, error) {
h := newUpdateDeviceMetadataHandler(req.GetCorrelationId())
subject := utils.GetDeviceMetadataEventSubject(owner, req.GetDeviceId(), (&events.DeviceMetadataUpdated{}).EventType())
obs, err := c.subscriber.Subscribe(ctx, req.GetCorrelationId(), subject, h)
if err != nil {
return nil, fmt.Errorf("cannot subscribe to eventbus: %w", err)
}
defer func() {
if errC := obs.Close(); errC != nil {
log.Errorf("update device metadata: %w", errC)
}
}()
_, err = c.UpdateDeviceMetadata(ctx, req)
if err != nil {
return nil, err
}
return h.recv(ctx)
}