This repository was archived by the owner on Sep 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.ts
364 lines (309 loc) · 8.15 KB
/
loader.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
/**
* This file is initializer which prepare all application stuff and create new instance of Application
*
* This file is part of Jumbo framework for Node.js
* Written by Roman Jámbor ©
*/
import * as $cluster from "cluster"
import * as $path from "path";
import * as $fs from "fs";
import * as ObjectUtils from "jumbo-core/utils/object";
import {dirname} from "jumbo-core/utils/path";
// Start timer measuring application load time
if ($cluster.isMaster)
{
console.time("Application Master load-time: ");
}
else
{
console.time("Application Worker " + $cluster.worker.id + " load-time: ");
}
const DIRNAME = dirname(module);
/**
* Base project directory
* @type {string}
*/
const PROJECT_DIR = $path.dirname(require.main.filename);//.toLowerCase();
/**
* Number of milisecond in day
* @type {number}
*/
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Declaration of global object/namespace Jumbo which represents
* base framework object for accessing framework data
*/
const JumboGlobalNamespace = {
/** @type {ApplicationConfig} */
config: {},
CONFIG_PATH: $path.join(PROJECT_DIR, "config.js"),
CFG_PATH: $path.join(DIRNAME, "config.js"),
BASE_DIR: PROJECT_DIR,
CORE_DIR: DIRNAME,
PUBLIC_DIR: $path.join(PROJECT_DIR, "public"),
APP_DIR: $path.join(PROJECT_DIR, "app"),
SUB_APP_DIR: $path.join(PROJECT_DIR, "app", "sub-apps"),
ERR_DIR: $path.join(PROJECT_DIR, "data", "errors"),
LOG_DIR: $path.join(PROJECT_DIR, "data", "logs"),
UPLOAD_DIR: $path.resolve(PROJECT_DIR, "data", "uploads"),
CACHE_DIR: $path.resolve(PROJECT_DIR, "temp", "cache"),
SESSION_DIR: $path.resolve(PROJECT_DIR, "temp", "sessions"),
};
(<any>global).Jumbo = JumboGlobalNamespace;
class Loader
{
//region Fields
/**
* Is true if something went wrong. Application will be closed when loader finish.
* @type {boolean}
*/
private exitStatus: boolean = false;
/**
* Config; Filled from checkConfig()
* @type {ApplicationConfig}
*/
private config: any;
//endregion
//region Static methods
/**
* Initialize application
*/
public static initializeApplication()
{
let loader = new Loader();
loader.initialize();
if ($cluster.isMaster)
{
loader.deleteCachedFiles();
loader.deleteOldSessions();
}
loader.initAutoloader();
const Application = require("jumbo-core/application/Application").Application;
// Create instance of application
let app = Application.instance;
(<any>global).Application = app;
// // Export application
// module.exports = {
// /**
// * @type {Jumbo.Application.Application}
// */
// application: app,
//
// /**
// * @type {JumboNamespace}
// */
// Jumbo: Jumbo
// };
// Additional global objects
(<any>global).nameof = function nameof(obj) {
return Object.keys(obj)[0];
};
}
//endregion
//region Methods
/**
* Delete cached filed
*/
public deleteCachedFiles()
{
$fs.readdir(JumboGlobalNamespace.CACHE_DIR, (err, files) => {
let i = 0;
for (let fileName of files)
{
if (fileName.slice(-9) == ".tplcache")
{
let file = $path.join(JumboGlobalNamespace.CACHE_DIR, fileName);
// remove file
$fs.unlink(file, () => { });
i++;
}
}
Jumbo.Logging.Log.line(`${i} cached template files deleted`);
});
}
/**
* Delete old sessions
*/
public deleteOldSessions()
{
$fs.readdir(JumboGlobalNamespace.SESSION_DIR, (err, files) => {
let sessionLimitTime = (new Date().getTime() - Jumbo.config.session.sessionLifetime * DAY_MS);
for (let fileName of files)
{
if (fileName.slice(-8) == ".session")
{
let file = $path.join(JumboGlobalNamespace.SESSION_DIR, fileName);
let stats = $fs.statSync(file);
if (stats.birthtime.getTime() < sessionLimitTime)
{
// remove session file
// noinspection JSUnusedLocalSymbols
$fs.unlink(file, (err) => {});
Jumbo.Logging.Log.line(`Deleting session file '${fileName}'`);
}
}
}
});
}
/**
* Initialize autoloader
*/
public initAutoloader()
{
// Load the Autoloader
const autoloader = require("jumbo-core/autoloader/autoloader");
/**
* @namespace App
* @global
*/
(<any>global).App = autoloader.App;
// Add items from core directory to namespace/object Jumbo
let objs = Object.getOwnPropertyNames(autoloader.Core);
let c = objs.length;
for (let p = 0; p < c; p++)
{
JumboGlobalNamespace[objs[p]] = autoloader.Core[objs[p]];
}
}
/**
* Provede inicializaci
*/
public initialize()
{
this.checkConfig();
this.checkAppStructure();
if (this.exitStatus)
{
process.exit(0);
}
}
//endregion
//region Private methods
/**
* Check that all framework directories exists
*/
private checkAppStructure()
{
[
$path.join(PROJECT_DIR, "app"),
$path.join(PROJECT_DIR, "app", "controllers"),
$path.join(PROJECT_DIR, "app", "sub-apps"),
$path.join(PROJECT_DIR, "app", "services"),
$path.join(PROJECT_DIR, "app", "facades"),
$path.join(PROJECT_DIR, "app", "models"),
$path.join(PROJECT_DIR, "app", "templates"),
// $path.join(PROJECT_DIR, "app", "tests"),
$path.join(PROJECT_DIR, "data"),
$path.join(PROJECT_DIR, "data", "uploads"),
$path.join(PROJECT_DIR, "data", "logs"),
$path.join(PROJECT_DIR, "data", "errors"),
$path.join(PROJECT_DIR, "public"),
// $path.join(base, "public", "styles"),
// $path.join(base, "public", "scripts"),
// $path.join(base, "public", "images"),
$path.join(PROJECT_DIR, "temp"),
$path.join(PROJECT_DIR, "temp", "cache"),
$path.join(PROJECT_DIR, "temp", "sessions")
].forEach(function (p) {
try
{
let stat = $fs.lstatSync(p);
if (!stat.isDirectory())
{
console.error(`[ERROR] Structure directory '${p}' not found.`);
this.exitStatus = true;
}
}
catch (ex)
{
this.exitStatus = true;
}
});
}
private isInConfig(section, ...properties)
{
let sect = this.config[section];
let succ = true;
if (sect === undefined)
{
console.error(`[ERROR] Config file is corrupted. Section '${section}' is missing.`);
succ = false;
}
else
{
for (let prop in properties)
{
prop = properties[prop];
if (!sect.hasOwnProperty(prop))
{
console.error(`[ERROR] Config file is corrupted. Property '${prop}' is missing in section '${section}'.`);
succ = false;
}
}
}
return succ;
}
/**
* Load config, check it and prepare object with readonly properties and put it into global Jumbo
*/
private checkConfigSections()
{
if (
this.isInConfig("protocol", "protocol", "privateKey", "certificate", "pfx", "passphrase")
&& this.isInConfig("clustering", "numberOfWorkers")
&& this.isInConfig("cache", "enabled", "memoryCacheSizeLimit")
&& this.isInConfig("session", "sessionsCookieName", "sessionLifetime", "memorySizeLimit", "justInMemory")
&& this.isInConfig("log", "enabled", "level")
// && this.isInConfig("doTestsAfterRun")
&& this.isInConfig("maxRequestPerSecond")
&& this.isInConfig("maxPostDataSize")
&& this.isInConfig("deployment")
&& this.isInConfig("debugMode")
&& this.isInConfig("DOSPrevention", "enabled", "blockTime", "maxRequestPerIP")
&& this.isInConfig("globalization", "enabled")
)
{
JumboGlobalNamespace.config = ObjectUtils.freeze(this.config, 2);
}
else
{
// ...
}
}
/**
* Check that config exists
*/
private checkConfig()
{
if (!$fs.lstatSync(Jumbo.CONFIG_PATH).isFile())
{
this.exitStatus = true;
console.error("Application config '" + Jumbo.CONFIG_PATH + "' not found.");
}
try
{
// Default config values
let defaultConfig = require("jumbo-core/default-config.js");
// Extend default config with app config
this.config = ObjectUtils.assign(defaultConfig, require(Jumbo.CONFIG_PATH));
this.checkConfigSections();
}
catch (ex)
{
this.exitStatus = true;
console.error("Config JSON invalid.", ex);
}
}
//endregion
}
if ($cluster.isMaster)
{
console.log("*******************************");
console.log("**");
console.log("** JumboJS, booting up...");
console.log("**");
console.log("*******************************");
}
Loader.initializeApplication();
import {Application} from "./application/Application";
export const application: Application = (<any>global).Application;