forked from victor73/OSDF
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnode-handler.js
1780 lines (1550 loc) · 61.5 KB
/
node-handler.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
// async/each - For handling async code in series
// async/waterfall - For handling complicated async workflows
// async/series - For handling async code in series
// cradle - For interactions with CouchDB
// lodash - For generic utility functions
// string-format - For better string formatting abilities
// ajv - Used for JSON validation with JSON-Schema
var _ = require('lodash');
var auth = require('auth_enforcer');
var config = require('config');
var cradle = require('cradle');
var http = require('http');
var each = require('async/each');
var format = require('string-format');
var fs = require('fs');
var linkage_controller = require('linkage-controller');
var osdf_utils = require('osdf_utils');
var path = require('path');
var perms = require('perms-handler');
var provenance = require('provenance');
var schema_utils = require('schema_utils');
var series = require('async/series');
var sprintf = require('sprintf').sprintf;
var ajv = require('ajv');
var util = require('util');
var waterfall = require('async/waterfall');
format.extend(String.prototype);
config.load(osdf_utils.get_config());
// Load some important configuration parameters.
var base_url = config.value('global', 'base_url');
var port = config.value('global', 'port');
var couch_address = config.value('global', 'couch_address');
var couch_port = config.value('global', 'couch_port');
var couch_user = config.value('global', 'couch_user');
var couch_pass = config.value('global', 'couch_pass');
var dbname = config.value('global', 'couch_dbname');
var logger = osdf_utils.get_logger();
var osdf_error = osdf_utils.send_error;
// An array to hold the namespaces.
var namespaces = [];
var validators = {};
var base_validator;
var base_validate;
var working_dir;
var couch_conn;
var db;
// This initializes the handler. The things we need to do before the
// handler is ready to begin its work are: establish a connection to the
// CouchDB server, determine what the installed namespaces are, and create
// the various validators for each of the node types inside each namespace.
exports.init = function(emitter, working_dir_custom) {
var module_base = path.basename(__filename);
logger.debug('In {} init().'.format(module_base));
working_dir = osdf_utils.get_working_dir();
logger.info('Creating CouchDB connection. Using db: ' + dbname);
// Establish the connection parameters, including the application's
// CouchDB credentials.
couch_conn = new(cradle.Connection)('http://' + couch_address, couch_port, {
auth: { username: couch_user, password: couch_pass },
cache: false,
raw: false
});
// Create the CouchDB connection using the configured database name.
db = couch_conn.database(dbname);
db.exists(function(err, exists) {
// Here we emit the error to abort the server startup process.
if (err) {
var msg = sprintf(
'Error connecting to CouchDB database at %s:%s. ' +
'Check settings & credentials in %s.',
couch_address,
couch_port,
osdf_utils.get_config()
);
emitter.emit('node_handler_aborted', msg);
}
if (! exists) {
emitter.emit(
'node_handler_aborted',
"CouchDB database '{}' doesn't exist.".format(dbname)
);
}
});
waterfall([
function(callback) {
// Load the base schema for nodes. This is used in the validation process.
var base_schema_path = path.join(
osdf_utils.get_osdf_root(),
'lib',
'node.json'
);
logger.info('Loading base node json-schema, node.json.');
fs.readFile(base_schema_path, 'utf8', function(err, schema_text) {
if (err) {
var msg = 'Unable to read base schema from {}: {}'
.format(base_schema_path, err);
callback(msg, null);
} else {
var base_schema = JSON.parse(schema_text);
callback(null, base_schema);
}
});
},
function(base_schema, callback) {
logger.info('Creating base node validator.');
base_validator = new ajv({allErrors: true});
base_validate = base_validator.compile(base_schema);
callback(null);
},
function(callback) {
// The linkage controller needs its own ability to interact with
// CouchDB, to validate nodes, so we give it the connection we
// established.
linkage_controller.set_db_connection(db);
osdf_utils.get_namespace_names(function(err, names) {
if (err) {
logger.error('Error retrieving namespace names: ' + err);
callback(err, null);
} else {
logger.info('Namespaces: ', names);
callback(null, names);
}
});
},
function(names, callback) {
namespaces = names;
populate_validators(function(err) {
if (err) {
logger.error('Error populating validators: ' + err);
callback(err);
} else {
callback(null);
}
});
},
function(callback) {
establish_linkage_controls(function(err) {
if (err) {
logger.error('Error establishing linkage controls: ' + err);
callback(err);
} else {
logger.info('Successfully established linkage controls.');
callback(null);
}
});
}],
function(err) {
if (err) {
emitter.emit('node_handler_aborted', err);
} else {
emitter.emit('node_handler_initialized');
}
});
};
// This function handles the deletion of nodes. We must check that the
// node exists and that the user has write permissions to it.
exports.delete_node = function(request, response) {
logger.debug('In delete_node.');
// Check that we actually have the id in the request...
var node_id = null;
if (request.hasOwnProperty('params') && request.params.hasOwnProperty('id')) {
node_id = request.params.id;
} else {
var msg = 'No node ID provided.';
logger.error(msg);
throw msg;
}
try {
// Check if this node has other nodes pointing to it.
has_dependent_nodes(node_id, function(err, has_dependencies) {
if (err) {
logger.error(err);
throw err;
}
if (has_dependencies) {
osdf_error(response, 'Node has dependencies on it.', 409);
} else {
logger.debug('No dependencies, so clear to delete.');
// Get the user that is making the deletion request.
var user = auth.get_user(request);
delete_helper(user, node_id, response);
}
});
} catch (err) {
logger.error('Error deleting node. Reason: ' + err);
osdf_error(response, 'Unable to delete node.', 500);
}
};
// This is the method that handles node retrieval. It is called when users HTTP
// GET the node.
exports.get_node = function(request, response) {
logger.debug('In get_node.');
db.get(request.params.id, function(err, node_data) {
node_retrieval_helper(request, response, err, node_data);
});
};
// This is the method that handles node retrieval by version number. It is
// called when users HTTP GET the node and supply a specific version number in
// the url.
exports.get_node_by_version = function(request, response) {
logger.debug('In get_node_by_version.');
var node_id = request.params.id;
var requested_version = parseInt(request.params.ver, 10);
if (requested_version <= 0) {
logger.warn('User asked for invalid version number of node.');
osdf_error(response, 'Invalid version number.', 422);
} else if ( isNaN(requested_version) ) {
logger.warn("User didn't provide a valid number for the version number.");
osdf_error(response, 'Invalid version number.', 422);
} else {
var version = request.params.ver.toString();
var stream = db.getAttachment(node_id + '_hist', version);
var data = '';
stream.on('data', function(chunk) {
data += chunk;
});
stream.on('end', function() {
logger.debug('CouchDB request for attachment complete.');
var couch_response = null;
try {
couch_response = JSON.parse(data);
} catch (err) {
logger.error(err, data);
}
if (couch_response === null) {
osdf_error(response, 'Unable to retrieve node version.', 422);
} else {
logger.info('Got a valid CouchDB response.');
if (couch_response.hasOwnProperty('error')) {
logger.info('CouchDB response indicated an error occurred.');
get_couch_doc(node_id, function(err, current_node) {
if (err) {
logger.error(err);
osdf_error(response, 'Unable to retrieve node.', 500);
} else {
var current_node_version = parse_version(current_node['_rev']);
// The user may be using this method to get the current version.
// They 'should' use the regular node retrieval method, but here
// they are using the 'by version' method to get the current
// version.
if (requested_version === current_node_version) {
response.jsonp(osdf_utils.fix_keys(current_node));
} else {
osdf_error(response, 'Unable to retrieve node version.', 404);
}
}
});
} else {
response.jsonp(couch_response);
}
}
return;
});
}
};
// Retrieve the nodes that a particular node links to
exports.get_out_linkage = function(request, response) {
logger.debug('In get_out_linkage.');
// Check that we actually have the id in the request...
var node_id = null;
if (request.hasOwnProperty('params') && request.params.hasOwnProperty('id')) {
node_id = request.params.id;
} else {
var msg = 'No node ID provided.';
logger.error(msg);
throw msg;
}
var view_opts = {include_docs: true, startkey: [node_id], endkey:[node_id, {}]};
try {
// This needs to query a view, not issue N queries...
db.view('linkage/out', view_opts, function(err, results) {
if (err) {
logger.error(err);
throw err;
}
// The first entry is the node itself. Subsequent elements in the
// array are the nodes that we are linking to
results.shift();
// Remove duplicates. A node can actually link to other nodes
// multiple times, but the API says we only report it once.
var seen_list = [];
logger.debug('Filtering duplicates from the result list.');
var filtered = _.filter(results, function(result) {
if ( _.includes(seen_list, result['doc']['_id'])) {
return false;
} else {
seen_list.push( result['doc']['_id'] );
return true;
}
});
// Move the structure up a level.
filtered = _.map(filtered, function(filtered_result) {
return filtered_result['doc'];
});
// Fix the couch docs to look like an OSDF doc
filtered = _.map(filtered, function(filtered_result) {
return osdf_utils.fix_keys(filtered_result);
});
// Exclude nodes that we do not have read permission for
var user = auth.get_user(request);
filtered = _.filter(filtered, function(node) {
return perms.has_read_permission(user, node);
});
// Assemble the final document for transmission
var report = {
'result_count': filtered.length,
'page': 1,
'results': []
};
_.each(filtered, function(filtered_result) {
report['results'].push( filtered_result );
});
response.jsonp(report);
});
} catch (e) {
logger.error(e);
osdf_error(response, 'Unable to retrieve node linkages.', 500);
}
};
// Retrieve the nodes that point to this node.
exports.get_in_linkage = function(request, response) {
logger.debug('In get_in_linkage.');
// Check that we actually have the id in the request...
var node_id = request.params.id;
if (node_id === null || node_id === '') {
osdf_error(response, 'Invalid or missing node id.', 422);
return;
}
try {
// This needs to query a view, not issue N queries...
db.view('linkage/in', {include_docs: true, key: node_id}, function(err, results) {
if (err) {
logger.error(err);
throw err;
}
// Remove duplicates. A node can actually link to other nodes multiple times, but
// the API says we only report it once.
var seen_list = [];
logger.debug('Filtering duplicates from the result list.');
var filtered = _.filter(results, function(result) {
if ( _.includes(seen_list, result['doc']['_id'])) {
return false;
} else {
seen_list.push( result['doc']['_id'] );
return true;
}
});
// Move the structure up a level.
filtered = _.map(filtered, function(filtered_result) {
return filtered_result['doc'];
});
// Fix the CouchDB doc to look like an OSDF doc
filtered = _.map(filtered, function(filtered_result) {
return osdf_utils.fix_keys(filtered_result);
});
// Exclude nodes that we do not have read permission for
var user = auth.get_user(request);
filtered = _.filter(filtered, function(node) {
return perms.has_read_permission(user, node);
});
// Assemble the final document for transmission
var report = {
'result_count': filtered.length,
'page': 1,
'results': []
};
_.each(filtered, function(filtered_result) {
report['results'].push( filtered_result );
});
response.jsonp(report);
});
} catch (e) {
logger.error(e);
osdf_error(response, 'Unable to retrieve node linkages.', 500);
}
};
// This is the method that handles node creation.
exports.insert_node = function(request, response) {
logger.debug('In insert_node.');
var content = request.rawBody;
waterfall([
function(callback) {
var node_data;
try {
node_data = JSON.parse(content);
} catch (err) {
callback({err: 'Invalid JSON data.', code: 422}, null);
return;
}
callback(null, node_data);
},
function(node_data, callback) {
validate_incoming_node(content, function(err, report) {
if (err) {
logger.error(err);
callback({err: err, code: 422});
} else {
callback(null, report, node_data);
}
});
},
function(report, node_data, callback) {
if (successful_validation_report(report)) {
logger.info('Node validated properly.');
callback(null, node_data);
} else {
if (report !== null && report.errors !== null && report.errors.length > 0) {
var first_err = report.errors[0];
logger.info('Node does not validate. Error: ' + first_err);
callback({err: first_err, code: 422});
} else {
callback({err: 'Node does not validate.', code: 422});
}
}
},
function(node_data, callback) {
couch_conn.uuids(1, function(err, uuid_list) {
if (err) {
callback(err, null);
} else {
callback(null, uuid_list[0], node_data);
}
});
},
function(uuid, node_data, callback) {
node_data['ver'] = 1;
node_data['id'] = uuid;
// Checksum the data for provenance purposes
node_data = provenance.hash_first_version(node_data);
// Set the ID for the document for CouchDB
//node_data['_id'] = uuid;
// Persist to CouchDB
logger.debug('Saving node to CouchDB.');
//db.save(node_data, function(err, couch_response) {
db.save(uuid, node_data, function(err, couch_response) {
if (err) {
logger.error(err);
callback(err);
} else {
logger.debug('Successfully saved node to CouchDB.');
callback(null, couch_response, node_data);
}
});
},
function(couch_response, node_data, callback) {
var node_id = couch_response.id;
if (couch_response.ok === true) {
// Save the history
node_data['id'] = node_id;
save_history(node_id, node_data, function(err) {
if (err) {
logger.error(err);
callback({err: err, code: 500});
} else {
var node_url = '{}:{}/nodes/{}'.format(base_url, port, node_id);
callback(null, node_url);
}
});
} else {
// This shouldn't happen, but...
logger.error("No error, but CouchDB response was not 'ok'.");
callback({err: 'Unable to save data.', code: 500});
}
}],
function(err, node_url) {
if (err) {
if (_.isPlainObject(err) && err.hasOwnProperty('err') &&
err.hasOwnProperty('code')) {
osdf_error(response, err['err'], err['code']);
} else {
logger.error(err);
osdf_error(response, 'Unable to save node.', 500);
}
} else {
logger.info('Successful insertion: ' + node_url);
response.location(node_url);
response.status(201).send('');
}
});
};
// This is the function that handles edits/modifications to nodes.
exports.update_node = function(request, response) {
logger.debug('In update_node.');
var node_id = request.params.id;
var content = request.rawBody;
waterfall([
function(callback) {
// Check that we have been provided valid JSON
try {
var node_data = JSON.parse(content);
callback(null, node_data);
} catch (err) {
callback({err: 'Invalid JSON data.', code: 422}, null);
}
},
function(node_data, callback) {
// Check that the version has been supplied.
if (node_data !== null && node_data.hasOwnProperty('ver')) {
callback(null, node_data);
} else {
callback({
err: 'Incoming node data does not supply the node version.',
code: 422
});
}
},
function(node_data, callback) {
validate_incoming_node(content, function(err, report) {
if (err) {
callback({err: err, code: 422});
} else {
callback(null, report, node_data);
}
});
},
function(report, node_data, callback) {
if (successful_validation_report(report)) {
logger.info('Node validated properly.');
callback(null, node_data);
} else {
if (report !== null && report.errors !== null && report.errors.length > 0) {
var first_err = report.errors[0];
logger.info('Node does not validate. Error: ' + first_err);
callback({err: first_err, code: 422});
} else {
callback({err: 'Node does not validate.', code: 422});
}
}
},
function(node_data, callback) {
var user = auth.get_user(request);
// If here, then the node looks okay for an update in terms of
// structure and validation. Now need to check permissions and
// execute the update, for which we have an auxiliary function.
update_helper(user, node_id, node_data, function(err, update_result) {
if (err) {
logger.error('Unable to update data in CouchDB.', err);
var msg = update_result['msg'];
var code = update_result['code'];
callback({'err': msg, 'code': code});
} else {
callback(null);
}
});
}],
function(err) {
if (err) {
if (_.isPlainObject(err) && err.hasOwnProperty('err') &&
err.hasOwnProperty('code')) {
osdf_error(response, err['err'], err['code']);
} else {
logger.error(err);
osdf_error(response, 'Unable to update node.', 500);
}
} else {
logger.info('Successful update for node id: ' + node_id);
response.status(200).send('');
}
});
};
// Just validate a node against a schema if it has one assigned for the
// specified node_type. If it does NOT then then only a check for
// well-formedness and basic OSDF structure is performed.
exports.validate_node = function(request, response) {
logger.debug('In validate_node.');
var content = request.rawBody;
var report; // To hold the results of validation
waterfall([
function(callback) {
var e = false;
try {
var node_data = JSON.parse(content);
} catch (err) {
e = true;
}
if (e) {
callback({err: 'Invalid JSON provided.', code: 422 });
} else {
callback(null, node_data);
}
},
function(node_data, callback) {
validate_incoming_node(content, function(err, report) {
if (err) {
callback(err, null);
} else {
callback(null, report);
}
});
},
function(report, callback) {
if (successful_validation_report(report)) {
// If here, then we're valid
logger.info('Detected a valid node.');
callback(null);
} else {
var first_err = report.errors[0];
logger.info('Invalid node. First error: ', first_err);
// Assemble the full list of errors by iterating and
// concatenating to a string.
var error_text = '';
_.forEach(report.errors, function(err) {
error_text = error_text.concat(err + '\n');
});
error_text = error_text.trim() + '\n';
var err_object = {
err: first_err,
code: 422,
content: error_text
};
callback(err_object);
}
}],
function(err, result) {
if (err) {
// If here, then it's because the node data didn't validate
// or some other problem occurred.
if (_.isPlainObject(err) && err.hasOwnProperty('err') &&
err.hasOwnProperty('code')) {
// Here we do not simply use the osdf_error() function because
// we actually want to list all the error messages without the
// user having to inspect HTTP headers. The first error message
// will still be in the headers though...
response.set('X-OSDF-Error', err['err']);
response.status(err['code']);
if (err.hasOwnProperty('content')) {
response.send(err['content']);
} else {
response.send('');
}
} else {
osdf_error(response, 'Could not validate node.', 500);
}
} else {
logger.debug('Valid node detected.');
response.status(200).send('');
}
});
};
// This message is used to process auxiliary schema deletion events
// that are relayed to this process from the master process by worker.js.
exports.process_aux_schema_change = function(msg) {
logger.debug('In process_aux_schema_change.');
var aux_schema_json;
if (msg.hasOwnProperty('cmd') && msg['cmd'] === 'aux_schema_change') {
var namespace = msg['ns'];
var aux_schema_name = msg['name'];
if (msg.hasOwnProperty('type') && msg['type'] === 'insertion') {
logger.debug('Got an auxiliary schema insertion.');
aux_schema_json = msg['json'];
insert_aux_schema_helper(namespace, aux_schema_name, aux_schema_json);
} else if (msg.hasOwnProperty('type') && msg['type'] === 'update') {
logger.debug('Got an auxiliary schema update.');
aux_schema_json = msg['json'];
update_aux_schema_helper(namespace, aux_schema_name, aux_schema_json);
} else if (msg.hasOwnProperty('type') && msg['type'] === 'deletion') {
logger.debug('Got an auxiliary schema deletion.');
delete_aux_schema_helper(namespace, aux_schema_name);
}
}
};
// This message is used to process schema deletion events that are relayed to
// this process from the master process by worker.js.
exports.process_schema_change = function(msg) {
logger.debug('In process_schema_change.');
if (msg.hasOwnProperty('cmd') && msg['cmd'] === 'schema_change') {
var namespace = msg['ns'];
var schema_name = msg['name'];
if (msg.hasOwnProperty('type') && msg['type'] === 'insertion') {
var json = msg['json'];
insert_schema_helper(namespace, schema_name, json);
} else if (msg.hasOwnProperty('type') && msg['type'] === 'deletion') {
delete_schema_helper(namespace, schema_name);
}
}
};
// Validates the data presented based on the json-schema of the node type.
// Returns a report with validation results, or throws an exception if we
// are unable to get that far, for instance, if the content can't be parsed
// into a JSON data structure.
function validate_incoming_node(node_string, callback) {
logger.debug('In validate_incoming_node.');
var node;
var msg;
if (typeof node_string === 'string') {
try {
node = JSON.parse(node_string);
} catch (parse_error) {
msg = 'Unable to parse content into JSON.';
logger.debug(msg);
callback(msg, null);
return;
}
}
// Do a rudimentary check with json-schema for whether the JSON document
// has the required structure/keys.
var base_result = base_validate(node);
if (! base_result) {
var errors = [];
_.each(base_validate.errors, function(validation_error) {
var err_msg = '{} on path {}'.format(
validation_error.message,
validation_error.dataPath
);
errors.push(err_msg);
});
logger.debug('Node JSON does not possess the correct structure.');
var report = {
valid: false,
errors: errors
};
callback(null, report);
return;
}
waterfall([
function(callback) {
var errors = [];
if (! _.includes(namespaces, node.ns)) {
msg = 'Node belongs to an unrecognized namespace.';
logger.error(msg);
errors.push(msg);
}
callback(null, errors);
},
function(errors, callback) {
// Check if the linkages look okay...
linkage_controller.valid_linkage(node, function(err, valid) {
if (err) {
logger.error('Error when checking for linkage validity: ' + err);
callback('Unable to check linkage validity.');
} else {
if (! valid) {
errors.push('Invalid linkage detected for node.');
}
callback(null, errors, valid);
}
});
},
function(errors, linkage_validity, callback) {
logger.debug('Linkage validity: ' + linkage_validity);
var report = null;
if ( validators.hasOwnProperty(node.ns) &&
validators[node.ns].hasOwnProperty(node.node_type) ) {
// Look up the schema for this node type from our validators
// data structure.
var schema = validators[node.ns][node.node_type]['schema'];
// So, we don't validate the whole node against the JSON schema,
// just the 'meta' portion.
var metadata = node['meta'];
// And validate...
var validator = validators[node.ns]['val'];
var valid;
try {
valid = validator.validate(schema, metadata);
} catch (err) {
callback('Error validating document: ' + err);
}
if (! valid) {
_.each(validator.errors, function(validation_error) {
var err_msg = validation_error.message + ' on path ' +
validation_error.dataPath;
errors.push(err_msg);
});
}
// We have to consider BOTH linkage validity AND JSON-Schema
// validity
var combined_validity = linkage_validity && valid;
report = {
valid: combined_validity,
errors: errors
};
} else {
logger.debug('No validator found for namespace/node_type of {}/{}.'.
format(node.ns, node.node_type));
// Since there is no JSON-Schema validation to check, the only
// validity to consider at this point is the linkage validity.
report = {
valid: linkage_validity,
errors: errors
};
}
callback(null, report);
}],
function(err, report) {
if (err) {
logger.error(err);
callback(err, null);
} else {
callback(null, report);
}
});
}
// A function to parse the version of a CouchDB document out
// from its native CouchDB representation as a string to a
// numeric form.
// Parameters: CouchDB (string)
// Returns: int
function parse_version(couchdb_version) {
logger.debug('In parse_version.');
if (couchdb_version === null) {
throw 'Invalid CouchDB version provided.';
}
var couchdb_version_int = parseInt(couchdb_version.split('-')[0], 10);
return couchdb_version_int;
}
function get_node_version(node_id, callback) {
logger.debug('In get_node_version.');
db.get(node_id, function(err, data) {
if (err) {
callback('Unable to retrieve node operation.', null);
} else {
var couchdb_version = data['_rev'];
var version = parse_version(couchdb_version);
callback(null, version);
}
});
}
// Simple function to retrieve a document from CouchDB backing database It then
// calls the user provided callback with an error flag, and the document which
// is null if an error was encountered.
// Parameters: couchdb_id (string), callback (function)
// Returns: none
function get_couch_doc(couchdb_id, callback) {
logger.debug('In get_couch_doc.');
db.get(couchdb_id, function(err, data) {
if (err) {
callback('Unable to retrieve CouchDB doc.', null);
} else {
callback(null, data);
}
});
}
function update_helper(user, node_id, node_data, callback) {
logger.debug('In update_helper.');
var node_version = node_data['ver'];
// What we will send back through the callback
var result = {};
waterfall([
function(callback) {
get_couch_doc(node_id, function(err, data) {
if (err) {
result['msg'] = 'Unable to perform update operation.';
result['code'] = 500;
// This should stop the waterfall...
callback(err);
} else {
callback(null, data);
}
});
},
function(data, callback) {
var previous_node = data;
var previous_version = previous_node['ver'];
var previous_couch_version = previous_node['_rev'];
if (node_version !== previous_version) {
var msg = "Version provided ({}) doesn't match saved ({}).";
msg = msg.format(node_version, previous_version);
result['msg'] = msg;
result['code'] = 422;
// This should stop the waterfall...
callback(msg);
} else {
callback(null, previous_node, previous_couch_version);
}
},
function(previous_node, previous_couch_version, callback) {
// Check that the user has sufficient permissions to make
// edits to this node.
var can_write = perms.has_write_permission(user, previous_node);
if (can_write) {
logger.debug('User {} has write permission to node {}.'
.format(user, node_id)
);
callback(null, previous_node, previous_couch_version);