-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
deviceMetadataSnapshotTaken.go
632 lines (578 loc) · 25.7 KB
/
deviceMetadataSnapshotTaken.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package events
import (
"context"
"fmt"
"time"
"github.com/plgd-dev/hub/v2/pkg/opentelemetry/propagation"
pkgTime "github.com/plgd-dev/hub/v2/pkg/time"
commands "github.com/plgd-dev/hub/v2/resource-aggregate/commands"
"github.com/plgd-dev/hub/v2/resource-aggregate/cqrs/aggregate"
"github.com/plgd-dev/hub/v2/resource-aggregate/cqrs/eventstore"
"github.com/plgd-dev/kit/v2/strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
const eventTypeDeviceMetadataSnapshotTaken = "devicemetadatasnapshottaken"
func (d *DeviceMetadataSnapshotTaken) Version() uint64 {
return d.GetEventMetadata().GetVersion()
}
func (d *DeviceMetadataSnapshotTaken) Marshal() ([]byte, error) {
return proto.Marshal(d)
}
func (d *DeviceMetadataSnapshotTaken) Unmarshal(b []byte) error {
return proto.Unmarshal(b, d)
}
func (d *DeviceMetadataSnapshotTaken) EventType() string {
return eventTypeDeviceMetadataSnapshotTaken
}
func (d *DeviceMetadataSnapshotTaken) AggregateID() string {
return commands.MakeStatusResourceUUID(d.GetDeviceId()).String()
}
func (d *DeviceMetadataSnapshotTaken) GroupID() string {
return d.GetDeviceId()
}
func (d *DeviceMetadataSnapshotTaken) IsSnapshot() bool {
return true
}
func (d *DeviceMetadataSnapshotTaken) ETag() *eventstore.ETagData {
return nil
}
func (d *DeviceMetadataSnapshotTaken) Timestamp() time.Time {
return pkgTime.Unix(0, d.GetEventMetadata().GetTimestamp())
}
func (d *DeviceMetadataSnapshotTaken) ServiceID() (string, bool) {
return d.GetDeviceMetadataUpdated().GetConnection().GetServiceId(), true
}
func (d *DeviceMetadataSnapshotTaken) Types() []string {
return nil
}
func (d *DeviceMetadataSnapshotTaken) CopyData(event *DeviceMetadataSnapshotTaken) {
d.DeviceId = event.GetDeviceId()
d.DeviceMetadataUpdated = event.GetDeviceMetadataUpdated()
d.UpdatePendings = event.GetUpdatePendings()
d.EventMetadata = event.GetEventMetadata()
}
func (d *DeviceMetadataSnapshotTaken) CheckInitialized() bool {
return d.GetDeviceId() != "" &&
d.GetEventMetadata() != nil &&
(d.GetDeviceMetadataUpdated() != nil ||
d.GetUpdatePendings() != nil)
}
func (d *DeviceMetadataSnapshotTaken) HandleDeviceMetadataUpdated(_ context.Context, upd *DeviceMetadataUpdated, confirm bool) (bool, error) {
index := -1
updatePendings := d.GetUpdatePendings()
for i, event := range updatePendings {
if event.GetAuditContext().GetCorrelationId() == upd.GetAuditContext().GetCorrelationId() {
index = i
break
}
}
if confirm && index < 0 {
return false, status.Errorf(codes.InvalidArgument, "cannot find twin synchronization update pending event with correlationId('%v')", upd.GetAuditContext().GetCorrelationId())
}
if index >= 0 {
updatePendings = append(updatePendings[:index], updatePendings[index+1:]...)
d.UpdatePendings = updatePendings
}
if d.GetDeviceMetadataUpdated().Equal(upd) {
return false, nil
}
d.DeviceId = upd.GetDeviceId()
d.DeviceMetadataUpdated = upd
d.EventMetadata = upd.GetEventMetadata()
return true, nil
}
func (d *DeviceMetadataSnapshotTaken) HandleDeviceMetadataSnapshotTaken(_ context.Context, s *DeviceMetadataSnapshotTaken) {
d.CopyData(s)
}
func (d *DeviceMetadataSnapshotTaken) HandleDeviceMetadataUpdatePending(_ context.Context, updatePending *DeviceMetadataUpdatePending) error {
now := time.Now()
if updatePending.IsExpired(now) {
d.DeviceId = updatePending.GetDeviceId()
d.EventMetadata = updatePending.GetEventMetadata()
// for events from eventstore we do nothing
return nil
}
for _, event := range d.GetUpdatePendings() {
if event.IsExpired(now) {
continue
}
if event.GetAuditContext().GetCorrelationId() == updatePending.GetAuditContext().GetCorrelationId() {
return status.Errorf(codes.InvalidArgument, "device metadata update pending with correlationId('%v') already exist", updatePending.GetAuditContext().GetCorrelationId())
}
}
d.DeviceId = updatePending.GetDeviceId()
d.EventMetadata = updatePending.GetEventMetadata()
d.UpdatePendings = append(d.UpdatePendings, updatePending)
return nil
}
func (d *DeviceMetadataSnapshotTaken) Handle(ctx context.Context, iter eventstore.Iter) error {
for {
eu, ok := iter.Next(ctx)
if !ok {
break
}
if eu.EventType() == "" {
return status.Errorf(codes.Internal, "cannot determine type of event")
}
switch eu.EventType() {
case (&DeviceMetadataSnapshotTaken{}).EventType():
var s DeviceMetadataSnapshotTaken
if err := eu.Unmarshal(&s); err != nil {
return status.Errorf(codes.Internal, "%v", err)
}
d.HandleDeviceMetadataSnapshotTaken(ctx, &s)
case (&DeviceMetadataUpdated{}).EventType():
var s DeviceMetadataUpdated
if err := eu.Unmarshal(&s); err != nil {
return status.Errorf(codes.Internal, "%v", err)
}
_, _ = d.HandleDeviceMetadataUpdated(ctx, &s, false)
case (&DeviceMetadataUpdatePending{}).EventType():
var s DeviceMetadataUpdatePending
if err := eu.Unmarshal(&s); err != nil {
return status.Errorf(codes.Internal, "%v", err)
}
_ = d.HandleDeviceMetadataUpdatePending(ctx, &s)
}
}
return iter.Err()
}
func timeToLive2ValidUntil(timeToLive int64) int64 {
if timeToLive == 0 {
return 0
}
return pkgTime.UnixNano(time.Now().Add(time.Duration(timeToLive)))
}
func (d *DeviceMetadataSnapshotTaken) cancelDeviceMetadataUpdate(ctx context.Context, req *commands.ConfirmDeviceMetadataUpdateRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
ev := DeviceMetadataUpdated{
DeviceId: req.GetDeviceId(),
Connection: d.GetDeviceMetadataUpdated().GetConnection(),
TwinSynchronization: d.GetDeviceMetadataUpdated().GetTwinSynchronization(),
TwinEnabled: d.GetDeviceMetadataUpdated().GetTwinEnabled(),
Canceled: true,
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
ok, err := d.HandleDeviceMetadataUpdated(ctx, &ev, true)
if !ok {
return nil, err
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTaken) updateTwinEnabled(ctx context.Context, req *commands.ConfirmDeviceMetadataUpdateRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
twinSynchronization := d.GetDeviceMetadataUpdated().GetTwinSynchronization()
if twinSynchronization == nil {
twinSynchronization = &commands.TwinSynchronization{
State: commands.TwinSynchronization_OUT_OF_SYNC,
CommandMetadata: req.GetCommandMetadata(),
}
}
if req.GetCommandMetadata().GetConnectionId() == d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetCommandMetadata().GetConnectionId() {
switch req.GetTwinEnabled() {
case true:
if twinSynchronization.GetState() == commands.TwinSynchronization_DISABLED {
twinSynchronization.State = commands.TwinSynchronization_OUT_OF_SYNC
}
case false:
twinSynchronization.State = commands.TwinSynchronization_DISABLED
}
}
ev := DeviceMetadataUpdated{
DeviceId: req.GetDeviceId(),
Connection: d.GetDeviceMetadataUpdated().GetConnection(),
TwinEnabled: req.GetTwinEnabled(),
TwinSynchronization: twinSynchronization,
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
ok, err := d.HandleDeviceMetadataUpdated(ctx, &ev, true)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTakenForCommand) updateTwinForceSynchronization(ctx context.Context, req *commands.ConfirmDeviceMetadataUpdateRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
if !req.GetTwinForceSynchronization() {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization with invalid forceSynchronization(%v)", req.GetTwinForceSynchronization())
}
twinSynchronization := d.GetDeviceMetadataUpdated().GetTwinSynchronization()
if twinSynchronization == nil {
twinSynchronization = &commands.TwinSynchronization{
CommandMetadata: req.GetCommandMetadata(),
}
}
twinSynchronization.State = commands.TwinSynchronization_OUT_OF_SYNC
twinSynchronization.ForceSynchronizationAt = em.GetTimestamp()
ev := DeviceMetadataUpdated{
DeviceId: req.GetDeviceId(),
Connection: d.GetDeviceMetadataUpdated().GetConnection(),
TwinEnabled: true,
TwinSynchronization: twinSynchronization,
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
ok, err := d.HandleDeviceMetadataUpdated(ctx, &ev, true)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTakenForCommand) ConfirmDeviceMetadataUpdateRequest(ctx context.Context, req *commands.ConfirmDeviceMetadataUpdateRequest, newVersion uint64, cancel bool) ([]eventstore.Event, error) {
if req.GetCommandMetadata() == nil {
return nil, status.Errorf(codes.InvalidArgument, errInvalidCommandMetadata)
}
em := MakeEventMeta(req.GetCommandMetadata().GetConnectionId(), req.GetCommandMetadata().GetSequence(), newVersion, d.hubID)
ac := commands.NewAuditContext(d.userID, req.GetCorrelationId(), d.owner)
_, is_confirm_twin_enabled := req.GetConfirm().(*commands.ConfirmDeviceMetadataUpdateRequest_TwinEnabled)
_, is_confirm_twin_force_synchronization := req.GetConfirm().(*commands.ConfirmDeviceMetadataUpdateRequest_TwinForceSynchronization)
switch {
case cancel:
return d.cancelDeviceMetadataUpdate(ctx, req, em, ac)
case is_confirm_twin_enabled:
return d.updateTwinEnabled(ctx, req, em, ac)
case is_confirm_twin_force_synchronization:
return d.updateTwinForceSynchronization(ctx, req, em, ac)
default:
return nil, status.Errorf(codes.InvalidArgument, "unknown confirm type(%T)", req.GetConfirm())
}
}
func (d *DeviceMetadataSnapshotTakenForCommand) CancelPendingMetadataUpdatesRequest(ctx context.Context, req *commands.CancelPendingMetadataUpdatesRequest, newVersion uint64) ([]eventstore.Event, error) {
if req.GetCommandMetadata() == nil {
return nil, status.Errorf(codes.InvalidArgument, errInvalidCommandMetadata)
}
correlationIdFilter := strings.MakeSet(req.GetCorrelationIdFilter()...)
events := make([]eventstore.Event, 0, 4)
for _, event := range d.GetUpdatePendings() {
if len(correlationIdFilter) != 0 && !correlationIdFilter.HasOneOf(event.GetAuditContext().GetCorrelationId()) {
continue
}
ev, err := d.ConfirmDeviceMetadataUpdateRequest(ctx, &commands.ConfirmDeviceMetadataUpdateRequest{
DeviceId: req.GetDeviceId(),
CorrelationId: event.GetAuditContext().GetCorrelationId(),
Status: commands.Status_CANCELED,
CommandMetadata: req.GetCommandMetadata(),
}, newVersion+uint64(len(events)), true)
if err == nil {
// errors appears only when command with correlationID doesn't exist
events = append(events, ev...)
}
}
if len(events) == 0 {
return nil, status.Errorf(codes.NotFound, "cannot find commands with correlationID(%v)", req.GetCorrelationIdFilter())
}
return events, nil
}
func (d *DeviceMetadataSnapshotTaken) prepareTwinSynchronization() *commands.TwinSynchronization {
twinSynchronization := d.GetDeviceMetadataUpdated().GetTwinSynchronization()
// check if it is new connection
// reset twinSynchronization
if twinSynchronization == nil {
twinSynchronization = &commands.TwinSynchronization{}
}
return twinSynchronization
}
func (d *DeviceMetadataSnapshotTaken) getTwinSynchronizationForConnectedDevice(req *commands.UpdateDeviceMetadataRequest) (*commands.TwinSynchronization, error) {
twinSynchronization := d.prepareTwinSynchronization()
if req.GetConnection().GetId() != d.GetDeviceMetadataUpdated().GetConnection().GetId() || !d.GetDeviceMetadataUpdated().GetConnection().IsOnline() {
if d.GetDeviceMetadataUpdated().GetTwinEnabled() {
twinSynchronization.State = commands.TwinSynchronization_OUT_OF_SYNC
} else {
twinSynchronization.State = commands.TwinSynchronization_DISABLED
}
twinSynchronization.CommandMetadata = req.GetCommandMetadata()
}
return twinSynchronization, nil
}
func (d *DeviceMetadataSnapshotTaken) getTwinSynchronizationForDisconnectedDevice(req *commands.UpdateDeviceMetadataRequest) (*commands.TwinSynchronization, error) {
twinSynchronization := d.prepareTwinSynchronization()
if d.GetDeviceMetadataUpdated().GetConnection().IsOnline() && !req.GetConnection().IsOnline() && d.GetDeviceMetadataUpdated().GetConnection().GetId() != req.GetConnection().GetId() {
// if previous status was online and new status is offline, the connectionId must be the same
return nil, status.Errorf(codes.InvalidArgument, "cannot update connection status online(id='%v') to offline(id='%v'): connectionId mismatch", d.GetDeviceMetadataUpdated().GetConnection().GetId(), req.GetConnection().GetId())
}
if d.GetDeviceMetadataUpdated().GetTwinEnabled() {
twinSynchronization.State = commands.TwinSynchronization_OUT_OF_SYNC
} else {
twinSynchronization.State = commands.TwinSynchronization_DISABLED
}
twinSynchronization.CommandMetadata = req.GetCommandMetadata()
return twinSynchronization, nil
}
func (d *DeviceMetadataSnapshotTaken) updateDeviceConnection(ctx context.Context, req *commands.UpdateDeviceMetadataRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
// it is expected that the device updates the status on its own. no confirmation needed.
req.GetConnection().Id = req.GetCommandMetadata().GetConnectionId()
if req.GetConnection().GetId() == "" {
return nil, status.Errorf(codes.InvalidArgument, "cannot update connection status for empty connectionId")
}
if !req.GetConnection().IsOnline() {
if em.GetVersion() == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot update connection status to offline for not existing device %v", req.GetDeviceId())
}
// set instance service id to empty
req.GetConnection().ServiceId = ""
// set protocol to previous value
req.GetConnection().Protocol = d.GetDeviceMetadataUpdated().GetConnection().GetProtocol()
}
// keep last connected at from the previous event
lastConnectedAt := d.GetDeviceMetadataUpdated().GetConnection().GetConnectedAt()
if req.GetConnection().GetConnectedAt() < lastConnectedAt {
req.GetConnection().ConnectedAt = lastConnectedAt
}
// keep local endpoints from the previous event
if len(req.GetConnection().GetLocalEndpoints()) == 0 {
req.GetConnection().LocalEndpoints = d.GetDeviceMetadataUpdated().GetConnection().GetLocalEndpoints()
}
getTwinSynchronization := d.getTwinSynchronizationForDisconnectedDevice
if req.GetConnection().IsOnline() {
getTwinSynchronization = d.getTwinSynchronizationForConnectedDevice
}
twinSynchronization, err := getTwinSynchronization(req)
if err != nil {
return nil, err
}
ev := DeviceMetadataUpdated{
DeviceId: req.GetDeviceId(),
Connection: req.GetConnection(),
TwinEnabled: d.GetDeviceMetadataUpdated().GetTwinEnabled(),
TwinSynchronization: twinSynchronization,
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
ok, err := d.HandleDeviceMetadataUpdated(ctx, &ev, false)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTaken) prepareTwinSynchronizationToSyncing(twinSynchronization *commands.TwinSynchronization) (bool, error) {
if !d.GetDeviceMetadataUpdated().GetTwinEnabled() {
return false, status.Errorf(codes.InvalidArgument, "cannot update twinSynchronization to %v: twin is disabled", commands.TwinSynchronization_SYNCING)
}
if twinSynchronization.GetSyncingAt() <= 0 {
return false, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization with invalid startedAt(%v)", twinSynchronization.GetSyncingAt())
}
if d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetState() == commands.TwinSynchronization_SYNCING {
if twinSynchronization.GetSyncingAt() > d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetSyncingAt() {
return false, nil
}
}
twinSynchronization.InSyncAt = d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetInSyncAt()
return true, nil
}
func (d *DeviceMetadataSnapshotTaken) prepareTwinSynchronizationToInSync(twinSynchronization *commands.TwinSynchronization) (bool, error) {
if !d.GetDeviceMetadataUpdated().GetTwinEnabled() {
return false, status.Errorf(codes.InvalidArgument, "cannot update twinSynchronization to %v: twin is disabled", commands.TwinSynchronization_IN_SYNC)
}
if twinSynchronization.GetInSyncAt() <= 0 {
return false, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization with invalid finishAt(%v)", twinSynchronization.GetSyncingAt())
}
if d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetState() == commands.TwinSynchronization_IN_SYNC {
if twinSynchronization.GetInSyncAt() < d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetInSyncAt() {
return false, nil
}
}
if d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetState() == commands.TwinSynchronization_SYNCING {
if twinSynchronization.GetInSyncAt() < d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetSyncingAt() {
return false, nil
}
}
twinSynchronization.SyncingAt = d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetSyncingAt()
return true, nil
}
func (d *DeviceMetadataSnapshotTaken) updateDeviceTwinSynchronization(ctx context.Context, req *commands.UpdateDeviceMetadataRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
commandMetadata := req.GetCommandMetadata()
// it is expected that the device updates the status on its own. no confirmation needed.
if commandMetadata.GetConnectionId() == "" {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization for empty connectionId")
}
if commandMetadata.GetConnectionId() != d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetCommandMetadata().GetConnectionId() {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization for different connectionId: get %v, expected %v", commandMetadata.GetConnectionId(), d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetCommandMetadata().GetConnectionId())
}
if em.GetVersion() == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization for not existing device %v", req.GetDeviceId())
}
if commandMetadata.GetSequence() <= d.GetDeviceMetadataUpdated().GetTwinSynchronization().GetCommandMetadata().GetSequence() {
return nil, nil
}
twinSynchronization := req.GetTwinSynchronization()
switch twinSynchronization.GetState() {
case commands.TwinSynchronization_OUT_OF_SYNC:
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin synchronization with invalid state(%v)", twinSynchronization.GetState())
case commands.TwinSynchronization_SYNCING:
if ok, err := d.prepareTwinSynchronizationToSyncing(twinSynchronization); err != nil || !ok {
return nil, err
}
case commands.TwinSynchronization_IN_SYNC:
if ok, err := d.prepareTwinSynchronizationToInSync(twinSynchronization); err != nil || !ok {
return nil, err
}
}
twinSynchronization.CommandMetadata = commandMetadata
ev := DeviceMetadataUpdated{
DeviceId: req.GetDeviceId(),
Connection: d.GetDeviceMetadataUpdated().GetConnection(),
TwinEnabled: d.GetDeviceMetadataUpdated().GetTwinEnabled(),
TwinSynchronization: twinSynchronization,
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
ok, err := d.HandleDeviceMetadataUpdated(ctx, &ev, false)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTaken) updateDeviceTwinEnabled(ctx context.Context, req *commands.UpdateDeviceMetadataRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
if em.GetVersion() == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin enabled for not existing device %v", req.GetDeviceId())
}
ev := DeviceMetadataUpdatePending{
DeviceId: req.GetDeviceId(),
ValidUntil: timeToLive2ValidUntil(req.GetTimeToLive()),
UpdatePending: &DeviceMetadataUpdatePending_TwinEnabled{
TwinEnabled: req.GetTwinEnabled(),
},
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
err := d.HandleDeviceMetadataUpdatePending(ctx, &ev)
if err != nil {
return nil, err
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTakenForCommand) updateDeviceTwinForceSynchronization(ctx context.Context, req *commands.UpdateDeviceMetadataRequest, em *EventMetadata, ac *commands.AuditContext) ([]eventstore.Event, error) {
if em.GetVersion() == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin enabled for not existing device %v", req.GetDeviceId())
}
if !req.GetTwinForceSynchronization() {
return nil, status.Errorf(codes.InvalidArgument, "cannot update twin force synchronization with invalid forceSynchronization(%v)", req.GetTwinForceSynchronization())
}
ev := DeviceMetadataUpdatePending{
DeviceId: req.GetDeviceId(),
ValidUntil: timeToLive2ValidUntil(req.GetTimeToLive()),
UpdatePending: &DeviceMetadataUpdatePending_TwinForceSynchronization{
TwinForceSynchronization: req.GetTwinForceSynchronization(),
},
AuditContext: ac,
EventMetadata: em,
OpenTelemetryCarrier: propagation.TraceFromCtx(ctx),
}
err := d.HandleDeviceMetadataUpdatePending(ctx, &ev)
if err != nil {
return nil, err
}
return []eventstore.Event{&ev}, nil
}
func (d *DeviceMetadataSnapshotTakenForCommand) updateDeviceMetadataRequest(ctx context.Context, req *commands.UpdateDeviceMetadataRequest, newVersion uint64) ([]eventstore.Event, error) {
if req.GetCommandMetadata() == nil {
return nil, status.Errorf(codes.InvalidArgument, errInvalidCommandMetadata)
}
em := MakeEventMeta(req.GetCommandMetadata().GetConnectionId(), req.GetCommandMetadata().GetSequence(), newVersion, d.hubID)
ac := commands.NewAuditContext(d.userID, req.GetCorrelationId(), d.owner)
_, is_update_twin_enabled := req.GetUpdate().(*commands.UpdateDeviceMetadataRequest_TwinEnabled)
_, is_process_twin_force_synchronization := req.GetUpdate().(*commands.UpdateDeviceMetadataRequest_TwinForceSynchronization)
switch {
case req.GetConnection() != nil:
return d.updateDeviceConnection(ctx, req, em, ac)
case req.GetTwinSynchronization() != nil:
return d.updateDeviceTwinSynchronization(ctx, req, em, ac)
case is_update_twin_enabled:
return d.updateDeviceTwinEnabled(ctx, req, em, ac)
case is_process_twin_force_synchronization:
return d.updateDeviceTwinForceSynchronization(ctx, req, em, ac)
default:
return nil, status.Errorf(codes.InvalidArgument, "unknown update type(%T)", req.GetUpdate())
}
}
func (d *DeviceMetadataSnapshotTakenForCommand) updateToOfflineRequest(ctx context.Context, req *UpdateDeviceToOfflineRequest, newVersion uint64) ([]eventstore.Event, error) {
if req.GetDeviceId() == "" {
return nil, status.Errorf(codes.InvalidArgument, "cannot update device to offline for empty deviceId")
}
if d.GetDeviceMetadataUpdated().GetConnection().GetServiceId() != req.ServiceID {
// ignore request from different service
return nil, nil
}
em := MakeEventMeta(d.GetDeviceMetadataUpdated().GetConnection().GetId(), d.GetEventMetadata().GetSequence()+1, newVersion, d.hubID)
// we need to use owner from previous event, because it's determine event-bus subject where the event will be published
ac := commands.NewAuditContext(d.userID, "", d.GetDeviceMetadataUpdated().GetAuditContext().GetOwner())
return d.updateDeviceConnection(ctx, &commands.UpdateDeviceMetadataRequest{
DeviceId: req.GetDeviceId(),
Update: &commands.UpdateDeviceMetadataRequest_Connection{
Connection: &commands.Connection{
Status: commands.Connection_OFFLINE,
},
},
CommandMetadata: &commands.CommandMetadata{
Sequence: em.GetSequence(),
ConnectionId: em.GetConnectionId(),
},
}, em, ac)
}
type UpdateDeviceToOfflineRequest struct {
DeviceID string
ServiceID string
}
func (r *UpdateDeviceToOfflineRequest) GetDeviceId() string {
return r.DeviceID
}
func (d *DeviceMetadataSnapshotTakenForCommand) HandleCommand(ctx context.Context, cmd aggregate.Command, newVersion uint64) ([]eventstore.Event, error) {
switch req := cmd.(type) {
case *commands.UpdateDeviceMetadataRequest:
return d.updateDeviceMetadataRequest(ctx, req, newVersion)
case *UpdateDeviceToOfflineRequest:
return d.updateToOfflineRequest(ctx, req, newVersion)
case *commands.ConfirmDeviceMetadataUpdateRequest:
return d.ConfirmDeviceMetadataUpdateRequest(ctx, req, newVersion, false)
case *commands.CancelPendingMetadataUpdatesRequest:
return d.CancelPendingMetadataUpdatesRequest(ctx, req, newVersion)
}
return nil, fmt.Errorf("unknown command (%T)", cmd)
}
func (d *DeviceMetadataSnapshotTaken) TakeSnapshot(version uint64) (eventstore.Event, bool) {
var s DeviceMetadataSnapshotTaken
s.CopyData(d)
s.EventMetadata = MakeEventMeta(d.GetEventMetadata().GetConnectionId(), d.GetEventMetadata().GetSequence(), version, d.GetEventMetadata().GetHubId())
return &s, true
}
type DeviceMetadataSnapshotTakenForCommand struct {
userID string
owner string
hubID string
*DeviceMetadataSnapshotTaken
}
func NewDeviceMetadataSnapshotTakenForCommand(userID string, owner string, hubID string) *DeviceMetadataSnapshotTakenForCommand {
return &DeviceMetadataSnapshotTakenForCommand{
DeviceMetadataSnapshotTaken: NewDeviceMetadataSnapshotTaken(),
userID: userID,
owner: owner,
hubID: hubID,
}
}
func NewDeviceMetadataSnapshotTaken() *DeviceMetadataSnapshotTaken {
return &DeviceMetadataSnapshotTaken{
DeviceMetadataUpdated: &DeviceMetadataUpdated{
TwinEnabled: true,
},
EventMetadata: &EventMetadata{},
}
}