index.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. const os = require('os');
  2. const throng = require('throng');
  3. const dotenv = require('dotenv');
  4. const express = require('express');
  5. const http = require('http');
  6. const redis = require('redis');
  7. const pg = require('pg');
  8. const log = require('npmlog');
  9. const url = require('url');
  10. const { WebSocketServer } = require('@clusterws/cws');
  11. const uuid = require('uuid');
  12. const fs = require('fs');
  13. const env = process.env.NODE_ENV || 'development';
  14. const alwaysRequireAuth = process.env.WHITELIST_MODE === 'true' || process.env.AUTHORIZED_FETCH === 'true';
  15. dotenv.config({
  16. path: env === 'production' ? '.env.production' : '.env',
  17. });
  18. log.level = process.env.LOG_LEVEL || 'verbose';
  19. const dbUrlToConfig = (dbUrl) => {
  20. if (!dbUrl) {
  21. return {};
  22. }
  23. const params = url.parse(dbUrl, true);
  24. const config = {};
  25. if (params.auth) {
  26. [config.user, config.password] = params.auth.split(':');
  27. }
  28. if (params.hostname) {
  29. config.host = params.hostname;
  30. }
  31. if (params.port) {
  32. config.port = params.port;
  33. }
  34. if (params.pathname) {
  35. config.database = params.pathname.split('/')[1];
  36. }
  37. const ssl = params.query && params.query.ssl;
  38. if (ssl && ssl === 'true' || ssl === '1') {
  39. config.ssl = true;
  40. }
  41. return config;
  42. };
  43. const redisUrlToClient = (defaultConfig, redisUrl) => {
  44. const config = defaultConfig;
  45. if (!redisUrl) {
  46. return redis.createClient(config);
  47. }
  48. if (redisUrl.startsWith('unix://')) {
  49. return redis.createClient(redisUrl.slice(7), config);
  50. }
  51. return redis.createClient(Object.assign(config, {
  52. url: redisUrl,
  53. }));
  54. };
  55. const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  56. const startMaster = () => {
  57. if (!process.env.SOCKET && process.env.PORT && isNaN(+process.env.PORT)) {
  58. log.warn('UNIX domain socket is now supported by using SOCKET. Please migrate from PORT hack.');
  59. }
  60. log.info(`Starting streaming API server master with ${numWorkers} workers`);
  61. };
  62. const startWorker = (workerId) => {
  63. log.info(`Starting worker ${workerId}`);
  64. const pgConfigs = {
  65. development: {
  66. user: process.env.DB_USER || pg.defaults.user,
  67. password: process.env.DB_PASS || pg.defaults.password,
  68. database: process.env.DB_NAME || 'mastodon_development',
  69. host: process.env.DB_HOST || pg.defaults.host,
  70. port: process.env.DB_PORT || pg.defaults.port,
  71. max: 10,
  72. },
  73. production: {
  74. user: process.env.DB_USER || 'mastodon',
  75. password: process.env.DB_PASS || '',
  76. database: process.env.DB_NAME || 'mastodon_production',
  77. host: process.env.DB_HOST || 'localhost',
  78. port: process.env.DB_PORT || 5432,
  79. max: 10,
  80. },
  81. };
  82. if (!!process.env.DB_SSLMODE && process.env.DB_SSLMODE !== 'disable') {
  83. pgConfigs.development.ssl = true;
  84. pgConfigs.production.ssl = true;
  85. }
  86. const app = express();
  87. app.set('trusted proxy', process.env.TRUSTED_PROXY_IP || 'loopback,uniquelocal');
  88. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  89. const server = http.createServer(app);
  90. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  91. const redisParams = {
  92. host: process.env.REDIS_HOST || '127.0.0.1',
  93. port: process.env.REDIS_PORT || 6379,
  94. db: process.env.REDIS_DB || 0,
  95. password: process.env.REDIS_PASSWORD,
  96. };
  97. if (redisNamespace) {
  98. redisParams.namespace = redisNamespace;
  99. }
  100. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  101. const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  102. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  103. const subs = {};
  104. redisSubscribeClient.on('message', (channel, message) => {
  105. const callbacks = subs[channel];
  106. log.silly(`New message on channel ${channel}`);
  107. if (!callbacks) {
  108. return;
  109. }
  110. callbacks.forEach(callback => callback(message));
  111. });
  112. const subscriptionHeartbeat = (channel) => {
  113. const interval = 6*60;
  114. const tellSubscribed = () => {
  115. redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval*3);
  116. };
  117. tellSubscribed();
  118. const heartbeat = setInterval(tellSubscribed, interval*1000);
  119. return () => {
  120. clearInterval(heartbeat);
  121. };
  122. };
  123. const subscribe = (channel, callback) => {
  124. log.silly(`Adding listener for ${channel}`);
  125. subs[channel] = subs[channel] || [];
  126. if (subs[channel].length === 0) {
  127. log.verbose(`Subscribe ${channel}`);
  128. redisSubscribeClient.subscribe(channel);
  129. }
  130. subs[channel].push(callback);
  131. };
  132. const unsubscribe = (channel, callback) => {
  133. log.silly(`Removing listener for ${channel}`);
  134. subs[channel] = subs[channel].filter(item => item !== callback);
  135. if (subs[channel].length === 0) {
  136. log.verbose(`Unsubscribe ${channel}`);
  137. redisSubscribeClient.unsubscribe(channel);
  138. }
  139. };
  140. const allowCrossDomain = (req, res, next) => {
  141. res.header('Access-Control-Allow-Origin', '*');
  142. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  143. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  144. next();
  145. };
  146. const setRequestId = (req, res, next) => {
  147. req.requestId = uuid.v4();
  148. res.header('X-Request-Id', req.requestId);
  149. next();
  150. };
  151. const setRemoteAddress = (req, res, next) => {
  152. req.remoteAddress = req.connection.remoteAddress;
  153. next();
  154. };
  155. const accountFromToken = (token, allowedScopes, req, next) => {
  156. pgPool.connect((err, client, done) => {
  157. if (err) {
  158. next(err);
  159. return;
  160. }
  161. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.chosen_languages, oauth_access_tokens.scopes FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 AND oauth_access_tokens.revoked_at IS NULL LIMIT 1', [token], (err, result) => {
  162. done();
  163. if (err) {
  164. next(err);
  165. return;
  166. }
  167. if (result.rows.length === 0) {
  168. err = new Error('Invalid access token');
  169. err.statusCode = 401;
  170. next(err);
  171. return;
  172. }
  173. const scopes = result.rows[0].scopes.split(' ');
  174. if (allowedScopes.size > 0 && !scopes.some(scope => allowedScopes.includes(scope))) {
  175. err = new Error('Access token does not cover required scopes');
  176. err.statusCode = 401;
  177. next(err);
  178. return;
  179. }
  180. req.accountId = result.rows[0].account_id;
  181. req.chosenLanguages = result.rows[0].chosen_languages;
  182. req.allowNotifications = scopes.some(scope => ['read', 'read:notifications'].includes(scope));
  183. next();
  184. });
  185. });
  186. };
  187. const accountFromRequest = (req, next, required = true, allowedScopes = ['read']) => {
  188. const authorization = req.headers.authorization;
  189. const location = url.parse(req.url, true);
  190. const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
  191. if (!authorization && !accessToken) {
  192. if (required) {
  193. const err = new Error('Missing access token');
  194. err.statusCode = 401;
  195. next(err);
  196. return;
  197. } else {
  198. next();
  199. return;
  200. }
  201. }
  202. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  203. accountFromToken(token, allowedScopes, req, next);
  204. };
  205. const PUBLIC_STREAMS = [
  206. 'public',
  207. 'public:media',
  208. 'public:local',
  209. 'public:local:media',
  210. 'public:remote',
  211. 'public:remote:media',
  212. 'hashtag',
  213. 'hashtag:local',
  214. ];
  215. const wsVerifyClient = (info, cb) => {
  216. const location = url.parse(info.req.url, true);
  217. const authRequired = alwaysRequireAuth || !PUBLIC_STREAMS.some(stream => stream === location.query.stream);
  218. const allowedScopes = [];
  219. if (authRequired) {
  220. allowedScopes.push('read');
  221. if (location.query.stream === 'user:notification') {
  222. allowedScopes.push('read:notifications');
  223. } else {
  224. allowedScopes.push('read:statuses');
  225. }
  226. }
  227. accountFromRequest(info.req, err => {
  228. if (!err) {
  229. cb(true, undefined, undefined);
  230. } else {
  231. log.error(info.req.requestId, err.toString());
  232. cb(false, 401, 'Unauthorized');
  233. }
  234. }, authRequired, allowedScopes);
  235. };
  236. const PUBLIC_ENDPOINTS = [
  237. '/api/v1/streaming/public',
  238. '/api/v1/streaming/public/local',
  239. '/api/v1/streaming/public/remote',
  240. '/api/v1/streaming/hashtag',
  241. '/api/v1/streaming/hashtag/local',
  242. ];
  243. const authenticationMiddleware = (req, res, next) => {
  244. if (req.method === 'OPTIONS') {
  245. next();
  246. return;
  247. }
  248. const authRequired = alwaysRequireAuth || !PUBLIC_ENDPOINTS.some(endpoint => endpoint === req.path);
  249. const allowedScopes = [];
  250. if (authRequired) {
  251. allowedScopes.push('read');
  252. if (req.path === '/api/v1/streaming/user/notification') {
  253. allowedScopes.push('read:notifications');
  254. } else {
  255. allowedScopes.push('read:statuses');
  256. }
  257. }
  258. accountFromRequest(req, next, authRequired, allowedScopes);
  259. };
  260. const errorMiddleware = (err, req, res, {}) => {
  261. log.error(req.requestId, err.toString());
  262. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  263. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  264. };
  265. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  266. const authorizeListAccess = (id, req, next) => {
  267. pgPool.connect((err, client, done) => {
  268. if (err) {
  269. next(false);
  270. return;
  271. }
  272. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [id], (err, result) => {
  273. done();
  274. if (err || result.rows.length === 0 || result.rows[0].account_id !== req.accountId) {
  275. next(false);
  276. return;
  277. }
  278. next(true);
  279. });
  280. });
  281. };
  282. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  283. const accountId = req.accountId || req.remoteAddress;
  284. const streamType = notificationOnly ? ' (notification)' : '';
  285. log.verbose(req.requestId, `Starting stream from ${id} for ${accountId}${streamType}`);
  286. const listener = message => {
  287. const { event, payload, queued_at } = JSON.parse(message);
  288. const transmit = () => {
  289. const now = new Date().getTime();
  290. const delta = now - queued_at;
  291. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  292. log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  293. output(event, encodedPayload);
  294. };
  295. if (notificationOnly && event !== 'notification') {
  296. return;
  297. }
  298. if (event === 'notification' && !req.allowNotifications) {
  299. return;
  300. }
  301. // Only messages that may require filtering are statuses, since notifications
  302. // are already personalized and deletes do not matter
  303. if (!needsFiltering || event !== 'update') {
  304. transmit();
  305. return;
  306. }
  307. const unpackedPayload = payload;
  308. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  309. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  310. if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
  311. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  312. return;
  313. }
  314. // When the account is not logged in, it is not necessary to confirm the block or mute
  315. if (!req.accountId) {
  316. transmit();
  317. return;
  318. }
  319. pgPool.connect((err, client, done) => {
  320. if (err) {
  321. log.error(err);
  322. return;
  323. }
  324. const queries = [
  325. client.query(`SELECT 1 FROM blocks WHERE (account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})) OR (account_id = $2 AND target_account_id = $1) UNION SELECT 1 FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})`, [req.accountId, unpackedPayload.account.id].concat(targetAccountIds)),
  326. ];
  327. if (accountDomain) {
  328. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  329. }
  330. Promise.all(queries).then(values => {
  331. done();
  332. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  333. return;
  334. }
  335. transmit();
  336. }).catch(err => {
  337. done();
  338. log.error(err);
  339. });
  340. });
  341. };
  342. subscribe(`${redisPrefix}${id}`, listener);
  343. attachCloseHandler(`${redisPrefix}${id}`, listener);
  344. };
  345. // Setup stream output to HTTP
  346. const streamToHttp = (req, res) => {
  347. const accountId = req.accountId || req.remoteAddress;
  348. res.setHeader('Content-Type', 'text/event-stream');
  349. res.setHeader('Cache-Control', 'no-store');
  350. res.setHeader('Transfer-Encoding', 'chunked');
  351. res.write(':)\n');
  352. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  353. req.on('close', () => {
  354. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  355. clearInterval(heartbeat);
  356. });
  357. return (event, payload) => {
  358. res.write(`event: ${event}\n`);
  359. res.write(`data: ${payload}\n\n`);
  360. };
  361. };
  362. // Setup stream end for HTTP
  363. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  364. req.on('close', () => {
  365. unsubscribe(id, listener);
  366. if (closeHandler) {
  367. closeHandler();
  368. }
  369. });
  370. };
  371. // Setup stream output to WebSockets
  372. const streamToWs = (req, ws) => (event, payload) => {
  373. if (ws.readyState !== ws.OPEN) {
  374. log.error(req.requestId, 'Tried writing to closed socket');
  375. return;
  376. }
  377. ws.send(JSON.stringify({ event, payload }));
  378. };
  379. // Setup stream end for WebSockets
  380. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  381. const accountId = req.accountId || req.remoteAddress;
  382. ws.on('close', () => {
  383. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  384. unsubscribe(id, listener);
  385. if (closeHandler) {
  386. closeHandler();
  387. }
  388. });
  389. ws.on('error', () => {
  390. log.verbose(req.requestId, `Ending stream for ${accountId}`);
  391. unsubscribe(id, listener);
  392. if (closeHandler) {
  393. closeHandler();
  394. }
  395. });
  396. };
  397. const httpNotFound = res => {
  398. res.writeHead(404, { 'Content-Type': 'application/json' });
  399. res.end(JSON.stringify({ error: 'Not found' }));
  400. };
  401. app.use(setRequestId);
  402. app.use(setRemoteAddress);
  403. app.use(allowCrossDomain);
  404. app.get('/api/v1/streaming/health', (req, res) => {
  405. res.writeHead(200, { 'Content-Type': 'text/plain' });
  406. res.end('OK');
  407. });
  408. app.use(authenticationMiddleware);
  409. app.use(errorMiddleware);
  410. app.get('/api/v1/streaming/user', (req, res) => {
  411. const channel = `timeline:${req.accountId}`;
  412. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  413. });
  414. app.get('/api/v1/streaming/user/notification', (req, res) => {
  415. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  416. });
  417. app.get('/api/v1/streaming/public', (req, res) => {
  418. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  419. const channel = onlyMedia ? 'timeline:public:media' : 'timeline:public';
  420. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  421. });
  422. app.get('/api/v1/streaming/public/local', (req, res) => {
  423. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  424. const channel = onlyMedia ? 'timeline:public:local:media' : 'timeline:public:local';
  425. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  426. });
  427. app.get('/api/v1/streaming/public/remote', (req, res) => {
  428. const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
  429. const channel = onlyMedia ? 'timeline:public:remote:media' : 'timeline:public:remote';
  430. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
  431. });
  432. app.get('/api/v1/streaming/direct', (req, res) => {
  433. const channel = `timeline:direct:${req.accountId}`;
  434. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)), true);
  435. });
  436. app.get('/api/v1/streaming/hashtag', (req, res) => {
  437. const { tag } = req.query;
  438. if (!tag || tag.length === 0) {
  439. httpNotFound(res);
  440. return;
  441. }
  442. streamFrom(`timeline:hashtag:${tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  443. });
  444. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  445. const { tag } = req.query;
  446. if (!tag || tag.length === 0) {
  447. httpNotFound(res);
  448. return;
  449. }
  450. streamFrom(`timeline:hashtag:${tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  451. });
  452. app.get('/api/v1/streaming/list', (req, res) => {
  453. const listId = req.query.list;
  454. authorizeListAccess(listId, req, authorized => {
  455. if (!authorized) {
  456. httpNotFound(res);
  457. return;
  458. }
  459. const channel = `timeline:list:${listId}`;
  460. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  461. });
  462. });
  463. const wss = new WebSocketServer({ server, verifyClient: wsVerifyClient });
  464. wss.on('connection', (ws, req) => {
  465. const location = url.parse(req.url, true);
  466. req.requestId = uuid.v4();
  467. req.remoteAddress = ws._socket.remoteAddress;
  468. let channel;
  469. switch(location.query.stream) {
  470. case 'user':
  471. channel = `timeline:${req.accountId}`;
  472. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  473. break;
  474. case 'user:notification':
  475. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  476. break;
  477. case 'public':
  478. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  479. break;
  480. case 'public:local':
  481. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  482. break;
  483. case 'public:remote':
  484. streamFrom('timeline:public:remote', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  485. break;
  486. case 'public:media':
  487. streamFrom('timeline:public:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  488. break;
  489. case 'public:local:media':
  490. streamFrom('timeline:public:local:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  491. break;
  492. case 'public:remote:media':
  493. streamFrom('timeline:public:remote:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  494. break;
  495. case 'direct':
  496. channel = `timeline:direct:${req.accountId}`;
  497. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)), true);
  498. break;
  499. case 'hashtag':
  500. if (!location.query.tag || location.query.tag.length === 0) {
  501. ws.close();
  502. return;
  503. }
  504. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  505. break;
  506. case 'hashtag:local':
  507. if (!location.query.tag || location.query.tag.length === 0) {
  508. ws.close();
  509. return;
  510. }
  511. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  512. break;
  513. case 'list':
  514. const listId = location.query.list;
  515. authorizeListAccess(listId, req, authorized => {
  516. if (!authorized) {
  517. ws.close();
  518. return;
  519. }
  520. channel = `timeline:list:${listId}`;
  521. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  522. });
  523. break;
  524. default:
  525. ws.close();
  526. }
  527. });
  528. wss.startAutoPing(30000);
  529. attachServerWithConfig(server, address => {
  530. log.info(`Worker ${workerId} now listening on ${address}`);
  531. });
  532. const onExit = () => {
  533. log.info(`Worker ${workerId} exiting, bye bye`);
  534. server.close();
  535. process.exit(0);
  536. };
  537. const onError = (err) => {
  538. log.error(err);
  539. server.close();
  540. process.exit(0);
  541. };
  542. process.on('SIGINT', onExit);
  543. process.on('SIGTERM', onExit);
  544. process.on('exit', onExit);
  545. process.on('uncaughtException', onError);
  546. };
  547. const attachServerWithConfig = (server, onSuccess) => {
  548. if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
  549. server.listen(process.env.SOCKET || process.env.PORT, () => {
  550. if (onSuccess) {
  551. fs.chmodSync(server.address(), 0o666);
  552. onSuccess(server.address());
  553. }
  554. });
  555. } else {
  556. server.listen(+process.env.PORT || 4000, process.env.BIND || '127.0.0.1', () => {
  557. if (onSuccess) {
  558. onSuccess(`${server.address().address}:${server.address().port}`);
  559. }
  560. });
  561. }
  562. };
  563. const onPortAvailable = onSuccess => {
  564. const testServer = http.createServer();
  565. testServer.once('error', err => {
  566. onSuccess(err);
  567. });
  568. testServer.once('listening', () => {
  569. testServer.once('close', () => onSuccess());
  570. testServer.close();
  571. });
  572. attachServerWithConfig(testServer);
  573. };
  574. onPortAvailable(err => {
  575. if (err) {
  576. log.error('Could not start server, the port or socket is in use');
  577. return;
  578. }
  579. throng({
  580. workers: numWorkers,
  581. lifetime: Infinity,
  582. start: startWorker,
  583. master: startMaster,
  584. });
  585. });