-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.js
2494 lines (2356 loc) · 141 KB
/
server.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
const axios = require('axios');
/* Application dependencies & config - START */
// Config
require('dotenv').config();
// PATH
var path = require('path');
// Tool required for reading AOT manifest
const readline = require('readline');
//ContentType
const FileType = require('file-type');
// Node Cache
const NodeCache = require("node-cache");
const myCache = new NodeCache();
// Random string
var randomstring = require("randomstring");
// UUID
const {
v4: uuidv4
} = require('uuid');
//File system
const fs = require('fs');
// Server name for keys
const server_name = process.env.server_name;
// HTTPS
const https = require('https');
const privateKey = fs.readFileSync('/etc/letsencrypt/live/' + server_name + '/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/' + server_name + '/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/' + server_name + '/fullchain.pem', 'utf8');
const helmet = require("helmet");
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
// Buffer string to array
const converter = require('buffer-string-to-array')
// Express
const express = require('express');
const app = express();
app.use(helmet());
// Body parser
var bodyParser = require('body-parser');
app.use(bodyParser.text({
type: "text/plain",
limit: 100000000
}));
app.use(bodyParser.json({
type: "application/json"
}));
app.use(bodyParser.raw({
type: "application/octet-stream",
limit: 100000000
}));
//Port
const port = process.env.port;
// Data ser/des
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
// CORS
var cors = require('cors');
app.use(cors());
// Database
console.log("Connecting to database, please wait ... ");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: process.env.db_host,
user: process.env.db_user,
password: process.env.db_password,
database: process.env.db_name
});
connection.connect((err) => {
if (err) throw err;
console.log('Connection to database succeeded!');
});
// Logging
// 0 equals no logging
// 1 equals logging
console.log("Setting log level ...");
const log_level = process.env.log_level;
// Measure gas and invocations
console.log("Setting whether to measure gas and invocations");
const measure_gas_and_invocations = process.env.measure_gas_and_invocations;
// Filtering the content types which are allowed to access Joey
app.use(function(req, res, next) {
if (req.method === 'POST') {
if (req.is('application/octet-stream' !== 'application/octet-stream') || req.is('application/json' !== 'application/json') || req.is('text/plain' !== 'text/plain')) {
return res.send(406);
}
}
next();
});
// Multipart form data
const formidable = require('formidable');
// SSVM
//var ssvm = require('ssvm-storage');
const ssvm = require("wasmedge-extensions");
// Checksum
const checksum = require('crypto');
// Rate limiter
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 100 // limit each IP to 2 requests per windowMs
});
// apply to all requests
app.use(limiter);
/* Application dependencies & config - END */
/* Application startup - START */
// Serve
https.createServer(credentials, app).listen(port, process.env.host, () => {
console.log(`Welcome to wasm-joey` + '\nHost:' + process.env.host + '\nPort: ' + port);
console.log("Reading database configuration, please wait ... ");
console.log("Database host: " + process.env.db_host);
console.log("Database port: " + process.env.db_port);
console.log("Database name: " + process.env.db_name);
console.log("Database user: " + process.env.db_user);
console.log("\n");
});
// START Load AOT files from manifect
const readInterface = readline.createInterface({
input: fs.createReadStream(path.join(process.env.aot_dir, 'manifest.txt')),
output: process.stdout,
console: false
});
console.log("Loading AOT into cache");
readInterface.on('line', function(line) {
var split_id_aot = line.split(",");
console.log("Loading " + split_id_aot[0] + "'s AOT file into cache (" + split_id_aot[1] + ")");
myCache.set(split_id_aot[0], split_id_aot[1], 0);
});
// END Load AOT files from manifect
function writeToUsageFile(_wasm_id, _gas, _execution_time) {
return new Promise(function(resolve, reject) {
var usage_file = _wasm_id + ".txt";
var file_path = path.join(process.env.usage_dir, usage_file);
var timestamp = Math.floor(new Date().getTime() / 1000)
fs.appendFile(file_path, timestamp + "," + _gas + "," + _execution_time + '\n', function(err) {
if (err) throw err;
console.log("Usage recorded at " + file_path);
resolve();
});
});
}
function readLines(_readInterface2) {
return new Promise(function(resolve, reject) {
overview = {};
details = {};
_readInterface2.on('line', function(line) {
//console.log("Line:" + line);
var split_time_gas = line.split(",");
details["gas"] = split_time_gas[1];
details["total_execution_time"] = split_time_gas[2];
overview[split_time_gas[0]] = details;
}).on('close', function() {
//console.log("Internal object: " + JSON.stringify(overview));
resolve(overview);
});
});
}
function readUsageFile(_wasm_id) {
return new Promise(function(resolve, reject) {
var usage_obj = {};
var usage_file = _wasm_id + ".txt";
var file_path = path.join(process.env.usage_dir, usage_file);
console.log("File path: " + file_path);
if (fs.existsSync(file_path)) {
console.log("Reading usage file");
const readInterface2 = readline.createInterface({
input: fs.createReadStream(file_path),
output: process.stdout,
console: false
});
readLines(readInterface2).then((readResult) => {
usage_obj["full_usage_report"] = readResult;
//console.log("Usage object ... : " + JSON.stringify(usage_obj));
resolve(JSON.stringify(usage_obj));
});
} else {
usage_obj["full_usage_report"] = {};
console.log(" ... No usage recorded for " + _wasm_id + " \nPlease set measure_gas_and_invocations=1 in the .env file to start usage collection");
resolve(JSON.stringify(usage_obj));
}
});
}
/* Application startup - END */
/* Utils - START */
function objectIsEmpty(_json) {
if (typeof _json == "string") {
_json = JSON.parse(_json);
}
//console.log("Processing JSON: " + JSON.stringify(_json));
var empty = true;
return new Promise(function(resolve, reject) {
for (var key in _json) {
console.log("Processing key: " + key);
if (_json.hasOwnProperty(key)) {
console.log("*");
empty = false;
break;
}
}
console.log("It is resolved that the JSON object is not empty, returning to function execution ...");
resolve(empty);
});
}
function isValidJSON(text) {
return new Promise(function(resolve, reject) {
if (typeof text !== "string") {
console.log("Not a JSON string");
resolve(false);
}
try {
JSON.parse(text);
resolve(true);
} catch (error) {
resolve(false);
}
});
}
function removeElementFromArray(arr, value) {
return arr.filter(function(ele) {
return ele != value;
});
}
function performSqlQuery(string_query, parameter_array) {
return new Promise(function(resolve, reject) {
connection.query(string_query, parameter_array, function(err, resultSelect) {
if (err) {
res.status(400).send("Perhaps a bad request, or database is not running");
}
resolve(resultSelect);
});
});
}
function executableExists(wasm_id) {
return new Promise(function(resolve, reject) {
connection.query("select wasm_id from wasm_executables where wasm_id='" + wasm_id + "';", function(err, resultSelect) {
if (err) {
res.status(400).send("Perhaps a bad request, or database is not running");
}
resolve(resultSelect.length);
});
});
}
function executionLogExists(wasm_id) {
return new Promise(function(resolve, reject) {
connection.query("select log_id from wasm_execution_log where wasm_executable_id='" + wasm_id + "';", function(err, resultSelect) {
if (err) {
res.status(400).send("Perhaps a bad request, or database is not running");
}
resolve(resultSelect.length);
});
});
}
function executeCallbackRequest(_original_id, _request_options) {
return new Promise(function(resolve, reject) {
if (log_level == 1) {
parameterArray = [_original_id];
var sqlSelect = "SELECT wasm_state FROM wasm_executables WHERE wasm_id = ?;";
performSqlQuery(sqlSelect, parameterArray).then((stateResult) => {
var logging_object = {};
logging_object["original_wasm_executables_id"] = _original_id;
logging_object["callback_request_options"] = _request_options;
parameterArray2 = [_original_id, stateResult[0].wasm_state, JSON.stringify(logging_object)];
var sqlInsert = "INSERT INTO wasm_execution_log (wasm_executable_id, wasm_executable_state, execution_timestamp, execution_object) VALUES (?, ?, NOW(), ?);";
performSqlQuery(sqlInsert, parameterArray2).then((resultInsert) => {});
});
}
var options = JSON.parse(_request_options);
var data = options.body;
if (typeof data == "object") {
data = JSON.stringify(data);
}
options["headers"]["Content-Length"] = data.length;
delete options.body;
const req = https.request(JSON.parse(JSON.stringify(options)), (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
resolve(data);
} catch (error) {
console.error(error.message);
};
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
});
}
function executeMultipartRequest(_original_id, _request_options) {
return new Promise(function(resolve, reject) {
if (log_level == 1) {
parameterArray = [_original_id];
var sqlSelect = "SELECT wasm_state FROM wasm_executables WHERE wasm_id = ?;";
performSqlQuery(sqlSelect, parameterArray).then((stateResult) => {
var logging_object = {};
logging_object["original_wasm_executables_id"] = _original_id;
logging_object["callback_request_options"] = _request_options;
parameterArray2 = [_original_id, stateResult[0].wasm_state, JSON.stringify(logging_object)];
var sqlInsert = "INSERT INTO wasm_execution_log (wasm_executable_id, wasm_executable_state, execution_timestamp, execution_object) VALUES (?, ?, NOW(), ?);";
performSqlQuery(sqlInsert, parameterArray2).then((resultInsert) => {});
});
}
var options = JSON.parse(_request_options);
const data = JSON.stringify(options["body"]);
delete options.body;
options["headers"]["Content-Length"] = data.length;
const req = https.request(options, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on("end", () => {
try {
if (typeof body == "object") {
resolve(JSON.stringify(body));
} else if (typeof body == "string") {
resolve(body);
}
} catch (error) {
console.error(error.message);
};
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
});
}
function axiosFetch(_value) {
return new Promise(function(resolve, reject) {
axios.get(_value, {
responseType: 'arraybuffer'
}).then(function(response) {
//const buffer = Buffer.from(response.data, "utf-8");
// The following will produce 0-255 u8 style
const buffer = new Uint8Array(response.data);
//console.log(buffer);
resolve(buffer);
})
.catch(function(error) {
// handle error
console.log(error);
})
.then(function() {
// always executed
});
});
}
function fetchUsingGet(_value) {
if (_value.charAt(0) == '"' && _value.charAt(_value.length - 1) == '"') {
_value = _value.substr(1, _value.length - 2)
}
return new Promise(function(resolve, reject) {
https.get(_value, (res) => {
let body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
try {
if (typeof body == "object") {
resolve(JSON.stringify(data));
} else if (typeof body == "string") {
var contentType = res.headers['content-type'];
if (contentType.startsWith("image")) {
axiosFetch(_value).then((result, error) => {
if (!error) {
resolve(result);
} else {
console.log(file_read_error);
}
});
} else {
resolve(body);
}
}
} catch (error) {
console.error(error.message);
};
});
}).on("error", (error) => {
console.error(error.message);
});
});
}
function getContentType(_file_path) {
return new Promise(function(resolve, reject) {
var a = FileType.fromFile(_file_path);
resolve(a);
});
}
function readTheFile(_file) {
return new Promise(function(resolve, reject) {
var file_path = _file[1]["path"];
var aa = getContentType(file_path).then((result, error) => {
if (!error) {
fs.readFile(file_path, (err, data) => {
if (err) {
console.log("err ocurred", err);
} else {
var return_data = {};
//console.log("FILE DATA: " + data);
if (JSON.stringify(result).includes("image")) {
console.log("This is an image");
const image_as_array = Uint8Array.from(data);
return_data[_file[0]] = image_as_array;
return_data["content_type"] = "image";
resolve(return_data);
} else {
return_data[_file[0]] = data;
return_data["content_type"] = "string";
resolve(return_data);
}
}
});
} else {
console.log(file_read_error);
}
});
});
}
function parseMultipart(_readyAtZero, _files, _fields, _req) {
return new Promise(function(resolve, reject) {
for (var file of Object.entries(_files)) {
readTheFile(file).then((fetched_result_object, file_read_error) => {
if (!file_read_error) {
if (fetched_result_object["content_type"].toString().includes("image")) {
const _string_position = Object.keys(fetched_result_object)[0].lastIndexOf("_");
const index_key = Object.keys(fetched_result_object)[0].slice(_string_position + 1, Object.keys(fetched_result_object)[0].length);
_readyAtZero.container[index_key] = fetched_result_object[Object.keys(fetched_result_object)[0]];
_readyAtZero.decrease();
if (_readyAtZero.isReady()) {
resolve();
}
} else {
const _string_position = Object.keys(fetched_result_object)[0].lastIndexOf("_");
const index_key = Object.keys(fetched_result_object)[0].slice(_string_position + 1, Object.keys(fetched_result_object)[0].length);
_readyAtZero.container[index_key] = fetched_result_object[Object.keys(fetched_result_object)[0]]["data"];
_readyAtZero.decrease();
if (_readyAtZero.isReady()) {
resolve();
}
}
} else {
console.log(file_read_error);
}
});
}
for (var field of Object.entries(_fields)) {
const _string_position = field[0].lastIndexOf("_");
const index_key = field[0].slice(_string_position + 1, field[0].length);
if (field[0].startsWith("fetch")) {
if (field[1].startsWith("http")) {
console.log("Fetching data using GET ...");
fetchUsingGet(field[1]).then((fetched_result, error) => {
console.log("Fetching data using GET success!");
_readyAtZero.container[index_key] = fetched_result;
_readyAtZero.decrease();
if (_readyAtZero.isReady()) {
resolve();
}
});
} else {
console.log("Fetching data using POST object ...");
executeMultipartRequest(_req.params.wasm_id, field[1]).then((fetched_result2, error) => {
console.log("Fetching data using POST object success!");
fetched_result_object2 = JSON.parse(JSON.stringify(fetched_result2));
_readyAtZero.container[index_key] = JSON.stringify(fetched_result_object2);
_readyAtZero.decrease();
if (_readyAtZero.isReady()) {
resolve();
}
});
}
} else if (field[0].startsWith("SSVM_Callback") || field[0].startsWith("ssvm_callback")) {
if (_readyAtZero.callback_already_set == false) {
_readyAtZero.set_callback_object(JSON.parse(field[1]));
_readyAtZero.decrease();
} else if (_readyAtZero.callback_already_set == true) {
_readyAtZero.decrease();
}
if (_readyAtZero.isReady()) {
resolve();
}
} else {
_readyAtZero.container[index_key] = field[1];
_readyAtZero.decrease();
if (_readyAtZero.isReady()) {
resolve();
}
}
}
});
}
function getOptions(_wasm_id) {
return new Promise(function(resolve, reject) {
parameterArray = [_wasm_id];
var sqlSelect = "SELECT storage_key, wasm_state from wasm_executables WHERE wasm_id = ?;";
performSqlQuery(sqlSelect, parameterArray).then((result, error) => {
var _storage_key = result[0].storage_key;
var _wasm_state = result[0].wasm_state;
var enable_measurement = false;
if (measure_gas_and_invocations > 0) {
enable_measurement = true;
}
var ssvm_options = {
"EnableAOT": true,
"EnableMeasurement": enable_measurement,
"args": [],
"env": {
"wasm_id": _wasm_id,
"storage_key": _storage_key
},
"preopens": {
"/": "/tmp"
}
};
ssvm_options.args[0] = _wasm_state;
console.log("SSVM Options: " + JSON.stringify(ssvm_options));
resolve(JSON.stringify(ssvm_options));
});
});
}
function updateAOT(_wasm_id, _ssvm_options, _is_an_update) {
return new Promise(function(resolve, reject) {
if (_is_an_update == false) {
var aot_filename = myCache.get(_wasm_id);
if (aot_filename == undefined) {
console.log("AOT filename not found, please wait ...");
parameterArray = [_wasm_id];
var sqlSelect = "SELECT wasm_binary from wasm_executables WHERE wasm_id = ?;";
performSqlQuery(sqlSelect, parameterArray).then((result2, error2) => {
const nodeBuffer2 = new Buffer.from(result2[0].wasm_binary.toString().split(','));
var uint8array = new Uint8Array(nodeBuffer2.buffer, nodeBuffer2.byteOffset, nodeBuffer2.length);
var vm = new ssvm.VM(uint8array, _ssvm_options);
var new_aot_key = uuidv4() + ".so";
var file_path = path.join(process.env.aot_dir, new_aot_key);
var bool_compiled = vm.Compile(file_path);
console.log("Was the AOT compile a success ... ?: " + bool_compiled);
myCache.set(_wasm_id, new_aot_key, 0);
fs.appendFile(path.join(process.env.aot_dir, "manifest.txt"), _wasm_id + "," + new_aot_key + '\n', function(err) {
if (err) throw err;
console.log("AOT executable saved at " + file_path);
resolve();
});
});
} else {
resolve();
}
} else if (_is_an_update == true) {
console.log("AOT file needs to be updated, please wait ...");
parameterArray = [_wasm_id];
var sqlSelect = "SELECT wasm_binary from wasm_executables WHERE wasm_id = ?;";
performSqlQuery(sqlSelect, parameterArray).then((result2, error2) => {
const nodeBuffer2 = new Buffer.from(result2[0].wasm_binary.toString().split(','));
var uint8array = new Uint8Array(nodeBuffer2.buffer, nodeBuffer2.byteOffset, nodeBuffer2.length);
var vm = new ssvm.VM(uint8array, _ssvm_options);
var new_aot_key = uuidv4() + ".so";
var file_path = path.join(process.env.aot_dir, new_aot_key);
var bool_compiled = vm.Compile(file_path);
console.log("Was the AOT compile a success ... ?: " + bool_compiled);
myCache.set(_wasm_id, new_aot_key, 0);
fs.appendFile(path.join(process.env.aot_dir, "manifest.txt"), _wasm_id + "," + new_aot_key + '\n', function(err) {
if (err) throw err;
console.log("Updated AOT executable saved at " + file_path);
resolve();
});
});
}
});
}
function executeSSVM(_readyAtZero, _wasm_id, _storage_key, _function_name, _array_of_parameters, _return_type) {
var _joey_response = {};
return new Promise(function(resolve, reject) {
getOptions(_wasm_id).then((optionsResult, optionsError) => {
updateAOT(_wasm_id, optionsResult, false).then((aotResult, aotError) => {
aot_filename = myCache.get(_wasm_id);
console.log("Instantiating SSVM with AOT filename of: " + path.join(process.env.aot_dir, aot_filename) + " which has a typeof: " + typeof(aot_filename));
options_object = JSON.parse(optionsResult);
var vm = new ssvm.VM(path.join(process.env.aot_dir, aot_filename), options_object);
//console.log("VM:" + vm);
//console.log(vm.GetStatistics());
console.log("Instantiation success!");
if (_readyAtZero.fetchable_already_set == true) {
var fetchable_object = _readyAtZero.get_fetchable_object();
if (fetchable_object.hasOwnProperty("GET")) {
console.log("Performing GET request for SSVM_Fetch ........");
fetchUsingGet(fetchable_object["GET"]).then((fetched_result, error) => {
objectIsEmpty(_readyAtZero.get_callback_object()).then((resultEmptyObject, error) => {
if (resultEmptyObject == false) {
var callback_object_for_processing = _readyAtZero.get_callback_object();
if (typeof callback_object_for_processing == "string") {
callback_object_for_processing = JSON.parse(callback_object_for_processing);
}
try {
console.log("Executing ssvm function WITH a callback ...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, fetched_result);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, fetched_result);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
executeCallbackRequest(_wasm_id, JSON.stringify(callback_object_for_processing)).then((callbackResult, error) => {
resolve(callbackResult);
});
} else {
try {
console.log("Executing ssvm function WITHOUT a callback...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, fetched_result);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, fetched_result);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
resolve(return_value);
}
});
});
} else if (fetchable_object.hasOwnProperty("POST")) {
console.log("Performing POST request for SSVM_Fetch ........");
executeMultipartRequest(_wasm_id, fetchable_object["POST"]).then((fetched_result2, error) => {
objectIsEmpty(_readyAtZero.get_callback_object()).then((resultEmptyObject, error) => {
if (resultEmptyObject == false) {
var callback_object_for_processing = _readyAtZero.get_callback_object();
if (typeof callback_object_for_processing == "string") {
callback_object_for_processing = JSON.parse(callback_object_for_processing);
}
try {
console.log("Executing ssvm function WITH a callback ...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, fetched_result2);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, fetched_result2);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
executeCallbackRequest(_wasm_id, JSON.stringify(callback_object_for_processing)).then((callbackResult, error) => {
resolve(callbackResult);
});
} else {
try {
console.log("Executing ssvm function WITHOUT a callback...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, fetched_result2);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, fetched_result2);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
resolve(return_value);
}
});
});
}
} else if (_array_of_parameters.length == 0) {
objectIsEmpty(_readyAtZero.get_callback_object()).then((resultEmptyObject, error) => {
if (resultEmptyObject == false) {
var callback_object_for_processing = _readyAtZero.get_callback_object();
if (typeof callback_object_for_processing == "string") {
callback_object_for_processing = JSON.parse(callback_object_for_processing);
}
try {
console.log("Parameters len == 0");
console.log("Executing function WITH a callback ...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
executeCallbackRequest(_wasm_id, JSON.stringify(callback_object_for_processing)).then((callbackResult, error) => {
resolve(callbackResult);
});
} else {
try {
console.log("Parameters len == 0");
console.log("Executing function WITHOUT a callback...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
resolve(return_value);
}
});
} else if (_array_of_parameters.length == 1 && typeof _array_of_parameters[0] == "object") {
console.log("There is only one parameter and it is an object, processing now ...");
objectIsEmpty(_array_of_parameters[0]).then((resultEmptyParameter, error) => {
if (resultEmptyParameter == true) {
objectIsEmpty(_readyAtZero.get_callback_object()).then((resultEmptyObject, error) => {
if (resultEmptyObject == false) {
var callback_object_for_processing = _readyAtZero.get_callback_object();
if (typeof callback_object_for_processing == "string") {
callback_object_for_processing = JSON.parse(callback_object_for_processing);
}
try {
console.log("Parameters len == 1 and it is an object");
console.log("Executing function WITH a callback ...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
executeCallbackRequest(_wasm_id, JSON.stringify(callback_object_for_processing)).then((callbackResult, error) => {
resolve(callbackResult);
});
} else {
try {
console.log("Parameters len == 1 and it is an object");
console.log("Executing function WITHOUT a callback...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
resolve(return_value);
}
});
} else {
objectIsEmpty(_readyAtZero.get_callback_object()).then((resultEmptyObject, error) => {
if (resultEmptyObject == false) {
var callback_object_for_processing = _readyAtZero.get_callback_object();
if (typeof callback_object_for_processing == "string") {
callback_object_for_processing = JSON.parse(callback_object_for_processing);
}
try {
console.log("Parameters len == 1 and it is an empty object");
console.log("Executing function WITH a callback ...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, ..._array_of_parameters);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, ..._array_of_parameters);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
try {
console.log("Assuming that this object is not image and wants to be string");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, JSON.stringify(..._array_of_parameters));
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
callback_object_for_processing["body"] = return_value;
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, JSON.stringify(..._array_of_parameters)); if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
callback_object_for_processing["body"] = return_value;
}
} catch (err) {
_joey_response["return_value"] = "Error executing this function, please check function name, input parameters, return parameter for correctness";
resolve(JSON.stringify(_joey_response));
}
}
executeCallbackRequest(_wasm_id, JSON.stringify(callback_object_for_processing)).then((callbackResult, error) => {
resolve(callbackResult);
});
} else {
try {
console.log("Parameters len == 1 and it is an empty object");
console.log("Executing function WITHOUT a callback...");
if (_return_type == "string") {
var return_value = vm.RunString(_function_name, ..._array_of_parameters);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");
} else if (_return_type == "bytes") {
var return_value = vm.RunUint8Array(_function_name, ..._array_of_parameters);
if (measure_gas_and_invocations > 0) {
var usage = vm.GetStatistics();
console.log("Statistics object: " + JSON.stringify(usage.TotalGasCost));
writeToUsageFile(_wasm_id, usage.TotalGasCost, usage.TotalExecutionTime);
}
console.log("Success!");