-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSyncherManager.js
executable file
·1091 lines (798 loc) · 36.2 KB
/
SyncherManager.js
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/
// Log System
import * as logger from 'loglevel';
let log = logger.getLogger('SyncherManager');
import { divideURL, deepClone } from '../utils/utils';
//import { schemaValidation } from '../utils/schemaValidation';
import AddressAllocation from '../allocation/AddressAllocation';
import ReporterObject from './ReporterObject';
import ObserverObject from './ObserverObject';
import * as cryptoManager from '../cryptoManager/CryptoManager';
/**
* @author [email protected]
* Core Syncronization system.
*/
class SyncherManager {
/* private
_url: URL
_bus: MiniBus
_registry: Registry
_allocator: AddressAllocation
_reporters: { ObjectURL: ReporterObject }
_observers: { ObjectURL: ObserverObject }
*/
constructor(runtimeURL, bus, registry, storageManager, allocator, storeDataObjects, identityModule) {
if (!runtimeURL) throw new Error('[Syncher Manager] - needs the runtimeURL parameter');
if (!bus) throw new Error('[Syncher Manager] - needs the MessageBus instance');
if (!registry) throw new Error('[Syncher Manager] - needs the Registry instance');
if (!storageManager) throw new Error('[Syncher Manager] - need the storageManager instance');
let _this = this;
_this._bus = bus;
_this._registry = registry;
_this._storageManager = storageManager;
_this._identityModule = identityModule;
//TODO: these should be saved in persistence engine?
_this.runtimeURL = runtimeURL;
_this._url = runtimeURL + '/sm';
_this._objectURL = runtimeURL + '/object-allocation';
_this._reporters = {};
_this._observers = {};
_this._dataObjectsStorage = storeDataObjects;
console.log('[NOTSAVING] storeDataObjects', storeDataObjects);
//TODO: this should not be hardcoded!
_this._domain = divideURL(runtimeURL).domain;
if (allocator) {
_this._allocator = allocator;
} else {
_this._allocator = AddressAllocation.instance;
}
log.log('[SyncherManager - AddressAllocation] - ', _this._allocator);
bus.addListener(_this._url, (msg) => {
log.info('[SyncherManager] RCV: ', msg);
switch (msg.type) {
case 'create': _this._onCreate(msg); break;
case 'delete': _this._onDelete(msg); break;
case 'subscribe': _this._onLocalSubscribe(msg); break;
case 'unsubscribe': _this._onLocalUnSubscribe(msg); break;
case 'read': _this._onRead(msg); break;
case 'execute': _this._onExecute(msg); break;
}
});
}
get url() { return this._url; }
//FLOW-IN: message received from Syncher -> read
_onExecute(msg) {
let _this = this;
let reply = {
type: 'response',
from: msg.to,
to: msg.from,
id: msg.id
}
log.info('[SyncherManager.onExecute] new message', msg);
if (msg.hasOwnProperty('body') && msg.body.hasOwnProperty('method') && msg.body.hasOwnProperty('params')) {
switch (msg.body.method) {
case 'sync': _this._dataObjectsStorage.sync(msg.body.params[0], msg.body.params[1], false);
break;
case 'stopSync': _this._dataObjectsStorage.stopSync(msg.body.params[0]);
break;
}
reply.body = {
code: 200
};
_this._bus.postMessage(reply);
} else {
reply.body = {
code: 400,
desc: 'missing body or body method / params mandatory fields'
};
log.error('[SyncherManager.onExecute] error. Missing body or body method / params mandatory fields', msg);
_this._bus.postMessage(reply);
}
}
//FLOW-IN: message received from Syncher -> read
_onRead(msg) {
let _this = this;
let reply = {
type: 'response',
from: msg.to,
to: msg.from,
id: msg.id
}
log.info('[SyncherManager.onRead] new message', msg);
if (msg.hasOwnProperty('body') && msg.body.hasOwnProperty('resource')) {
_this._dataObjectsStorage.sync(msg.body.resource, true).then((dataObject)=>{
reply.body = {
code: 200,
value: dataObject
};
log.info('[SyncherManager.onRead] found object: ', dataObject);
_this._bus.postMessage(reply);
}, (error)=>{
reply.body = {
code: 404,
desc: error
};
log.warn('[SyncherManager.onRead] warning: ', error);
_this._bus.postMessage(reply);
});
} else {
reply.body = {
code: 400,
desc: 'missing body or body resource mandatory fields'
};
log.error('[SyncherManager.onRead] error. Missing body or body resource mandatory fields', msg);
_this._bus.postMessage(reply);
}
}
//FLOW-IN: message received from Syncher -> create
_onCreate(msg) {
let from = msg.from;
let to = msg.to;
let _this = this;
// check if message is to save new childrenObjects in the local storage
// TODO: check if message is to store new child in the local storage and call storeChild. How to distinguish from others?
//debugger;
if (msg.body.attribute) { this._storeChildrens(msg); } else {
if (!msg.body.hasOwnProperty('resume') || (msg.body.hasOwnProperty('resume') && !msg.body.resume)) {
// check if this is an invitation message
if (msg.body.authorise) {
this._authorise(msg);
log.info('[SyncherManager.onCreate - invite observers]', msg);
} else { // this is to create a new data object
log.info('[SyncherManager.onCreate - Create New Object]', msg);
this._newCreate(msg);
}
} else {
// If from the hyperty side, call the resumeReporter we will have resume = true'
// so we will create an resumed object and will try to resume the object previously saved;
this._dataObjectsStorage.getResourcesByCriteria(msg, true).then((result) => {
log.info('[SyncherManager - Create Resumed] - ResourcesByCriteria | Message: ', msg, ' result: ', result);
if (result && Object.keys(result).length > 0) {
let listOfReporters = [];
Object.keys(result).forEach((objURL) => {
listOfReporters.push(
_this._resumeCreate(msg, result[objURL])
);
});
Promise.all(listOfReporters).then((resumedReporters) => {
log.log('[SyncherManager - Create Resumed]', resumedReporters);
// TODO: shoud send the information if some object was failing;
let successfullyResumed = Object.values(resumedReporters).filter((reporter) => {
return reporter !== false;
});
log.info('[SyncherManager.onCreate] returning resumed objects : ', successfullyResumed);
//FLOW-OUT: message response to Syncher -> create resume
this._bus.postMessage({
id: msg.id, type: 'response', from: to, to: from,
body: { code: 200, value: deepClone(successfullyResumed) }
});
/*successfullyResumed.forEach((reporter) => {
if (reporter.backup) {
this._dataObjectsStorage.sync(reporter.url);
}
});*/
});
} else {
//forward to hyperty:
let reply = {};
reply.id = msg.id;
reply.from = msg.to;
reply.to = msg.from;
reply.type = 'response';
reply.body = {
code: 404,
desc: 'No data objects reporters to be resumed'
};
this._bus.postMessage(reply);
}
});
}
}
}
_storeChildrens(msg) {
let _this = this;
let resource = msg.body.resource;
let attribute = msg.body.attribute;
if (attribute === 'childrenObjects') {
_this._dataObjectsStorage.saveChildrens(false, resource, undefined, msg.body.value);
} else { _this._dataObjectsStorage.saveChildrens(true, resource, attribute, msg.body.value);
}
}
_newCreate(msg) {
let _this = this;
let owner = msg.from;
let domain = divideURL(msg.from).domain;
// if reporter is in a Interworking Protostub the runtime domain backend services will be used
if (_this._registry.isInterworkingProtoStub(msg.from)) {
domain = divideURL(_this.runtimeURL).domain;
}
// let domainRegistration = msg.body.value.hasOwnProperty('domain_registration') ? msg.body.value.domain_registration : true;
let domainRouting = msg.body.value.hasOwnProperty('domain_routing') ? msg.body.value.domain_routing : true;
// Process invitation message to observers
/*if (msg.body.authorise) {
_this._authorise(msg);
return;
}*/
//get schema from catalogue and parse -> (scheme, children)
_this._registry.getDataSchemaDescriptor(msg.body.schema).then((descriptor) => {
let properties = descriptor.sourcePackage.sourceCode.properties;
let scheme = properties.scheme ? properties.scheme : 'resource';
let childrens = properties.childrens ? properties.childrens : [];
// Do schema validation
// TODO: check if is need to handle with the result of validation
// schemaValidation(scheme, descriptor, msg.body.value);
let objectInfo = {
name: msg.body.value.name,
schema: msg.body.value.schema,
reporter: msg.body.value.reporter,
resources: msg.body.value.resources
};
// should resuse data object url if it passed
let reuseDataObject = msg.body.value.resource;
let numOfAddress = 1;
//debugger;
//request address allocation of a new object from the msg-node
//_this._allocator.create(domain, numOfAddress, objectInfo, scheme, reuseDataObject).then((allocated) => {
_this._allocator.create(domain, numOfAddress, objectInfo, scheme, reuseDataObject).then((allocated) => {
let objectRegistration = deepClone(msg.body.value);
objectRegistration.url = allocated.address[0];
objectRegistration.authorise = msg.body.authorise;
objectRegistration.childrens = childrens;
//objectRegistration.expires = 30;//TODO: get it from data object configuration description when present
delete objectRegistration.data;
log.log('[SyncherManager._newCreate] ALLOCATOR CREATE:', allocated);
let subscriptionURL = objectRegistration.url + '/subscription';
log.log('[SyncherManager._newCreate] Subscription URL', subscriptionURL);
//To register the dataObject in the runtimeRegistry
log.info('[SyncherManager._newCreate] Register Object: ', objectRegistration);
//_this._registry.registerDataObject(msg.body.value.name, msg.body.value.schema, objURL, msg.body.value.reporter, msg.body.value.resources, allocated, msg.body.authorise).then((resolve) => {
_this._registry.registerDataObject(objectRegistration).then((registeredObject) => {
log.log('[SyncherManager._newCreate] DataObject successfully registered', registeredObject);
//all OK -> create reporter and register listeners
let reporter;
if (!this._reporters[objectRegistration.url]) {
let offline = objectRegistration.offline ? objectRegistration.offline : false;
reporter = new ReporterObject(_this, owner, objectRegistration.url, childrens, offline);
} else {
reporter = this._reporters[objectRegistration.url];
}
log.log('[SyncherManager - new Create] - ', msg);
// Store for each reporter hyperty the dataObject
let userURL;
// let interworking = false;
if (msg.body.hasOwnProperty('identity') && msg.body.identity.userProfile && msg.body.identity.userProfile.userURL) {
userURL = msg.body.identity.userProfile.userURL;
// if (!userURL.includes('user://')) {
// interworking = true;
// }
} else {
userURL = _this._registry.getHypertyOwner(msg.from);
// if (!userURL) {
// interworking = true;
// }
}
// should we use the msg.body.value instead?
let metadata = deepClone(objectRegistration);
metadata.subscriberUser = userURL;
metadata.isReporter = true;
// Store the dataObject information
//if (!interworking) {
if (msg.body.hasOwnProperty('store') && msg.body.store) {
reporter.isToSaveData = true;
metadata.isToSaveData = true;
if (msg.body.value.data) {
metadata.data = deepClone(msg.body.value.data);
// _this._dataObjectsStorage.saveData(true, objectRegistration.url, null, msg.body.value.data); }
// _this._dataObjectsStorage.update(true, objectRegistration.url, 'isToSaveData', true);
// if (msg.body.value.data) { _this._dataObjectsStorage.saveData(true, objectRegistration.url, null, msg.body.value.data); }
}
}
_this._dataObjectsStorage.set(metadata).then((storeObject) => {
if (metadata.offline) { //register new DataObject at Offline Subscription Manager
msg.body.identity.guid = _this._identityModule._identities.guid;
let forward = {
from: msg.to,
to: metadata.offline + '/register',
type: 'forward',
body: msg
};
forward.body.body.resource = objectRegistration.url;
forward.body.body.value = metadata;
log.log('[SyncherManager.newCreate] registering new object at offline manager ', forward);
_this._bus.postMessage(forward);
}
//}
let responseMsg = {
id: msg.id, type: 'response', from: msg.to, to: owner,
body: { code: 200, resource: objectRegistration.url, childrenResources: childrens }
};
// adding listeners to forward to reporter
if (domainRouting) {
reporter.forwardSubscribe([objectRegistration.url, subscriptionURL]).then(() => {
reporter.addChildrens().then(() => {
_this._reporters[objectRegistration.url] = reporter;
//FLOW-OUT: message response to Syncher -> create
_this._bus.postMessage(responseMsg);
});
});
} else {
reporter.addChildrens().then(() => {
_this._reporters[objectRegistration.url] = reporter;
//FLOW-OUT: message response to Syncher -> create
_this._bus.postMessage(responseMsg);
});
}
}, (error)=> {
log.error(error);
});
}, function (error) {
log.error(error);
});
});
}).catch((reason) => {
//FLOW-OUT: error message response to Syncher -> create
let responseMsg = {
id: msg.id, type: 'response', from: msg.to, to: owner,
body: { code: 500, desc: reason }
};
_this._bus.postMessage(responseMsg);
});
}
_resumeCreate(msg, storedObject) {
let _this = this;
return new Promise((resolve) => {
let owner = msg.from;
let schema = storedObject.schema;
let resource = storedObject.url;
let domainRegistration = storedObject.hasOwnProperty('domain_registration') ? storedObject.domain_registration : true;
let initialData = storedObject.data;
log.log('[SyncherManager] - resume create', msg, storedObject);
//get schema from catalogue and parse -> (scheme, children)
_this._registry.getDataSchemaDescriptor(schema).then((descriptor) => {
let properties = descriptor.sourcePackage.sourceCode.properties;
let scheme = properties.scheme ? properties.scheme.constant : 'resource';
let childrens = properties.childrens ? properties.childrens : [];
log.log('[SyncherManager] - getDataSchemaDescriptor: ', descriptor, childrens);
// Do schema validation
// TODO: check if is need to handle with the result of validation
// schemaValidation(scheme, descriptor, initialData);
//all OK -> create reporter and register listeners
let reporter;
let offline;
if (!this._reporters[resource]) {
offline = storedObject.offline ? storedObject.offline : false;
reporter = new ReporterObject(_this, owner, resource, childrens, offline);
} else {
reporter = this._reporters[resource];
}
reporter.isToSaveData = storedObject.isToSaveData;
if (offline) { //update new DataObject at Offline Subscription Manager
let msg = {
from: _this._url,
to: offline + '/register',
type: 'update',
body: {}
};
log.log('[SyncherManager._resumeCreate] update object at offline manager ', msg);
_this._bus.postMessage(msg);
}
if (domainRegistration) {
reporter.forwardSubscribe([storedObject.url]).then(() => {
log.log('[SyncherManager._resumeCreate] resumingReporterSubscription ', storedObject);
_this._resumeReporterSubscriptions(msg, storedObject, reporter, childrens, domainRegistration).then((resumeObject)=>{
log.log('[SyncherManager._resumeCreate] resolved resumed object ', resumeObject);
resolve(resumeObject);
});
});
} else resolve(_this._resumeReporterSubscriptions(msg, storedObject, reporter, childrens, domainRegistration));
// resolve();
}).catch((reason) => {
log.error('[SyncherManager - resume create] - fail on getDataSchemaDescriptor: ', reason);
resolve(false);
});
});
}
_resumeReporterSubscriptions(msg, storedObject, reporter, childrens, domainRegistration){
let _this = this;
let resource = storedObject.url;
let objectRegistration = deepClone(msg.body.value);
objectRegistration.url = storedObject.url;
objectRegistration.expires = storedObject.expires;
objectRegistration.domain_registration = domainRegistration;
delete objectRegistration.data;
return new Promise((resolve) => {
reporter.addChildrens().then(() => {
reporter.resumeSubscriptions(storedObject.subscriptions);
_this._reporters[resource] = reporter;
log.info('[SyncherManager - resume create] - resolved resumed: ', storedObject);
return _this._decryptChildrens(storedObject, childrens);
}).then((decryptedObject) => {
log.info('[SyncherManager._resumeReporterSubscriptions] Register Object: ', objectRegistration);
_this._registry.registerDataObject(objectRegistration).then((registered) => {
log.log('[SyncherManager._resumeReporterSubscriptions] DataObject registration successfully updated', registered);
log.log('[SyncherManager._resumeReporterSubscriptions] resolving object', decryptedObject);
resolve(decryptedObject);
});
// log.log('result of previous promise');
}).catch((reason) => {
log.error('[SyncherManager - resume create] - fail on addChildrens: ', reason);
resolve(false);
});
});
}
// to decrypt DataChildObjects if they are encrypted
_decryptChildrens(encryptedObject, childrens) {
let _this = this;
let storedObject = deepClone(encryptedObject);
return new Promise((resolve) => {
if (!childrens) { resolve(storedObject); } else {
let childrensObj = Object.keys(storedObject.childrenObjects);
if (childrensObj.length === 0) {
resolve(storedObject);
}
childrens.forEach((children) => {
// let childObjects = storedObject.childrenObjects[children];
let childObjects = storedObject.childrenObjects;
log.log('[SyncherManager._decryptChildrens] dataObjectChilds to decrypt ', childObjects);
let listOfDecryptedObjects = [];
Object.keys(childObjects).forEach((childId) => {
let child = childObjects[childId];
let owner = childId.split('#')[0];
if (typeof child.value === 'string') {
log.log('[SyncherManager._decryptChildrens] createdBy ', owner, ' object: ', child.value);
let decrypted = cryptoManager.default.decryptDataObject(JSON.parse(child.value), storedObject.url);
listOfDecryptedObjects.push(decrypted);
}
});
Promise.all(listOfDecryptedObjects).then((decryptedObjects) => {
log.log('[SyncherManager._decryptChildrens] returning decrypted ', decryptedObjects);
decryptedObjects.forEach((decryptedObject) => {
const childId = decryptedObject.value.url;
storedObject.childrenObjects[childId].value = decryptedObject.value;
});
log.log('[SyncherManager._decryptChildrens] storedObject ', storedObject);
resolve(storedObject);
}).catch((reason) => {
log.warn('[SyncherManager._decryptChildrens] failed : ', reason);
});
});
}
});
}
// Process invitations to observers
_authorise(msg) {
let _this = this;
if (!msg.body.resource) {
throw new Error('[SyncherManager._authorise] invitation request without data object url:', msg);
}
let objSubscriptorURL = msg.body.resource + '/subscription';
let p2p = msg.body.p2p ? msg.body.p2p : false;
log.log('[SyncherManager - authorise] - ', msg);
if (msg.body.authorise) {
msg.body.authorise.forEach((hypertyURL) => {
//FLOW-OUT: send invites to list of remote Syncher -> _onRemoteCreate -> onNotification
_this._bus.postMessage({
type: 'create', from: objSubscriptorURL, to: hypertyURL,
body: { p2p: p2p, identity: msg.body.identity, source: msg.from, value: msg.body.value, schema: msg.body.schema }
}, (reply) => { // lets forward the invitation response
let response = {
from: msg.to,
to: msg.from,
id: msg.id,
type: reply.type,
body: reply.body
};
_this._bus.postMessage(response);
});
});
}
}
//FLOW-IN: message received from DataObjectReporter -> delete
_onDelete(msg) {
let _this = this;
let objURL = msg.body.resource;
let object = _this._reporters[objURL];
if (object) {
//TODO: is there any policy verification before delete?
if (object.offline) { //register new DataObject at Offline Subscription Manager
let forward = {
from: msg.to,
to: object.offline + '/register',
type: 'forward',
body: msg
};
log.log('[SyncherManager._onDelete] unregistering object from offline manager ', forward);
_this._bus.postMessage(forward);
}
object.delete();
this._dataObjectsStorage.deleteResource(objURL).then((result) => {
log.log('[SyncherManager - onDelete] - deleteResource: ', result);
_this._registry.unregisterDataObject(objURL);
//TODO: unregister object?
_this._bus.postMessage({
id: msg.id, type: 'response', from: msg.to, to: msg.from,
body: { code: 200 }
});
});
}
}
//FLOW-IN: message received from local Syncher -> subscribe
_onLocalSubscribe(msg) {
//debugger;
if (msg.body.hasOwnProperty('resume') && (msg.body.resume )) {
this._dataObjectsStorage.getResourcesByCriteria(msg, false).then((result) => {
log.info('[SyncherManager.onLocalSubscribe. resume]: ', msg, ' result: ', result);
if (result && Object.keys(result).length > 0) {
let listOfObservers = [];
// TODO: should reuse the stored information
Object.keys(result).forEach((objURL) => {
log.log('[SyncherManager - resume Subscribe] - reuse current object url: ', result[objURL]);
listOfObservers.push(this._resumeSubscription(msg, result[objURL]));
});
Promise.all(listOfObservers).then((resumedObservers) => {
log.log('[SyncherManager - Observers Resumed]', resumedObservers);
// TODO: shoud send the information if some object is failing;
let successfullyResumed = Object.values(resumedObservers).filter((observer) => {
return observer !== false;
});
let response = {
id: msg.id, type: 'response', from: msg.to, to: msg.from,
body: { code: 200, value: successfullyResumed }
};
log.log('[SyncherManager - Observers Resumed] replying ', response);
//FLOW-OUT: message response to Syncher -> create
this._bus.postMessage(response);
});
} else {
//forward to hyperty:
let reply = {};
reply.id = msg.id;
reply.from = msg.to;
reply.to = msg.from;
reply.type = 'response';
reply.body = {
code: 404,
desc: 'No data objects observers to be resumed'
};
this._bus.postMessage(reply);
}
});
} else {
log.log('[SyncherManager.onLocalSubscribe - new Subscribe] - ', msg.body.schema, msg.body.resource);
this._newSubscription(msg);
}
}
_newSubscription(msg) {
let _this = this;
let objURL = msg.body.resource;
let hypertyURL = msg.from;
let domain = divideURL(objURL).domain;
let domainSubscription = msg.body.hasOwnProperty('domain_subscription') ? msg.body.domain_subscription : true;
let childBaseURL = objURL + '/children/';
//get schema from catalogue and parse -> (children)
_this._registry.getDataSchemaDescriptor(msg.body.schema).then((descriptor) => {
let properties = descriptor.sourcePackage.sourceCode.properties;
let childrens = properties.childrens ? properties.childrens : [];
let subscriptions = [];
subscriptions.push(objURL + '/changes');
// childrens.forEach((child) => subscriptions.push(childBaseURL + child));
subscriptions.push(childBaseURL);
//children addresses
if (domainSubscription) { //FLOW-OUT: subscribe message to the msg-node, registering listeners on the broker
let nodeSubscribeMsg = {
type: 'subscribe', from: _this._url, to: 'domain://msg-node.' + domain + '/sm',
body: { identity: msg.body.identity, resources: subscriptions, source: hypertyURL }
};
//subscribe in msg-node
_this._bus.postMessage(nodeSubscribeMsg, (reply) => {
log.log('node-subscribe-response(observer): ', reply);
console.log('REUSETEST SyncherManager - node-subscribe-response(observer): ', reply);
if (reply.body.code === 200) {
_this._newReporterSubscribe(msg, hypertyURL, objURL, childrens);
} else {
//listener rejected
_this._bus.postMessage({
id: msg.id, type: 'response', from: msg.to, to: hypertyURL,
body: reply.body
});
}
});
} else _this._newReporterSubscribe(msg, hypertyURL, objURL, childrens);
});
}
_newReporterSubscribe(msg, hypertyURL, objURL, childrens){
let _this = this;
let objURLSubscription = objURL + '/subscription';
//FLOW-OUT: reply with provisional response
_this._bus.postMessage({
id: msg.id, type: 'response', from: msg.to, to: hypertyURL,
body: { code: 100, childrenResources: childrens, schema: msg.body.schema, resource: msg.body.resource }
});
//FLOW-OUT: subscribe message to remote ReporterObject -> _onRemoteSubscribe
let objSubscribeMsg = {
type: 'subscribe', from: _this._url, to: objURLSubscription,
body: { identity: msg.body.identity, subscriber: hypertyURL }
};
//TODO: For Further Study
if (msg.body.hasOwnProperty('mutual')) objSubscribeMsg.body.mutual = msg.body.mutual;
log.log('[SyncherManager._newSubscription]', objSubscribeMsg, msg);
console.log('REUSETEST SyncherManager - [SyncherManager._newSubscription]', objSubscribeMsg, msg);
//subscribe to reporter SM
_this._bus.postMessage(objSubscribeMsg, (reply) => {
log.log('reporter-subscribe-response-new: ', reply);
console.log('REUSETEST SyncherManager - reporter-subscribe-response-new: ', reply);
if (reply.body.code === 200) _this._processSuccessfullSubscription(reply, hypertyURL, objURL, childrens, msg);
else if (msg.body.offline) _this._processOfflineSubscription(objSubscribeMsg, msg.body.offline, hypertyURL, objURL, childrens, msg);
else {
//TODO: send response back to Hyperty with error message received in the reply
}
});
}
_processOfflineSubscription(subscription, redirectTo, hypertyURL, objURL, childrens, msg) {
let _this = this;
let forward = {
from: subscription.from,
type: 'forward',
to: redirectTo,
body: subscription
};
console.log('[SyncherManager._processOfflineSubscription] forwading ', forward);
_this._bus.postMessage(forward, (reply) => {
log.log('[SyncherManager._processOfflineSubscription] reply ', reply);
if (reply.body.code === 200) _this._processSuccessfullSubscription(reply, hypertyURL, objURL, childrens, msg);
else {
//TODO: send response back to Hyperty with error message received in the reply
}
});
}
_processSuccessfullSubscription(reply, hypertyURL, objURL, childrens, msg) {
let _this = this;
log.log('[SyncherManager._newSubscription] - observers: ', _this._observers, objURL, _this._observers[objURL]);
console.log('REUSETEST SyncherManager - 200 code[SyncherManager._newSubscription] - observers: ', _this._observers, objURL, _this._observers[objURL]);
let observer = _this._observers[objURL];
if (!observer) {
observer = new ObserverObject(_this, objURL, childrens);
log.log('[SyncherManager._newSubscription] - observers: create new ObserverObject: ', observer);
_this._observers[objURL] = observer;
// register new hyperty subscription
observer.addSubscription(hypertyURL);
// add childrens and listeners to save data if necessary
observer.addChildrens();
}
let interworking = false;
//debugger;
// Store for each reporter hyperty the dataObject
let userURL;
if (msg.body.hasOwnProperty('identity') && msg.body.identity.userProfile && msg.body.identity.userProfile.userURL) {
userURL = msg.body.identity.userProfile.userURL;
if (!userURL.includes('user://')) {
interworking = true;
}
} else {
userURL = _this._registry.getHypertyOwner(msg.from);
if (!userURL) interworking = true;
}
let metadata = deepClone(reply.body.value);
// let childrenObjects = metadata.childrenObjects || {};
delete metadata.data;
delete metadata.childrenObjects;
metadata.childrens = childrens;
metadata.subscriberUser = userURL;
metadata.isReporter = false;
metadata.subscriberHyperty = hypertyURL;
if (!interworking) {
//_this._dataObjectsStorage.set(objURL, false, msg.body.schema, 'on', reply.body.owner, hypertyURL, childrens, userURL);
_this._dataObjectsStorage.set(metadata);
if ((metadata.hasOwnProperty('store') && metadata.store) || (metadata.hasOwnProperty('isToSaveData') && metadata.isToSaveData)) {
observer.isToSaveData = true;
_this._dataObjectsStorage.update(false, objURL, 'isToSaveData', true);
_this._dataObjectsStorage.saveData(false, objURL, null, reply.body.value.data);
// if (childrens) _this._dataObjectsStorage.initialObserverSync(objURL, reply.body.value.data.backupRevision);
}
}
//forward to hyperty:
reply.id = msg.id;
reply.from = _this._url;
reply.to = hypertyURL;
reply.body.schema = msg.body.schema;
reply.body.resource = msg.body.resource;
//TODO: For Further Study
if (msg.body.hasOwnProperty('mutual')) reply.body.mutual = msg.body.mutual;
log.log('[subscribe] - new subscription: ', msg, reply, observer);
this._bus.postMessage(reply);
}
_resumeSubscription(msg, storedObject) {
return new Promise((resolve) => {
let objURL = storedObject.url;
let schema = storedObject.schema;