-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
889 lines (810 loc) · 27.4 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
const http = require('http');
const path = require('path');
const eetase = require('eetase');
const asyngularServer = require('asyngular-server');
const express = require('express');
const serveStatic = require('serve-static');
const morgan = require('morgan');
const uuid = require('uuid');
const agcBrokerClient = require('agc-broker-client');
const agCrudRethink = require('ag-crud-rethink');
const Validator = require('jsonschema').Validator;
const AccountService = require('./services/account-service');
const getDataSchema = require('./schemas/data-schema');
const getRPCSchema = require('./schemas/rpc-schema');
const ENVIRONMENT = process.env.ENV || 'dev';
const BLOCKCHAIN = process.env.BLOCKCHAIN || 'lisk';
const SYNC_FROM_BLOCK_HEIGHT = parseInt(process.env.SYNC_FROM_BLOCK_HEIGHT) || null;
const {
SECRET_SIGNUP_KEY,
AUTH_KEY,
BLOCKCHAIN_WALLET_PASSPHRASE,
STORAGE_ENCRYPTION_KEY
} = process.env;
const ASYNGULAR_PORT = process.env.ASYNGULAR_PORT || 8000;
const ASYNGULAR_WS_ENGINE = process.env.ASYNGULAR_WS_ENGINE || 'ws';
const ASYNGULAR_SOCKET_CHANNEL_LIMIT = Number(process.env.ASYNGULAR_SOCKET_CHANNEL_LIMIT) || 1000;
const ASYNGULAR_LOG_LEVEL = process.env.ASYNGULAR_LOG_LEVEL || 2;
const AGC_INSTANCE_ID = uuid.v4();
const AGC_STATE_SERVER_HOST = process.env.AGC_STATE_SERVER_HOST || null;
const AGC_STATE_SERVER_PORT = process.env.AGC_STATE_SERVER_PORT || null;
const AGC_MAPPING_ENGINE = process.env.AGC_MAPPING_ENGINE || null;
const AGC_CLIENT_POOL_SIZE = process.env.AGC_CLIENT_POOL_SIZE || null;
const AGC_AUTH_KEY = process.env.AGC_AUTH_KEY || null;
const AGC_INSTANCE_IP = process.env.AGC_INSTANCE_IP || null;
const AGC_INSTANCE_IP_FAMILY = process.env.AGC_INSTANCE_IP_FAMILY || null;
const AGC_STATE_SERVER_CONNECT_TIMEOUT = Number(process.env.AGC_STATE_SERVER_CONNECT_TIMEOUT) || null;
const AGC_STATE_SERVER_ACK_TIMEOUT = Number(process.env.AGC_STATE_SERVER_ACK_TIMEOUT) || null;
const AGC_STATE_SERVER_RECONNECT_RANDOMNESS = Number(process.env.AGC_STATE_SERVER_RECONNECT_RANDOMNESS) || null;
const AGC_PUB_SUB_BATCH_DURATION = Number(process.env.AGC_PUB_SUB_BATCH_DURATION) || null;
const AGC_BROKER_RETRY_DELAY = Number(process.env.AGC_BROKER_RETRY_DELAY) || null;
let envConfig;
try {
// A config file attached via a Docker/K8s volume have priority.
envConfig = require(`./config/config.${ENVIRONMENT}.json`);
} catch (error) {
const configDev = require(`./blockchains/${BLOCKCHAIN}/config.dev.json`);
const configProd = require(`./blockchains/${BLOCKCHAIN}/config.prod.json`);
const config = {
dev: configDev,
prod: configProd
};
envConfig = config[ENVIRONMENT];
}
const databaseName = envConfig.databaseName || 'crypticle';
const authTokenExpiry = Math.round(envConfig.authTokenExpiry / 1000);
if (
ENVIRONMENT === 'prod' &&
(
envConfig.secretSignupKey ||
envConfig.authKey ||
envConfig.blockchainWalletPassphrase ||
envConfig.storageEncryptionKey
)
) {
throw new Error(
'The secretSignupKey, authKey, blockchainWalletPassphrase and storageEncryptionKey ' +
'properties should not be present in the config file for a production environment. ' +
'Use SECRET_SIGNUP_KEY, AUTH_KEY, BLOCKCHAIN_WALLET_PASSPHRASE and ' +
'STORAGE_ENCRYPTION_KEY environment variables instead.'
);
}
let secretSignupKey = envConfig.secretSignupKey || SECRET_SIGNUP_KEY;
let authKey = envConfig.authKey || AUTH_KEY;
let blockchainWalletPassphrase = envConfig.blockchainWalletPassphrase || BLOCKCHAIN_WALLET_PASSPHRASE;
let storageEncryptionKey = envConfig.storageEncryptionKey || STORAGE_ENCRYPTION_KEY;
if (secretSignupKey == null) {
throw new Error(
'The secret signup key was not specified. During development, ' +
'it must be provided either through the secretSignupKey config ' +
'option or through the SECRET_SIGNUP_KEY environment variable.' +
'In production, it must be provided through the SECRET_SIGNUP_KEY environment ' +
'variable for security reasons.'
);
}
if (authKey == null) {
throw new Error(
'The auth key was not specified. During development, ' +
'it must be provided either through the authKey config ' +
'option or through the AUTH_KEY environment variable.' +
'In production, it must be provided through the AUTH_KEY environment ' +
'variable for security reasons.'
);
}
if (blockchainWalletPassphrase == null) {
throw new Error(
'The blockchain wallet passphrase was not specified. During development, ' +
'it must be provided either through the blockchainWalletPassphrase config ' +
'option or through the BLOCKCHAIN_WALLET_PASSPHRASE environment variable.' +
'In production, it must be provided through the BLOCKCHAIN_WALLET_PASSPHRASE environment ' +
'variable for security reasons.'
);
}
const dataSchema = getDataSchema({
dbName: databaseName,
maxPageSize: envConfig.publicInfo.maxPageSize
});
let rpcValidator = new Validator();
let rpcSchema = getRPCSchema();
let agOptions = {
batchInterval: 50,
authKey
};
if (process.env.ASYNGULAR_OPTIONS) {
let envOptions = JSON.parse(process.env.ASYNGULAR_OPTIONS);
Object.assign(agOptions, envOptions);
}
function monitorBackpressure(socket) {
let authToken = socket.authToken;
let maxBackpressure = (
authToken && authToken.maxSocketBackpressure
) || envConfig.maxSocketBackpressure;
let isAdmin = authToken && authToken.admin;
if (!isAdmin && socket.getBackpressure() > maxBackpressure) {
throw new Error(
`The total backpressure of socket ${
socket.id
} with account ID ${
socket.authToken && socket.authToken.accountId
} exceeded the maximum threshold of ${
maxBackpressure
} operations`
);
}
}
let httpServer = eetase(http.createServer());
let agServer = asyngularServer.attach(httpServer, agOptions);
agServer.setMiddleware(agServer.MIDDLEWARE_INBOUND_RAW, async (middlewareStream) => {
for await (let action of middlewareStream) {
let {socket} = action;
try {
monitorBackpressure(socket);
} catch (error) {
console.warn('[BackpressureMonitor]', error);
let clientError = new Error('Socket consumed too many resources');
clientError.name = 'ResourceOveruseError';
clientError.isClientError = true;
action.block(clientError);
socket.disconnect(4500, 'Socket consumed too many resources');
continue;
}
action.allow();
}
});
let crudOptions = {
defaultPageSize: 10,
schema: dataSchema,
thinkyOptions: {
host: envConfig.databaseHost || '127.0.0.1',
db: databaseName,
port: envConfig.databasePort || 28015
}
};
let crud = agCrudRethink.attach(agServer, crudOptions);
(async () => {
for await (let {error} of crud.listener('error')) {
console.warn('[CRUD]', error);
}
})();
let shardInfo = {
shardIndex: null,
shardCount: null
};
let accountService = new AccountService({
transactionSettlementInterval: envConfig.transactionSettlementInterval,
withdrawalProcessingInterval: envConfig.withdrawalProcessingInterval,
maxTransactionSettlementsPerAccount: envConfig.maxTransactionSettlementsPerAccount,
maxConcurrentWithdrawalsPerAccount: envConfig.maxConcurrentWithdrawalsPerAccount,
maxConcurrentDebitsPerAccount: envConfig.maxConcurrentDebitsPerAccount,
blockchainSync: envConfig.blockchainSync,
blockchainNodeAddress: envConfig.blockchainNodeAddress,
blockPollInterval: envConfig.blockPollInterval,
blockFetchLimit: envConfig.blockFetchLimit,
blockchainWithdrawalMaxAttempts: envConfig.blockchainWithdrawalMaxAttempts,
bcryptPasswordRounds: envConfig.bcryptPasswordRounds,
thinky: crud.thinky,
crud,
publicInfo: envConfig.publicInfo,
shardInfo,
blockchainWalletPassphrase,
secretSignupKey,
storageEncryptionKey,
blockchainAdapterPath: path.resolve(__dirname, 'blockchains', BLOCKCHAIN, `adapter.js`),
syncFromBlockHeight: SYNC_FROM_BLOCK_HEIGHT
});
(async () => {
for await (let {error} of accountService.listener('error')) {
console.error('[AccountService]', error);
}
})();
(async () => {
for await (let {info} of accountService.listener('info')) {
console.info('[AccountService]', info);
}
})();
(async () => {
for await (let {block} of accountService.listener('processBlock')) {
console.log('[AccountService]', `Processed block at height ${block.height}`);
}
})();
let expressApp = express();
if (ENVIRONMENT === 'dev') {
// Log every HTTP request. See https://github.com/expressjs/morgan for other
// available formats.
expressApp.use(morgan('dev'));
}
expressApp.use(serveStatic(path.resolve(__dirname, 'public')));
// Add GET /health-check express route
expressApp.get('/health-check', (req, res) => {
res.status(200).send('OK');
});
function generateMessageFromSchemaError(error) {
return `The ${error.property.split('.')[1]} field ${error.message}`;
}
function validateRPCSchema(request) {
let schema = rpcSchema[request.procedure];
if (!schema) {
let error = new Error(`Could not find a schema for the ${request.procedure} procedure.`);
error.name = 'NoMatchingRequestSchemaError';
error.isClientError = true;
throw error;
}
let validationResult = rpcValidator.validate(request.data, schema);
if (!validationResult.valid) {
let errorsMessage = validationResult.errors.map(error => generateMessageFromSchemaError(error)).join('. ');
let error = new Error(`${errorsMessage}.`);
error.name = 'RequestSchemaValidationError';
error.errors = validationResult.errors;
error.isClientError = true;
throw error;
}
}
function verifyUserAuth(request, socket) {
if (!socket.authToken) {
let error = new Error(
`Cannot invoke the ${
request.procedure
} procedure while not authenticated.`
);
error.name = 'NotAuthenticatedError';
error.isClientError = true;
throw error;
}
}
function verifyAdminAuth(request, socket) {
if (!socket.authToken || !socket.authToken.admin) {
let error = new Error(
`Cannot invoke the ${
request.procedure
} procedure while not authenticated as an admin.`
);
error.name = 'NotAuthenticatedAsAdminError';
error.isClientError = true;
throw error;
}
}
// HTTP request handling loop.
(async () => {
for await (let requestData of httpServer.listener('request')) {
expressApp.apply(null, requestData);
}
})();
(async () => {
for await (let {socket} of agServer.listener('disconnection')) {
if (socket.authTokenRenewalIntervalId != null) {
clearInterval(socket.authTokenRenewalIntervalId);
}
}
})();
function renewAuthToken(socket) {
if (socket.authToken) {
let {exp, iat, ...tokenData} = socket.authToken;
socket.setAuthToken(tokenData, {expiresIn: authTokenExpiry});
}
}
// Asyngular/WebSocket connection handling loop.
(async () => {
for await (let {socket} of agServer.listener('connection')) {
// Handle socket connection.
// Batch everything to improve performance.
socket.startBatching();
renewAuthToken(socket);
// Refresh the token on an interval so long as the socket is connected.
socket.authTokenRenewalIntervalId = setInterval(() => {
renewAuthToken(socket);
}, envConfig.authTokenRenewalInterval);
(async () => {
for await (let request of socket.procedure('signup')) {
try {
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let accountData;
let accountId;
try {
accountData = await accountService.sanitizeSignupCredentials(request.data);
accountId = await crud.create({
type: 'Account',
value: accountData
});
} catch (error) {
if (error.name === 'DuplicatePrimaryKeyError') {
error = new Error('The specified account ID was already taken.');
error.name = 'AccountIdTakenError';
error.isClientError = true;
}
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Server error.');
clientError.name = 'SignupError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end({accountId});
}
})();
(async () => {
for await (let request of socket.procedure('login')) {
try {
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let accountData;
try {
accountData = await accountService.verifyLoginCredentials(request.data);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Server error.');
clientError.name = 'LoginError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
let token = {
accountId: accountData.id
};
if (accountData.maxConcurrentDebits != null) {
token.maxConcurrentDebits = accountData.maxConcurrentDebits;
}
if (accountData.maxConcurrentWithdrawals != null) {
token.maxConcurrentWithdrawals = accountData.maxConcurrentWithdrawals;
}
if (accountData.maxSocketBackpressure != null) {
token.maxSocketBackpressure = accountData.maxSocketBackpressure;
}
if (accountData.admin) {
token.admin = true;
}
socket.setAuthToken(token, {expiresIn: authTokenExpiry});
request.end({accountId: accountData.id});
}
})();
(async () => {
for await (let request of socket.procedure('getPublicInfo')) {
try {
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
request.end(envConfig.publicInfo);
}
})();
(async () => {
for await (let request of socket.procedure('withdraw')) {
try {
verifyUserAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let withdrawalData = request.data;
let result;
try {
result = await accountService.attemptWithdrawal({
amount: withdrawalData.amount,
fromAccountId: socket.authToken.accountId,
toWalletAddress: withdrawalData.toWalletAddress
}, socket.authToken.maxConcurrentWithdrawals);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute withdrawal due to a server error');
clientError.name = 'WithdrawError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('transfer')) {
try {
verifyUserAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let transferData = request.data;
let result;
try {
result = await accountService.attemptTransfer({
amount: transferData.amount,
fromAccountId: socket.authToken.accountId,
toAccountId: transferData.toAccountId,
debitId: transferData.debitId,
creditId: transferData.creditId,
data: transferData.data
}, socket.authToken.maxConcurrentDebits);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute transfer due to a server error');
clientError.name = 'TransferError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('debit')) {
try {
verifyUserAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let debitData = request.data;
let result;
try {
result = await accountService.attemptDirectDebit({
amount: debitData.amount,
fromAccountId: socket.authToken.accountId,
debitId: debitData.debitId,
data: debitData.data
}, socket.authToken.maxConcurrentDebits);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute debit due to a server error');
clientError.name = 'DebitError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('getBalance')) {
try {
verifyUserAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let balance;
try {
balance = await accountService.fetchAccountBalance(socket.authToken.accountId);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to get account balance due to a server error');
clientError.name = 'GetBalanceError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(balance);
}
})();
(async () => {
for await (let request of socket.procedure('adminImpersonate')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let accountData;
try {
accountData = await accountService.verifyLoginCredentialsAccountId(request.data);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error(`Failed to login to account ${request.data.accountId}.`);
clientError.name = 'AdminLoginError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
let realAccountId = socket.authToken.impersonator || socket.authToken.accountId;
let isOwnAdminAccount = accountData.id === realAccountId;
if (accountData.admin && !isOwnAdminAccount) {
let clientError = new Error(
`Failed to login to account ${
request.data.accountId
} because other admin accounts cannot be impersonated.`
);
clientError.name = 'AdminLoginError';
clientError.isClientError = true;
request.error(clientError);
console.error(clientError);
continue;
}
let token = {
accountId: accountData.id,
admin: true
};
if (!isOwnAdminAccount) {
token.impersonator = realAccountId;
}
socket.setAuthToken(token, {expiresIn: authTokenExpiry});
request.end({accountId: accountData.id});
}
})();
(async () => {
for await (let request of socket.procedure('adminWithdraw')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let withdrawalData = request.data;
let result;
try {
result = await accountService.execWithdrawal({
amount: withdrawalData.amount,
fromAccountId: withdrawalData.fromAccountId,
toWalletAddress: withdrawalData.toWalletAddress
});
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute withdrawal due to a server error');
clientError.name = 'AdminWithdrawError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('adminTransfer')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let transferData = request.data;
let result;
try {
result = await accountService.execTransfer({
amount: transferData.amount,
fromAccountId: transferData.fromAccountId,
toAccountId: transferData.toAccountId,
debitId: transferData.debitId,
creditId: transferData.creditId,
data: transferData.data
});
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute transfer due to a server error');
clientError.name = 'AdminTransferError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('adminDebit')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let debitData = request.data;
let result;
try {
result = await accountService.execDirectDebit({
amount: debitData.amount,
fromAccountId: debitData.fromAccountId,
debitId: debitData.debitId,
data: debitData.data
});
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute debit due to a server error');
clientError.name = 'DebitError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('adminCredit')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let creditData = request.data;
let result;
try {
result = await accountService.execDirectCredit({
amount: creditData.amount,
toAccountId: creditData.toAccountId,
creditId: creditData.creditId,
data: creditData.data
});
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to execute credit due to a server error');
clientError.name = 'CreditError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(result);
}
})();
(async () => {
for await (let request of socket.procedure('adminGetBalance')) {
try {
verifyAdminAuth(request, socket);
validateRPCSchema(request);
} catch (error) {
request.error(error);
console.error(error);
continue;
}
let getBalanceData = request.data;
let balance;
try {
balance = await accountService.fetchAccountBalance(getBalanceData.accountId);
} catch (error) {
if (error.isClientError) {
request.error(error);
} else {
let clientError = new Error('Failed to get account balance due to a server error');
clientError.name = 'AdminGetBalanceError';
clientError.isClientError = true;
request.error(clientError);
}
console.error(error);
continue;
}
request.end(balance);
}
})();
}
})();
(async () => {
await crud.thinky.dbReady();
httpServer.listen(ASYNGULAR_PORT);
})();
if (ASYNGULAR_LOG_LEVEL >= 1) {
(async () => {
for await (let {error} of agServer.listener('error')) {
console.error(error);
}
})();
}
if (ASYNGULAR_LOG_LEVEL >= 2) {
console.log(
` ${colorText('[Active]', 32)} Asyngular worker with PID ${process.pid} is listening on port ${ASYNGULAR_PORT}`
);
(async () => {
for await (let {warning} of agServer.listener('warning')) {
console.warn(warning);
}
})();
}
function colorText(message, color) {
if (color) {
return `\x1b[${color}m${message}\x1b[0m`;
}
return message;
}
if (AGC_STATE_SERVER_HOST) {
// Setup broker client to connect to the Asyngular cluster (AGC).
let agcClient = agcBrokerClient.attach(agServer.brokerEngine, {
instanceId: AGC_INSTANCE_ID,
instancePort: ASYNGULAR_PORT,
instanceIp: AGC_INSTANCE_IP,
instanceIpFamily: AGC_INSTANCE_IP_FAMILY,
pubSubBatchDuration: AGC_PUB_SUB_BATCH_DURATION,
stateServerHost: AGC_STATE_SERVER_HOST,
stateServerPort: AGC_STATE_SERVER_PORT,
mappingEngine: AGC_MAPPING_ENGINE,
clientPoolSize: AGC_CLIENT_POOL_SIZE,
authKey: AGC_AUTH_KEY,
stateServerConnectTimeout: AGC_STATE_SERVER_CONNECT_TIMEOUT,
stateServerAckTimeout: AGC_STATE_SERVER_ACK_TIMEOUT,
stateServerReconnectRandomness: AGC_STATE_SERVER_RECONNECT_RANDOMNESS,
brokerRetryDelay: AGC_BROKER_RETRY_DELAY
});
(async () => {
for await (let event of agcClient.listener('updateWorkers')) {
let sortedWorkerURIs = event.workerURIs.sort();
let workerCount = sortedWorkerURIs.length;
let currentWorkerIndex = event.workerURIs.indexOf(event.sourceWorkerURI);
shardInfo.shardIndex = currentWorkerIndex;
shardInfo.shardCount = workerCount;
}
})();
if (ASYNGULAR_LOG_LEVEL >= 1) {
(async () => {
for await (let {error} of agcClient.listener('error')) {
error.name = 'AGCError';
console.error(error);
}
})();
}
} else {
shardInfo.shardIndex = 0;
shardInfo.shardCount = 1;
}
process.on('uncaughtException', (error) => {
console.error('[uncaughtException]', error);
process.exit(1);
});
process.on('unhandledRejection', (error) => {
console.error('[unhandledRejection]', error);
process.exit(1);
});