forked from metarhia/impress
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimpress.js
More file actions
143 lines (125 loc) · 4.25 KB
/
impress.js
File metadata and controls
143 lines (125 loc) · 4.25 KB
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
'use strict';
process.title = 'impress';
const { Worker } = require('worker_threads');
const path = require('path');
const { Config } = require('metaconfiguration');
const metavm = require('metavm');
const metautil = require('metautil');
const { loadSchema } = require('metaschema');
const { Logger } = require('metalog');
const CONFIG_SECTIONS = ['log', 'scale', 'server', 'sessions'];
const PATH = process.cwd();
const CFG_PATH = path.join(PATH, 'application/config');
const LOG_PATH = path.join(PATH, 'log');
const CTRL_C = 3;
(async () => {
const logOpt = { path: LOG_PATH, workerId: 0, toFile: [] };
const { console } = await new Logger(logOpt);
const exit = (message = 'Can not start server') => {
console.error(metautil.replace(message, PATH, ''));
process.exit(1);
};
const validateConfig = async (config) => {
const schemaPath = path.join(__dirname, 'schemas/config');
let valid = true;
for (const section of CONFIG_SECTIONS) {
const fileName = path.join(schemaPath, section + '.js');
const schema = await loadSchema(fileName);
const checkResult = schema.check(config[section]);
if (!checkResult.valid) {
for (const err of checkResult.errors) {
console.error(`${err} in application/config/${section}.js`);
}
valid = false;
}
}
if (!valid) exit();
};
const context = metavm.createContext({ process });
const options = { mode: process.env.MODE, context };
const config = await new Config(CFG_PATH, options).catch((err) => {
exit(`Can not read configuration: ${CFG_PATH}\n${err.stack}`);
});
await validateConfig(config);
const { balancer, ports = [], workers = {} } = config.server;
const serversCount = ports.length + (balancer ? 1 : 0);
const schedulerCount = 1;
const schedulerId = serversCount;
const poolSize = workers.pool || 0;
const count = serversCount + schedulerCount + poolSize;
let startTimer = null;
let active = 0;
let starting = 0;
const threads = new Array(count);
const pool = new metautil.Pool({ timeout: workers.wait });
const stop = async () => {
for (const worker of threads) {
worker.postMessage({ type: 'event', name: 'stop' });
}
};
let scheduler = null;
const start = (id) => {
const workerPath = path.join(__dirname, 'lib/worker.js');
const worker = new Worker(workerPath, { trackUnmanagedFds: true });
threads[id] = worker;
if (id === schedulerId) scheduler = worker;
else if (id > schedulerId) pool.add(worker);
worker.on('exit', (code) => {
active--;
if (code !== 0) start(id);
else if (active === 0) process.exit(0);
else if (active < 0 && id === 0) exit();
});
worker.on('online', () => {
if (++starting === count) {
startTimer = setTimeout(() => {
if (active !== count) console.warn('Server initialization timed out');
}, config.server.timeouts.start);
}
});
const ITC = {
event: ({ name }) => {
if (name !== 'started') return;
active++;
if (active === count && startTimer) {
clearTimeout(startTimer);
startTimer = null;
}
},
task: (msg) => {
if (msg.type !== 'task') return;
const transferList = msg.port ? [msg.port] : undefined;
scheduler.postMessage(msg, transferList);
},
invoke: async (msg) => {
const { name, port, exclusive } = msg;
if (name === 'done') {
if (exclusive) pool.release(worker);
return;
}
if (name !== 'request') return;
const promisedThread = exclusive ? pool.capture() : pool.next();
const next = await promisedThread.catch(() => {
port.postMessage({ error: new Error('No thread available') });
return null;
});
if (!next) return;
next.postMessage(msg, [port]);
},
};
worker.on('message', (msg) => {
const handler = ITC[msg.type];
if (handler) handler(msg);
});
};
for (let id = 0; id < count; id++) start(id);
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
process.stdin.on('data', (data) => {
const key = data[0];
if (key === CTRL_C) stop();
});
}
})();