-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
914 lines (799 loc) · 23.6 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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package artifacts
import (
"context"
"fmt"
"go.opencensus.io/stats"
"github.com/insolar/insolar/insolar"
"github.com/insolar/insolar/insolar/bus"
"github.com/insolar/insolar/insolar/flow"
"github.com/insolar/insolar/insolar/payload"
insPulse "github.com/insolar/insolar/insolar/pulse"
"github.com/insolar/insolar/insolar/record"
"github.com/insolar/insolar/instrumentation/inslogger"
"github.com/insolar/insolar/instrumentation/instracer"
"github.com/insolar/insolar/logicrunner/metrics"
"github.com/insolar/insolar/pulse"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
const (
getPendingLimit = 100
)
type localStorage struct {
initialized bool
storage map[insolar.Reference]interface{}
}
func (s *localStorage) Initialized() {
s.initialized = true
}
func (s *localStorage) StoreObject(reference insolar.Reference, descriptor interface{}) {
if s.initialized {
panic("Trying to initialize singleFlightCache after initialization was finished")
}
s.storage[reference] = descriptor
}
func (s *localStorage) Code(reference insolar.Reference) CodeDescriptor {
codeDescI, ok := s.storage[reference]
if !ok {
return nil
}
codeDesc, ok := codeDescI.(CodeDescriptor)
if !ok {
return nil
}
return codeDesc
}
func (s *localStorage) Object(reference insolar.Reference) ObjectDescriptor {
objectDescI, ok := s.storage[reference]
if !ok {
return nil
}
objectDesc, ok := objectDescI.(ObjectDescriptor)
if !ok {
return nil
}
return objectDesc
}
func (s *localStorage) Prototype(reference insolar.Reference) PrototypeDescriptor {
objectDescI, ok := s.storage[reference]
if !ok {
return nil
}
desc, ok := objectDescI.(PrototypeDescriptor)
if !ok {
return nil
}
return desc
}
func newLocalStorage() *localStorage {
return &localStorage{
initialized: false,
storage: make(map[insolar.Reference]interface{}),
}
}
// Client provides concrete API to storage for processing module.
type client struct {
PCS insolar.PlatformCryptographyScheme `inject:""`
PulseAccessor insPulse.Accessor `inject:""`
sender bus.Sender
localStorage *localStorage
}
// NewClient creates new client instance.
func NewClient(sender bus.Sender) Client {
return &client{
sender: sender,
localStorage: newLocalStorage(),
}
}
// registerRequest registers incoming or outgoing request.
func (m *client) registerRequest(
ctx context.Context, req record.Request, msgPayload payload.Payload, sender bus.Sender,
) (*payload.RequestInfo, error) {
affinityRef, err := m.calculateAffinityReference(ctx, req)
if err != nil {
return nil, errors.Wrap(err, "registerRequest: failed to calculate affinity reference")
}
ctx, span := instracer.StartSpan(ctx, "artifactmanager.registerRequest")
instrumenter := instrument(ctx, "registerRequest").err(&err)
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
pl, err := m.sendToLight(ctx, sender, msgPayload, *affinityRef)
if err != nil {
return nil, errors.Wrap(err, "couldn't register request")
}
switch p := pl.(type) {
case *payload.RequestInfo:
return p, nil
case *payload.Error:
if p.Code == payload.CodeFlowCanceled {
err = flow.ErrCancelled
} else {
err = &payload.CodedError{Code: p.Code, Text: p.Text}
}
return nil, err
default:
err = fmt.Errorf("registerRequest: unexpected reply: %#v", p)
return nil, err
}
}
func (m *client) calculateAffinityReference(ctx context.Context, requestRecord record.Request) (*insolar.Reference, error) {
pulseNumber, err := m.pulse(ctx)
if err != nil {
return nil, err
}
return record.CalculateRequestAffinityRef(requestRecord, pulseNumber, m.PCS), nil
}
// RegisterIncomingRequest sends message for incoming request registration,
// returns request record Ref if request successfully created or already exists.
func (m *client) RegisterIncomingRequest(ctx context.Context, request *record.IncomingRequest) (*payload.RequestInfo, error) {
incomingRequest := &payload.SetIncomingRequest{Request: record.Wrap(request)}
// retriesNumber is zero, because we don't retry registering of incoming requests - the caller should
// re-send the request instead.
res, err := m.registerRequest(ctx, request, incomingRequest, m.sender)
if err != nil {
return nil, errors.Wrap(err, "RegisterIncomingRequest")
}
switch {
case res.Result != nil:
stats.Record(ctx, metrics.IncomingRequestsClosed.M(1))
case res.Request != nil:
stats.Record(ctx, metrics.IncomingRequestsDuplicate.M(1))
default:
stats.Record(ctx, metrics.IncomingRequestsNew.M(1))
}
return res, err
}
// RegisterOutgoingRequest sends message for outgoing request registration,
// returns request record Ref if request successfully created or already exists.
func (m *client) RegisterOutgoingRequest(ctx context.Context, request *record.OutgoingRequest) (*payload.RequestInfo, error) {
retrySender := bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 1)
outgoingRequest := &payload.SetOutgoingRequest{Request: record.Wrap(request)}
res, err := m.registerRequest(ctx, request, outgoingRequest, retrySender)
if err != nil {
return nil, errors.Wrap(err, "RegisterOutgoingRequest")
}
switch {
case res.Result != nil:
stats.Record(ctx, metrics.OutgoingRequestsClosed.M(1))
case res.Request != nil:
stats.Record(ctx, metrics.OutgoingRequestsDuplicate.M(1))
default:
stats.Record(ctx, metrics.OutgoingRequestsNew.M(1))
}
return res, err
}
// GetCode returns code from code record by provided reference according to provided machine preference.
//
// This method is used by VM to fetch code for execution.
func (m *client) GetCode(
ctx context.Context, code insolar.Reference,
) (CodeDescriptor, error) {
var (
desc CodeDescriptor
err error
)
desc = m.localStorage.Code(code)
if desc != nil {
return desc, nil
}
instrumenter := instrument(ctx, "GetCode").err(&err)
ctx, span := instracer.StartSpan(ctx, "artifactmanager.GetCode")
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
getCodePl := &payload.GetCode{CodeID: *code.GetLocal()}
pl, err := m.sendToLight(
ctx, bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 1), getCodePl, code,
)
if err != nil {
return nil, errors.Wrap(err, "failed to send GetCode")
}
switch p := pl.(type) {
case *payload.Code:
rec := record.Material{}
err := rec.Unmarshal(p.Record)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal record")
}
virtual := record.Unwrap(&rec.Virtual)
codeRecord, ok := virtual.(*record.Code)
if !ok {
return nil, fmt.Errorf("unexpected record %T", virtual)
}
desc = &codeDescriptor{
ref: code,
machineType: codeRecord.MachineType,
code: codeRecord.Code,
}
return desc, nil
case *payload.Error:
err = errors.New(p.Text)
return nil, err
default:
err = fmt.Errorf("GetCode: unexpected reply: %#v", p)
return nil, err
}
}
// GetObject returns object descriptor with latest state.
func (m *client) GetObject(
ctx context.Context,
head insolar.Reference,
request *insolar.Reference,
) (ObjectDescriptor, error) {
if desc := m.localStorage.Object(head); desc != nil {
return desc, nil
}
getObjectRes, err := m.sendGetObject(ctx, head, request)
if err != nil {
return nil, err
}
if getObjectRes.state.GetIsPrototype() {
return nil, errors.New("record is prototype, not an object")
}
desc := &objectDescriptor{
head: head,
state: *getObjectRes.index.LatestState,
prototype: getObjectRes.state.GetImage(),
memory: getObjectRes.state.GetMemory(),
parent: getObjectRes.index.Parent,
requestID: getObjectRes.lastRequestID,
}
return desc, nil
}
// GetPrototype returns prototype descriptor with latest state.
func (m *client) GetPrototype(
ctx context.Context,
head insolar.Reference,
) (PrototypeDescriptor, error) {
if desc := m.localStorage.Prototype(head); desc != nil {
return desc, nil
}
getObjectRes, err := m.sendGetObject(ctx, head, nil)
if err != nil {
return nil, err
}
if !getObjectRes.state.GetIsPrototype() {
return nil, errors.New("record is not a prototype")
}
ref := getObjectRes.state.GetImage()
if ref == nil {
return nil, errors.New("prototype has no code reference")
}
desc := &prototypeDescriptor{
head: head,
state: *getObjectRes.index.LatestState,
code: *ref,
}
return desc, nil
}
type getObjectRes struct {
index *record.Lifeline
state record.State
lastRequestID *insolar.ID
}
func (m *client) sendGetObject(
ctx context.Context,
head insolar.Reference,
request *insolar.Reference,
) (*getObjectRes, error) {
var (
err error
res = &getObjectRes{}
)
ctx, span := instracer.StartSpan(ctx, "artifactmanager.Getobject")
instrumenter := instrument(ctx, "GetObject").err(&err)
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
if err != nil && err == ErrObjectDeactivated {
err = nil // megahack: threat it 2xx
}
instrumenter.end()
}()
logger := inslogger.FromContext(ctx).WithField("object", head.GetLocal().String())
pl := payload.GetObject{
ObjectID: *head.GetLocal(),
}
if request != nil {
pl.RequestID = request.GetLocal()
}
msg, err := payload.NewMessage(&pl)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal message")
}
r := bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 2)
reps, done := r.SendRole(ctx, msg, insolar.DynamicRoleLightExecutor, head)
defer done()
success := func() bool {
return res.index != nil && res.state != nil
}
for rep := range reps {
replyPayload, err := payload.UnmarshalFromMeta(rep.Payload)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal reply")
}
switch p := replyPayload.(type) {
case *payload.Index:
logger.Debug("reply index")
res.index = &record.Lifeline{}
err := res.index.Unmarshal(p.Index)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal index")
}
res.lastRequestID = p.EarliestRequestID
case *payload.State:
logger.Debug("reply state")
rec := record.Material{}
err = rec.Unmarshal(p.Record)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal state")
}
virtual := record.Unwrap(&rec.Virtual)
s, ok := virtual.(record.State)
if !ok {
err = errors.New("wrong state record")
return nil, err
}
res.state = s
case *payload.Error:
logger.Debug("reply error: ", p.Text)
switch p.Code {
case payload.CodeDeactivated:
err = insolar.ErrDeactivated
return nil, err
default:
err = errors.New(p.Text)
return nil, err
}
default:
err = fmt.Errorf("GetObject: unexpected reply: %#v", p)
return nil, err
}
if success() {
break
}
}
if !success() {
err = ErrNoReply
return nil, err
}
return res, nil
}
func (m *client) GetAbandonedRequest(
ctx context.Context, object, reqRef insolar.Reference,
) (record.Request, error) {
var err error
instrumenter := instrument(ctx, "GetAbandonedRequest").err(&err)
ctx, span := instracer.StartSpan(ctx, "artifacts.GetAbandonedRequest")
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
getRequestPl := &payload.GetRequest{
ObjectID: *object.GetLocal(),
RequestID: *reqRef.GetLocal(),
}
pl, err := m.sendToLight(ctx, m.sender, getRequestPl, object)
if err != nil {
return nil, errors.Wrap(err, "failed to send GetRequest")
}
switch p := pl.(type) {
case *payload.Request:
concrete := record.Unwrap(&p.Request)
var result record.Request
switch v := concrete.(type) {
case *record.IncomingRequest:
result = v
case *record.OutgoingRequest:
result = v
default:
err = fmt.Errorf("GetAbandonedRequest: unexpected message: %#v", concrete)
return nil, err
}
return result, nil
case *payload.Error:
if p.Code == payload.CodeNotFound {
return nil, insolar.ErrNotFound
}
return nil, errors.New(p.Text)
default:
err = errors.Errorf("unexpected reply %T", pl)
return nil, err
}
}
// GetPendings returns a list of pending requests
func (m *client) GetPendings(ctx context.Context, object insolar.Reference) ([]insolar.Reference, error) {
var err error
instrumenter := instrument(ctx, "GetPendings").err(&err)
ctx, span := instracer.StartSpan(ctx, "artifactmanager.GetPendings")
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
getPendingsPl := &payload.GetPendings{
ObjectID: *object.GetLocal(),
Count: getPendingLimit,
}
pl, err := m.sendToLight(ctx, m.sender, getPendingsPl, object)
if err != nil {
return []insolar.Reference{}, errors.Wrap(err, "failed to send GetPendings")
}
switch concrete := pl.(type) {
case *payload.IDs:
res := make([]insolar.Reference, len(concrete.IDs))
for i := range concrete.IDs {
res[i] = *insolar.NewRecordReference(concrete.IDs[i])
}
return res, nil
case *payload.Error:
if concrete.Code == payload.CodeNoPendings {
return []insolar.Reference{}, insolar.ErrNoPendingRequest
}
err = errors.New(concrete.Text)
return []insolar.Reference{}, err
default:
return []insolar.Reference{}, fmt.Errorf("unexpected reply %T", pl)
}
}
// HasPendings returns true if object has unclosed requests.
func (m *client) HasPendings(
ctx context.Context,
object insolar.Reference,
) (bool, error) {
var err error
instrumenter := instrument(ctx, "HasPendings").err(&err)
ctx, span := instracer.StartSpan(ctx, "artifactmanager.HasPendings")
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
hasPendingsPl := &payload.HasPendings{
ObjectID: *object.GetLocal(),
}
pl, err := m.sendToLight(ctx, m.sender, hasPendingsPl, object)
if err != nil {
err = errors.Wrap(err, "failed to send HasPendings")
return false, err
}
switch concrete := pl.(type) {
case *payload.PendingsInfo:
return concrete.HasPendings, nil
case *payload.Error:
err = errors.New(concrete.Text)
return false, err
default:
err = fmt.Errorf("HasPendings: unexpected reply %T", pl)
return false, err
}
}
// DeployCode creates new code record in storage.
//
// CodeRef records are used to activate prototype or as migration code for an object.
func (m *client) DeployCode(ctx context.Context, code []byte, machineType insolar.MachineType) (*insolar.ID, error) {
var err error
ctx, span := instracer.StartSpan(ctx, "artifactmanager.DeployCode")
instrumenter := instrument(ctx, "DeployCode").err(&err)
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
codeRec := record.Code{
Code: code,
MachineType: machineType,
}
virtual := record.Wrap(&codeRec)
buf, err := virtual.Marshal()
if err != nil {
return nil, errors.Wrap(err, "failed to marshal record")
}
currentPN, err := m.pulse(ctx)
if err != nil {
return nil, err
}
h := m.PCS.ReferenceHasher()
recID := *insolar.NewID(currentPN, h.Sum(buf))
psc := &payload.SetCode{
Record: buf,
}
pl, err := m.sendToLight(
ctx, bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 1),
psc, *insolar.NewRecordReference(recID),
)
if err != nil {
return nil, errors.Wrap(err, "failed to send SetCode")
}
switch p := pl.(type) {
case *payload.ID:
return &p.ID, nil
case *payload.Error:
err = errors.New(p.Text)
return nil, err
default:
err = fmt.Errorf("DeployCode: unexpected reply: %#v", p)
return nil, err
}
}
// ActivatePrototype creates activate object record in storage. Provided prototype reference will be used as objects prototype
// memory as memory of created object. If memory is not provided, the prototype default memory will be used.
//
// Request reference will be this object's identifier and referred as "object head".
func (m *client) ActivatePrototype(
ctx context.Context,
object, parent, code insolar.Reference,
memory []byte,
) error {
var err error
ctx, span := instracer.StartSpan(ctx, "artifactmanager.ActivatePrototype")
instrumenter := instrument(ctx, "ActivatePrototype").err(&err)
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
err = m.activateObject(ctx, object, code, true, parent, memory)
return err
}
// pulse returns current PulseNumber for artifact manager
func (m *client) pulse(ctx context.Context) (insolar.PulseNumber, error) {
pulseObject, err := m.PulseAccessor.Latest(ctx)
if err != nil {
return pulse.Unknown, err
}
return pulseObject.PulseNumber, nil
}
func (m *client) activateObject(
ctx context.Context,
obj insolar.Reference,
prototype insolar.Reference,
isPrototype bool,
parent insolar.Reference,
memory []byte,
) error {
_, err := m.GetObject(ctx, parent, nil)
if err != nil {
return errors.Wrap(err, "wrong parent")
}
activate := record.Activate{
Request: obj,
Memory: memory,
Image: prototype,
IsPrototype: isPrototype,
Parent: parent,
}
result := record.Result{
Object: *obj.GetLocal(),
Request: obj,
}
virtActivate := record.Wrap(&activate)
virtResult := record.Wrap(&result)
activateBuf, err := virtActivate.Marshal()
if err != nil {
return errors.Wrap(err, "ActivateObject: can't serialize record")
}
resultBuf, err := virtResult.Marshal()
if err != nil {
return errors.Wrap(err, "ActivateObject: can't serialize record")
}
pa := &payload.Activate{
Record: activateBuf,
Result: resultBuf,
}
pl, err := m.sendToLight(ctx, bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 1), pa, obj)
if err != nil {
return errors.Wrap(err, "can't send activation and result records")
}
switch p := pl.(type) {
case *payload.ResultInfo:
return nil
case *payload.Error:
return errors.New(p.Text)
default:
return fmt.Errorf("ActivateObject: unexpected reply: %#v", p)
}
}
func (m *client) InjectCodeDescriptor(reference insolar.Reference, descriptor CodeDescriptor) {
m.localStorage.StoreObject(reference, descriptor)
}
func (m *client) InjectPrototypeDescriptor(reference insolar.Reference, descriptor PrototypeDescriptor) {
m.localStorage.StoreObject(reference, descriptor)
}
func (m *client) InjectFinish() {
m.localStorage.Initialized()
}
// RegisterResult saves VM method call result with it's side effects
func (m *client) RegisterResult(
ctx context.Context,
request insolar.Reference,
result RequestResult,
) error {
sendResult := func(
payloadInput payload.Payload,
obj insolar.Reference,
) (*insolar.ID, error) {
payloadOutput, err := m.sendToLight(
ctx, bus.NewRetrySender(m.sender, m.PulseAccessor, 1, 1), payloadInput, obj,
)
if err != nil {
return nil, err
}
switch p := payloadOutput.(type) {
case *payload.ResultInfo:
return &p.ResultID, nil
case *payload.ErrorResultExists:
return nil, errors.New("another result already exists")
case *payload.Error:
return nil, errors.New(p.Text)
default:
return nil, fmt.Errorf("RegisterResult: unexpected reply: %#v", p)
}
}
var (
pl payload.Payload
err error
)
ctx, span := instracer.StartSpan(ctx, "artifactmanager.RegisterResult")
instrumenter := instrument(ctx, "RegisterResult").err(&err)
defer func() {
if err != nil {
instracer.AddError(span, err)
}
span.End()
instrumenter.end()
}()
span.AddAttributes(trace.StringAttribute("SideEffect", result.Type().String()))
objReference := result.ObjectReference()
resultRecord := record.Result{
Object: *objReference.GetLocal(),
Request: request,
Payload: result.Result(),
}
switch result.Type() {
// ActivateObject creates activate object record in storage. Provided prototype reference will be used as objects prototype
// memory as memory of created object. If memory is not provided, the prototype default memory will be used.
//
// Request reference will be this object's identifier and referred as "object head".
case RequestSideEffectActivate:
parentRef, imageRef, memory := result.Activate()
vResultRecord := record.Wrap(&resultRecord)
vActivateRecord := record.Wrap(&record.Activate{
Request: request,
Memory: memory,
Image: imageRef,
IsPrototype: false,
Parent: parentRef,
})
plTyped := payload.Activate{}
plTyped.Record, err = vActivateRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Activate record")
}
plTyped.Result, err = vResultRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Result record")
}
pl = &plTyped
// UpdateObject creates amend object record in storage. Provided reference should be a reference to the head of the
// object. Provided memory well be the new object memory.
//
// Returned reference will be the latest object state (exact) reference.
case RequestSideEffectAmend:
objectStateID, objectImage, memory := result.Amend()
vResultRecord := record.Wrap(&resultRecord)
vAmendRecord := record.Wrap(&record.Amend{
Request: request,
Memory: memory,
Image: objectImage,
IsPrototype: false,
PrevState: objectStateID,
})
plTyped := payload.Update{}
plTyped.Record, err = vAmendRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Amend record")
}
plTyped.Result, err = vResultRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Result record")
}
pl = &plTyped
// DeactivateObject creates deactivate object record in storage. Provided reference should be a reference to the head
// of the object. If object is already deactivated, an error should be returned.
//
// Deactivated object cannot be changed.
case RequestSideEffectDeactivate:
objectStateID := result.Deactivate()
vResultRecord := record.Wrap(&resultRecord)
vDeactivateRecord := record.Wrap(&record.Deactivate{
Request: request,
PrevState: objectStateID,
})
plTyped := payload.Deactivate{}
plTyped.Record, err = vDeactivateRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Deactivate record")
}
plTyped.Result, err = vResultRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Result record")
}
pl = &plTyped
case RequestSideEffectNone:
vResultRecord := record.Wrap(&resultRecord)
plTyped := payload.SetResult{}
plTyped.Result, err = vResultRecord.Marshal()
if err != nil {
return errors.Wrap(err, "RegisterResult: can't serialize Result record")
}
pl = &plTyped
default:
err = errors.Errorf("RegisterResult: Unknown side effect %d", result.Type())
return err
}
_, err = sendResult(pl, result.ObjectReference())
if err != nil {
return errors.Wrapf(err, "RegisterResult: Failed to send results: %s", result.Type().String())
}
return nil
}
func (m *client) sendToLight(
ctx context.Context,
sender bus.Sender,
ppl payload.Payload,
ref insolar.Reference,
) (payload.Payload, error) {
msg, err := payload.NewMessage(ppl)
if err != nil {
return nil, err
}
reps, done := sender.SendRole(ctx, msg, insolar.DynamicRoleLightExecutor, ref)
defer done()
rep, ok := <-reps
if !ok {
return nil, ErrNoReply
}
pl, err := payload.UnmarshalFromMeta(rep.Payload)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal reply")
}
return pl, nil
}