-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
720 lines (655 loc) · 26.9 KB
/
index.ts
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
import atob from 'atob';
import { URL } from 'url';
import express from 'express';
import router from './imports/router/index.js';
import generateJwtServer from './imports/router/jwt.js';
import generateGuestServer from './imports/router/guest.js';
import generatePackagerServer from './imports/router/packager.js';
import axios from 'axios';
import http from 'http';
import { createProxyMiddleware, fixRequestBody, responseInterceptor } from 'http-proxy-middleware';
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const expressPlayground = require('graphql-playground-middleware-express').default;
import moesif from 'moesif-nodejs';
import Debug from 'debug';
import waitOn from 'wait-on';
import { generateApolloClient } from '@deep-foundation/hasura/client.js';
import { DeepClient } from './imports/client.js';
import gql from 'graphql-tag';
import { containerController, DOCKER, getJwt } from './imports/router/links.js';
import { MinilinkCollection, MinilinksGeneratorOptionsDefault } from './imports/minilinks.js';
import _ from 'lodash';
import Cors from 'cors';
import cookieParser from 'cookie-parser';
import async from 'async';
import { serializeError } from 'serialize-error';
const DEEPLINKS_HASURA_PATH = process.env.DEEPLINKS_HASURA_PATH || 'localhost:8080';
const DEEPLINKS_HASURA_STORAGE_URL = process.env.DEEPLINKS_HASURA_STORAGE_URL || 'http://localhost:8000';
const DEEPLINKS_HASURA_SSL = process.env.DEEPLINKS_HASURA_SSL || 0;
const DEEPLINKS_HASURA_SECRET = process.env.DEEPLINKS_HASURA_SECRET || 'myadminsecretkey';
const MOESIF_TOKEN = process.env.MOESIF_TOKEN || '';
const DEEPLINKS_PUBLIC_URL = process.env.DEEPLINKS_PUBLIC_URL || '';
const PORT = process.env.PORT || 3006;
const debug = Debug('deeplinks');
const log = debug.extend('log');
const error = debug.extend('error');
// Force enable this file errors output
export const delay = (time) => new Promise(res => setTimeout(() => res(null), time));
const makeDeepClient = (token: string) => {
return new DeepClient({
apolloClient: generateApolloClient({
path: `${process.env.DEEPLINKS_HASURA_PATH}/v1/graphql`,
ssl: !!+process.env.DEEPLINKS_HASURA_SSL,
token
}),
});
}
const app = express();
app.use(cookieParser());
const httpServer = http.createServer(app);
const cors = Cors({ origin: '*' });
app.use(cors);
app.get('/gql', expressPlayground({
tabs: [{
endpoint: `${DEEPLINKS_PUBLIC_URL}/gql`,
query: `query MyQuery {
links(limit: 1) {
id
}
}`,
headers: {
Authorization: 'Bearer TOKEN',
},
}],
}));
app.use('/gql', createProxyMiddleware((pathname, req) => {
return !!pathname.match(`^/gql`);
}, {
target: `http${DEEPLINKS_HASURA_SSL === '1' ? 's' : ''}://${DEEPLINKS_HASURA_PATH}`,
changeOrigin: true,
ws: true,
logLevel: 'debug',
pathRewrite: {
"/gql": "/v1/graphql",
},
}));
// const getQueryStringParam = (req, paramName) => {
// // protocol and hostname here are mean nothing, these are only required to create URL
// const urlString = `${req.protocol}://${req.hostname}${req.url}`;
// console.log('getQueryStringParam', 'urlString', urlString);
// const url = new URL(urlString);
// console.log('getQueryStringParam', 'url', url);
// console.log('getQueryStringParam', 'url.searchParams', url.searchParams);
// const paramValue = url.searchParams.get(paramName);
// console.log('getQueryStringParam', paramName, paramValue);
// return paramValue;
// }
app.get(['/file'], createProxyMiddleware((pathname, req) => {
return !!pathname.match(`^/file`);
}, {
target: DEEPLINKS_HASURA_STORAGE_URL,
changeOrigin: true,
logLevel: 'debug',
pathRewrite: async (path, req) => {
console.log('/file get proxy', 'path', path);
console.log('/file get proxy', 'req.baseUrl', req.baseUrl);
console.log('/file get proxy', 'req.originalUrl', req.originalUrl);
console.log('/file get proxy', 'req.protocol', req.protocol);
console.log('/file get proxy', 'req.hostname', req.hostname);
console.log('/file get proxy', 'req.url', req.url);
console.log('/file get proxy', 'req.query.linkId', req.query.linkId)
console.log('/file get proxy', 'req.query.token', req.query.token)
req.params
const headers = req.headers;
console.log('/file get proxy', 'headers', headers);
const cookies = req.cookies;
console.log('/file get proxy', 'cookies', JSON.stringify(cookies, null, 2));
let token = '';
let authorizationHeader = headers['authorization'];
if (authorizationHeader) {
token = authorizationHeader.split(' ')[1];
console.log('/file get proxy', 'header token', token);
} else {
const tokenCookie = cookies?.['dc-dg-token'];
if (tokenCookie) {
token = JSON.parse(tokenCookie)?.value;
console.log('/file get proxy', 'cookie token', token);
console.log('/file get proxy', 'cookie token is set as header token');
} else {
if (req.query.token) token = req.query.token as string;
}
}
if (token) {
req.headers.authorization = `Bearer ${token}`;
}
console.log('/file get proxy', 'result token', token);
const deep = makeDeepClient(token);
const linkId = req.query.linkId;
const result = await deep.apolloClient.query({
query: gql`{
files(where: {link_id: {_eq: ${linkId}}}) {
id
}
}`
})
// console.log('/file get proxy', 'result', result)
const fileId = result?.data?.files?.[0]?.id;
console.log('/file get proxy', 'fileId', fileId)
if (fileId) {
return `/v1/files/${fileId}`;
} else {
return `/v1/files/00000000-0000-0000-0000-000000000000`; // This should generate 404 error
}
}
}));
app.post('/file', async (req, res, next) => {
console.log('/file post proxy','DEEPLINKS_HASURA_STORAGE_URL', DEEPLINKS_HASURA_STORAGE_URL);
// canObject
const headers = req.headers;
console.log('/file post proxy', 'headers', JSON.stringify(headers, null, 2));
const cookies = req.cookies;
console.log('/file post proxy', 'cookies', JSON.stringify(cookies, null, 2));
let userId;
let linkId = +(headers['linkId'] || headers['linkid']) || +req.query?.linkId;
console.log('/file post proxy', 'req.query.linkId', req.query.linkId)
console.log('/file post proxy', 'req.query.token', req.query.token)
if (headers.authorization) {
try {
const claims = atob(`${headers['authorization'] ? headers['authorization'] : headers['Authorization']}`.split(' ')[1].split('.')[1]);
userId = +(JSON.parse(claims)['https://hasura.io/jwt/claims']['x-hasura-user-id']);
console.log('/file post proxy','linkId',linkId);
} catch (e) {
const serializedError = serializeError(e);
console.log('/file post proxy','error: ', JSON.stringify(serializedError, null, 2));
}
} else if (req.query.token) {
userId = +(await deep.jwt({ token: req.query.token as string })).linkId
}
if (!userId) res.status(403).send('!user (req.query.token || headers.authorization)');
const canResult = await deep.can(linkId, userId, deep.idLocal('@deep-foundation/core', 'AllowUpdate')) || await deep.can(null, userId, deep.idLocal('@deep-foundation/core', 'AllowAdmin'));
console.log('/file post proxy','can', await deep.can(linkId, userId, deep.idLocal('@deep-foundation/core', 'AllowUpdate')), 'isAdmin', await deep.can(null, userId, deep.idLocal('@deep-foundation/core', 'AllowAdmin')));
console.log('/file post proxy','userId', userId, typeof(userId));
console.log('/file post proxy','canResult', canResult);
if (!canResult) return res.status(403).send(`You cant update link ##${linkId} as user ##${userId}, and user ##${userId} is not admin.`);
//insert file
await createProxyMiddleware((pathname, req) => {
return !!pathname.match(`^/file`);
}, {
target: DEEPLINKS_HASURA_STORAGE_URL,
selfHandleResponse: true,
logLevel: 'debug',
onError: (err, req, res, target) => {
console.log('/file post proxy','onError', err);
res.writeHead(500, {
'Content-Type': 'text/plain',
});
res.end('Something went wrong. And we are reporting a custom error message.');
},
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
console.log('/file post proxy','onProxyRes');
//update linkId
const response = responseBuffer.toString('utf8'); // convert buffer to string
console.log('/file post proxy',`RESPONSE ${response}`);
let files;
try {
files = JSON.parse(response);
console.log('/file post proxy','files', files);
if (!files) return response;
const UPDATE_FILE_LINKID = gql`mutation UPDATE_FILE_LINKID($linkId: bigint, $fileid: uuid, $uploadedByLinkId: bigint) {
updateFiles(where: {id: {_eq: $fileid}}, _set: {link_id: $linkId, uploadedByLinkId: $uploadedByLinkId }){
returning {
id
link_id
uploadedByLinkId
}
}
}`;
console.log('/file post proxy','files[0].id', files.id);
const updated = await client.mutate({
mutation: UPDATE_FILE_LINKID,
variables: {
fileid: files.id,
linkId: linkId,
uploadedByLinkId: userId
},
});
console.log('/file post proxy','linkid',linkId)
console.log('/file post proxy','data',updated?.data?.updateFiles?.returning);
} catch (e) {
const serializedError = serializeError(e);
console.log('/file post proxy','try error: ', JSON.stringify(serializedError, null, 2));
if (files[0]?.id){
await client.mutate({
mutation: gql`mutation DELETE_FILE($fileid: uuid) { deleteFiles(where: {id: {_eq: $fileid}}){ returning { id } } }`,
variables: {
fileid: files.id,
},
});
return JSON.stringify({error: 'one link - one file'});
}
}
return response;
}),
changeOrigin: true,
pathRewrite: {
"/file": "/v1/files",
},
})(req,res,next);
});
// hasura-admin
app.use(['/v1','/v1alpha1','/v2','/console'], createProxyMiddleware({
target: `http${DEEPLINKS_HASURA_SSL === '1' ? 's' : ''}://${DEEPLINKS_HASURA_PATH}`,
changeOrigin: true,
ws: true,
logLevel: 'debug',
}));
// hasura-admin
if (MOESIF_TOKEN) {
const moesifMiddleware = moesif({applicationId: MOESIF_TOKEN});
app.use(moesifMiddleware);
moesifMiddleware.startCaptureOutgoing();
}
app.use(express.json());
app.use('/', router);
const start = async () => {
const jwtServer = generateJwtServer(httpServer);
const guestServer = generateGuestServer(httpServer);
const packagerServer = generatePackagerServer(httpServer);
await jwtServer.start();
await guestServer.start();
await packagerServer.start();
jwtServer.applyMiddleware({ path: '/api/jwt', app });
guestServer.applyMiddleware({ path: '/api/guest', app });
packagerServer.applyMiddleware({ path: '/api/packager', app });
await new Promise<void>(resolve => httpServer.listen({ port: process.env.PORT }, resolve));
log(`Hello bugfixers! Listening ${process.env.PORT} port`);
try {
await waitOn({ resources: [`http${DEEPLINKS_HASURA_SSL === '1' ? 's' : ''}-get://${DEEPLINKS_HASURA_PATH}/console`] });
await axios({
method: 'post',
url: `http${DEEPLINKS_HASURA_SSL === '1' ? 's' : ''}://${DEEPLINKS_HASURA_PATH}/v1/metadata`,
headers: { 'x-hasura-admin-secret': DEEPLINKS_HASURA_SECRET, 'Content-Type': 'application/json'},
data: { type: 'reload_metadata', args: {}}
}).then(() => {
log('hasura metadata reloaded');
}, () => {
error('hasura metadata broken');
});
} catch (e) {
const serializedError = serializeError(e);
error(JSON.stringify(serializedError, null, 2));
}
}
start();
const client = generateApolloClient({
path: `${process.env.DEEPLINKS_HASURA_PATH}/v1/graphql`,
ssl: !!+process.env.DEEPLINKS_HASURA_SSL,
secret: process.env.DEEPLINKS_HASURA_SECRET,
});
const deep = new DeepClient({
apolloClient: client,
})
const routesDebug = Debug('deeplinks').extend('eh').extend('routes');
const routesDebugLog = routesDebug.extend('log');
const routesDebugError = routesDebug.extend('error');
let currentServers = {};
let currentPorts = {};
let busy = false;
let portTypeId = 0;
// const ml = new MinilinkCollection(MinilinksGeneratorOptionsDefault);
// const addedListener = (nl, recursive = true, history = {}) => {
// if (nl.type_id == portTypeId) {
// // TODO: Start server
// routesDebugLog('server should be started at port', nl.value);
// } else {
// // TODO: Get list of servers affected by this change and restart them
// routesDebugLog('impossible');
// }
// };
// const updatedListener = (ol, nl, recursive = true, history = {}) => {
// if (ol.type_id == portTypeId && nl.type_id == portTypeId) {
// // TODO: Restart server
// routesDebugLog('server should be restarted at port', nl.value);
// } else {
// // TODO: Get list of servers affected by this change and restart them
// routesDebugLog('impossible');
// }
// };
// const removedListener = (ol, recursive = true, history = {}) => {
// if (ol.type_id == portTypeId) {
// // TODO: Stop server
// routesDebugLog('server should be stopped at port', ol.value);
// } else {
// // TODO: Get list of servers affected by this change and restart them
// routesDebugLog('impossible');
// }
// };
// ml.emitter.on('added', addedListener);
// ml.emitter.on('updated', updatedListener);
// ml.emitter.on('removed', removedListener);
const toJSON = (data) => JSON.stringify(data, Object.getOwnPropertyNames(data), 2);
let mainPort;
const handleRoutes = async () => {
if (busy)
return;
busy = true;
// clean up old servers
// for (const key in currentServers) {
// if (Object.prototype.hasOwnProperty.call(currentServers, key)) {
// const element = currentServers[key];
// element.close();
// }
// }
// currentServers = {};
try {
const portTypeId = deep.idLocal('@deep-foundation/core', 'Port');
const handleRouteTypeId = deep.idLocal('@deep-foundation/core', 'HandleRoute');
const routerStringUseTypeId = deep.idLocal('@deep-foundation/core', 'RouterStringUse');
const routerListeningTypeId = deep.idLocal('@deep-foundation/core', 'RouterListening');
try {
if (!mainPort) mainPort = await deep.id('@deep-foundation/main-port', 'port');
} catch (error) {}
const routesResult = await client.query({
query: gql`
query {
ports: links(where: {
type_id: { _eq: "${portTypeId}" }
}) {
id
port: value
routerListening: in(where: {
type_id: { _eq: "${routerListeningTypeId}" }
}) {
id
router: from {
id
routerStringUse: in(where: {
type_id: { _eq: "${routerStringUseTypeId}" }
}) {
id
routeString: value
route: from {
id
handleRoute: out(where: {
type_id: { _eq: "${handleRouteTypeId}" }
}) {
id
handler: to {
id
supports: from {
id
isolation: from {
id
image: value
}
}
file: to {
id
code: value
}
}
}
}
}
}
}
}
}
`, variables: {} });
const portsResult = routesResult.data.ports;
routesDebugLog('portsResult', JSON.stringify(portsResult, null, 2));
const ports = {};
for (const port of portsResult) {
const portValue = port?.port?.value;
ports[portValue] = port;
}
routesDebugLog('ports', JSON.stringify(ports, null, 2));
const updatedOrAddedPorts = [];
for (const key in currentPorts) {
if (currentPorts.hasOwnProperty(key)) {
if (ports.hasOwnProperty(key)) {
if(!_.isEqual(currentPorts[key], ports[key])) {
currentPorts[key] = ports[key];
updatedOrAddedPorts.push(ports[key]);
} else {
// do nothing
}
} else {
if (currentServers.hasOwnProperty(key))
{
const element = currentServers[key];
element.close();
delete currentServers[key];
}
delete currentPorts[key];
}
}
}
for (const key in ports) {
if (ports.hasOwnProperty(key)) {
if (!currentPorts.hasOwnProperty(key)) {
currentPorts[key] = ports[key];
updatedOrAddedPorts.push(ports[key]);
}
}
}
routesDebugLog('updatedOrAddedPorts', JSON.stringify(updatedOrAddedPorts, null, 2));
routesDebugLog('currentPorts', JSON.stringify(currentPorts, null, 2));
// const mlRoutesResult = await client.query({
// query: gql`
// {
// ports: links(where: {
// _or: [
// {type_id: {_eq: "${portTypeId}"}},
// {_by_item: {path_item: {type_id: {_eq: "${portTypeId}"}}}}
// ]
// }) {
// id
// type_id
// from_id
// to_id
// value
// }
// }
// `, variables: {} });
// const mlPorts = mlRoutesResult.data.ports;
// routesDebugLog('mlPorts', JSON.stringify(mlPorts, null, 2));
// ml.apply(mlPorts);
// routesDebugLog('ml', toJSON(ml));
// routesDebugLog('ml.byType', toJSON(ml.byType));
// get all image values
const imageContainers = {};
updatedOrAddedPorts.forEach(port => {
port.routerListening.forEach(routerListening => {
routerListening?.router?.routerStringUse.forEach(routerStringUse => {
routerStringUse?.route?.handleRoute.forEach(handleRoute => {
imageContainers[handleRoute?.handler?.supports?.isolation?.image?.value] = {};
});
});
});
});
const imageList = Object.keys(imageContainers);
routesDebugLog('imageList', imageList);
// prepare containers
for (const image of imageList) {
routesDebugLog(`preparing container ${image}`);
imageContainers[image] = await containerController.newContainer({
handler: image,
forceRestart: true,
publish: +DOCKER ? false : true,
});
}
// // for each port
// for (const port of ml.byType[portTypeId] ?? []) {
// routesDebugLog('port', toJSON(port));
// const routerListeningLinks = port.in.filter(l => l.type_id == routerListeningTypeId);
// routesDebugLog('routerListeningLinks', toJSON(routerListeningLinks));
// if (routerListeningLinks.length > 0) {
// const portValue = port?.value?.value;
// routesDebugLog('portValue', portValue);
// // routesDebugLog(`listening on port ${portValue}`);
// // for each router
// for (const routerListening of routerListeningLinks) {
// // routesDebugLog('routerListening', toJSON(routerListening));
// const router = routerListening.from;
// routesDebugLog('router', toJSON(router));
// const routerStringUseLinks = router.in.filter(l => l.type_id == routerStringUseTypeId);
// // for each routerStringUse
// for (const routerStringUse of routerStringUseLinks) {
// const routeString = routerStringUse?.value?.value;
// routesDebugLog(`route string ${routeString}`);
// const route = routerStringUse?.from;
// const handleRouteLinks = route.out.filter(l => l.type_id == handleRouteTypeId);
// // for each handleRoute
// for (const handleRoute of handleRouteLinks) {
// const handler = handleRoute?.to;
// routesDebugLog(`handler`, handler);
// const handlerId = handler?.id;
// routesDebugLog(`handler id ${handlerId}`);
// const jwt = await getJwt(handlerId, routesDebugLog);
// routesDebugLog(`jwt ${jwt}`);
// // get container
// const supports = ml.byId[handler?.from_id];
// routesDebugLog(`supports`, supports);
// const isolation = ml.byId[supports?.from_id];
// routesDebugLog(`isolation`, isolation);
// const image = isolation?.image?.value;
// routesDebugLog(`image`, image);
// const container = imageContainers[image];
// routesDebugLog(`container`, JSON.stringify(container, null, 2));
// const file = ml.byId[handler?.to_id];
// const code = file?.value?.value;
// routesDebugLog(`code ${code}`);
// }
// }
// }
// }
// }
// for each port
for (const port of updatedOrAddedPorts) {
const portValue = port?.port?.value || PORT;
if (currentServers.hasOwnProperty(portValue)) {
currentServers[portValue].close();
}
if (port.routerListening.length > 0) {
// listen on port
routesDebugLog(`listening on port ${portValue}`);
// start express server
let portServer;
if (+portValue === +PORT || port?.id === mainPort) {
portServer = nestedApp;
} else {
portServer = express();
currentServers[portValue] = http.createServer({ maxHeaderSize: 10*1024*1024*1024 }, portServer).listen(portValue);
}
// for each router
for (const routerListening of port.routerListening) {
const router = routerListening?.router;
// for each routerStringUse
for (const routerStringUse of router.routerStringUse) {
const routeString = routerStringUse?.routeString?.value;
routesDebugLog(`route string ${routeString}`);
const route = routerStringUse?.route;
// for each handleRoute
for (const handleRoute of route.handleRoute) {
const handler = handleRoute?.handler;
const handlerId = handler?.id;
routesDebugLog(`handler id ${handlerId}`);
const { token: jwt } = await getJwt(handlerId, routesDebugLog);
routesDebugLog(`jwt ${jwt}`);
// get container
const image = handler?.supports?.isolation?.image?.value;
routesDebugLog(`image`, image);
const container = imageContainers[image];
routesDebugLog(`container`, JSON.stringify(container, null, 2));
const { data: [_handler] = [] } = await deep.select({ handler_id: handlerId }, { table: 'handlers', returning: 'dist { value }' });
const code = _handler?.dist?.value?.value || handler?.file?.code?.value;
routesDebugLog(`code ${code}`);
routesDebugLog('container', container);
const filter = function (pathname, req) {
routesDebugLog('pathname', pathname, req.method, req.originalUrl, !!pathname.match(`^${routeString}`));
return !!pathname.match(`^${routeString}`);
};
// proxy to container using its host and port
const proxy = createProxyMiddleware(filter, {
target: `http://${container.host}:${container.port}`,
changeOrigin: true,
ws: true,
pathRewrite: {
[routeString]: "/http-call",
},
logLevel: 'debug',
onProxyReq: (proxyReq, req, res) => {
routesDebugLog('onProxyReq', req.baseUrl); // selfHandleResponse
routesDebugLog('deeplinks request')
routesDebugLog('req.method', req.method);
routesDebugLog('req.body', req.body);
proxyReq.setHeader('deep-call-options', encodeURI(JSON.stringify({
jwt,
code,
data: { deeplinksUrl: process.env?.DEEPLINKS_PUBLIC_URL, routeString, path: req.path, originalUrl: req.originalUrl, baseUrl: req.baseUrl, handlerId, routeId: route.id, router: router.id },
})));
return fixRequestBody(proxyReq, req);
},
onProxyRes: (proxyRes, req, res) => {
routesDebugLog('onProxyRes', req.baseUrl); // selfHandleResponse
// var body = "";
proxyRes.on('data', async function(data) {
try {
data = data.toString('utf-8');
// body += data;
routesDebugLog('data', data);
// if JSON
if (data.startsWith('{')) {
data = JSON.parse(data);
// log rejected
if (data.hasOwnProperty('rejected')) {
routesDebugLog('rejected', data.rejected);
// HandlingError type id
const handlingErrorTypeId = deep.idLocal('@deep-foundation/core', 'HandlingError');
routesDebugLog('handlingErrorTypeId', handlingErrorTypeId);
// const insertResult = await deep.insert({
// type_id: handlingErrorTypeId,
// object: { data: { value: data.rejected } },
// out: { data: [
// {
// type_id: deep.idLocal('@deep-foundation/core', 'HandlingErrorReason'),
// to_id: route.id
// },
// {
// type_id: deep.idLocal('@deep-foundation/core', 'HandlingErrorReason'),
// to_id: handleRoute.id
// }
// ]},
// }, {
// name: 'INSERT_HANDLING_ERROR',
// }) as any;
}
}
} catch (e) {
const serializedError = serializeError(e);
routesDebugError('deeplinks response error', JSON.stringify(serializedError, null, 2))
}
});
// routesDebugLog('body', body);
}
});
portServer.use(routeString, proxy);
}
}
}
}
}
} catch (e) {
const serializedError = serializeError(e);
routesDebugLog(JSON.stringify(serializedError, null, 2));
}
busy = false;
};
let nestedApp = express.Router();
app.use(nestedApp);
const startRouteHandling = async () => {
setInterval(handleRoutes, 5000);
};
startRouteHandling();