UNPKG

7.03 kBPlain TextView Raw
1import * as fs from 'fs';
2import * as akala from '@akala/core';
3import { join as pathJoin } from 'path';
4import * as debug from 'debug';
5import { router, Request, Response } from './router';
6import * as pac from './package';
7var log = debug('akala:master');
8import { microservice } from './microservice';
9import { updateConfig, getConfig } from './config';
10import { serveStatic } from './master-meta';
11
12var httpPackage: 'http' | 'https' = 'http';
13
14var port = process.env.PORT || '5678';
15
16akala.register('$updateConfig', new Proxy(updateConfig, {
17 get: function (uc, key: string)
18 {
19 return function (config, subKey)
20 {
21 return uc(config, key + '.' + subKey);
22 }
23 }
24}));
25akala.registerFactory('$config', new Proxy(getConfig, {
26 get: function (c, key: string)
27 {
28 return function ()
29 {
30 return c().then(function (config) { return config[key]; });
31 }
32 }
33}));
34
35var lateBoundRoutes = router();
36var preAuthenticatedRouter = router();
37var authenticationRouter = router();
38var app = router();
39akala.register('$preAuthenticationRouter', preAuthenticatedRouter);
40akala.register('$authenticationRouter', authenticationRouter);
41akala.register('$router', lateBoundRoutes);
42var masterRouter = router();
43masterRouter.use(preAuthenticatedRouter.router);
44masterRouter.use(authenticationRouter.router);
45masterRouter.use(lateBoundRoutes.router);
46masterRouter.use(app.router);
47
48var root: string;
49var index: string;
50var privateKey: string;
51var fullchain: string;
52
53var configFile = fs.realpathSync('./config.json');
54fs.exists(configFile, function (exists)
55{
56 var config = exists && require(configFile) || {};
57
58 root = config && config['@akala/server'] && config['@akala/server'].root;
59 index = config && config['@akala/server'] && config['@akala/server'].index;
60 port = config && config['@akala/server'] && config['@akala/server'].port || port;
61 privateKey = config && config['@akala/server'] && config['@akala/server'].privateKey || 'privkey.pem';
62 fullchain = config && config['@akala/server'] && config['@akala/server'].fullchain || 'fullchain.pem';
63 if (fs.existsSync(privateKey) && fs.existsSync(fullchain))
64 httpPackage = 'https';
65
66
67 var dn = config && config['@akala/server'] && config['@akala/server'].dn || 'localhost';
68
69 akala.register('$rootUrl', httpPackage + '://' + dn + ':' + port);
70
71 var sourcesFile = './sources.list';
72 fs.readFile(sourcesFile, 'utf8', function (error, sourcesFileContent)
73 {
74 var sources: string[] = [];
75 var modules: string[] = [];
76 if (error && error.code == 'ENOENT')
77 {
78 var pkg: pac.CoreProperties = require(pathJoin(process.cwd(), './package.json'))
79 var [source, folder] = pkg.name.split('/');
80 microservice(pkg.name, source, [source], config);
81 modules.push(pkg.name)
82 }
83 else
84 {
85 sources = JSON.parse(sourcesFileContent);
86 }
87 akala.eachAsync(sources, function (source, i, next)
88 {
89 fs.readdir('node_modules/' + source, function (err, dirModules)
90 {
91 if (err)
92 {
93 console.error(err);
94 return;
95 }
96
97 dirModules.forEach(function (folder)
98 {
99 microservice(source + '/' + folder, source, [source], config);
100 modules.push(source + '/' + folder);
101 });
102
103 next();
104 });
105 }, function (error?)
106 {
107 if (error)
108 {
109 console.error(error);
110 return;
111 }
112
113 akala.register('$$modules', modules);
114
115 log(modules);
116
117 akala.module('bootstrap', ...modules).init([], function ()
118 {
119 log('registering error handler');
120
121 var serveRoot = serveStatic(root, { index: index || undefined })
122 preAuthenticatedRouter.use(serveStatic(root, { index: index || undefined, fallthrough: true }));
123 preAuthenticatedRouter.get('/favicon.ico', serveStatic(root, { index: index || undefined, fallthrough: false }));
124 preAuthenticatedRouter.get('/manifest.json', serveStatic(root, { index: index || undefined, fallthrough: false }));
125 app.get('/@akala/client', function (_req: Request, res: Response)
126 {
127 res.json(modules.map(m => { return { name: m, dep: akala.module(m).dep } }))
128 });
129 app.get('*', function (request, response)
130 {
131 if (request.url.endsWith('.map'))
132 {
133 response.sendStatus(404);
134 }
135 else
136 serveRoot(request, response, function ()
137 {
138 fs.createReadStream(root + '/index.html').pipe(response);
139 });
140 });
141
142 masterRouter.use(function (err, req: Request, res: Response, next)
143 {
144 try
145 {
146 if (err)
147 {
148 console.error('error occurred on ' + req.url);
149
150 console.error(err.stack);
151 res.statusCode = 500;
152 res.write(JSON.stringify(err));
153 res.end();
154 }
155 else
156 res.sendStatus(404);
157 }
158 catch (e)
159 {
160 console.error(e.stack)
161 res.statusCode = 500;
162 res.end();
163 }
164 });
165
166 });
167
168 akala.module('bootstrap').run(['$rootUrl'], function (url)
169 {
170 console.log('server ready and listening on ' + url + '...');
171 })
172
173 akala.module('bootstrap').start();
174 });
175 });
176
177 switch (httpPackage)
178 {
179 case 'http':
180 const http = require('http');
181 var server = http.createServer();
182 break;
183 case 'https':
184 // const http2 = require('http2');
185 // var server = http2.createSecureServer({ allowHTTP1: true, key: fs.readFileSync('priv.pem'), cert: fs.readFileSync('fullchain.pem') });
186 const https = require(httpPackage);
187 var server = https.createServer({ key: fs.readFileSync(privateKey), cert: fs.readFileSync(fullchain) });
188 break;
189 }
190 server.listen(port, dn);
191 akala.register('$server', server);
192 masterRouter.attachTo(server);
193});
194