The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

489 lines
14 KiB

  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 WebSocket = require('uws');
  11. const uuid = require('uuid');
  12. const env = process.env.NODE_ENV || 'development';
  13. dotenv.config({
  14. path: env === 'production' ? '.env.production' : '.env',
  15. });
  16. log.level = process.env.LOG_LEVEL || 'verbose';
  17. const dbUrlToConfig = (dbUrl) => {
  18. if (!dbUrl) {
  19. return {};
  20. }
  21. const params = url.parse(dbUrl);
  22. const config = {};
  23. if (params.auth) {
  24. [config.user, config.password] = params.auth.split(':');
  25. }
  26. if (params.hostname) {
  27. config.host = params.hostname;
  28. }
  29. if (params.port) {
  30. config.port = params.port;
  31. }
  32. if (params.pathname) {
  33. config.database = params.pathname.split('/')[1];
  34. }
  35. const ssl = params.query && params.query.ssl;
  36. if (ssl) {
  37. config.ssl = ssl === 'true' || ssl === '1';
  38. }
  39. return config;
  40. };
  41. const redisUrlToClient = (defaultConfig, redisUrl) => {
  42. const config = defaultConfig;
  43. if (!redisUrl) {
  44. return redis.createClient(config);
  45. }
  46. if (redisUrl.startsWith('unix://')) {
  47. return redis.createClient(redisUrl.slice(7), config);
  48. }
  49. return redis.createClient(Object.assign(config, {
  50. url: redisUrl,
  51. }));
  52. };
  53. const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  54. const startMaster = () => {
  55. log.info(`Starting streaming API server master with ${numWorkers} workers`);
  56. };
  57. const startWorker = (workerId) => {
  58. log.info(`Starting worker ${workerId}`);
  59. const pgConfigs = {
  60. development: {
  61. user: process.env.DB_USER || pg.defaults.user,
  62. password: process.env.DB_PASS || pg.defaults.password,
  63. database: process.env.DB_NAME || 'mastodon_development',
  64. host: process.env.DB_HOST || pg.defaults.host,
  65. port: process.env.DB_PORT || pg.defaults.port,
  66. max: 10,
  67. },
  68. production: {
  69. user: process.env.DB_USER || 'mastodon',
  70. password: process.env.DB_PASS || '',
  71. database: process.env.DB_NAME || 'mastodon_production',
  72. host: process.env.DB_HOST || 'localhost',
  73. port: process.env.DB_PORT || 5432,
  74. max: 10,
  75. },
  76. };
  77. const app = express();
  78. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  79. const server = http.createServer(app);
  80. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  81. const redisParams = {
  82. host: process.env.REDIS_HOST || '127.0.0.1',
  83. port: process.env.REDIS_PORT || 6379,
  84. db: process.env.REDIS_DB || 0,
  85. password: process.env.REDIS_PASSWORD,
  86. };
  87. if (redisNamespace) {
  88. redisParams.namespace = redisNamespace;
  89. }
  90. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  91. const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  92. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  93. const subs = {};
  94. redisSubscribeClient.on('message', (channel, message) => {
  95. const callbacks = subs[channel];
  96. log.silly(`New message on channel ${channel}`);
  97. if (!callbacks) {
  98. return;
  99. }
  100. callbacks.forEach(callback => callback(message));
  101. });
  102. const subscriptionHeartbeat = (channel) => {
  103. const interval = 6*60;
  104. const tellSubscribed = () => {
  105. redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval*3);
  106. };
  107. tellSubscribed();
  108. const heartbeat = setInterval(tellSubscribed, interval*1000);
  109. return () => {
  110. clearInterval(heartbeat);
  111. };
  112. };
  113. const subscribe = (channel, callback) => {
  114. log.silly(`Adding listener for ${channel}`);
  115. subs[channel] = subs[channel] || [];
  116. if (subs[channel].length === 0) {
  117. log.verbose(`Subscribe ${channel}`);
  118. redisSubscribeClient.subscribe(channel);
  119. }
  120. subs[channel].push(callback);
  121. };
  122. const unsubscribe = (channel, callback) => {
  123. log.silly(`Removing listener for ${channel}`);
  124. subs[channel] = subs[channel].filter(item => item !== callback);
  125. if (subs[channel].length === 0) {
  126. log.verbose(`Unsubscribe ${channel}`);
  127. redisSubscribeClient.unsubscribe(channel);
  128. }
  129. };
  130. const allowCrossDomain = (req, res, next) => {
  131. res.header('Access-Control-Allow-Origin', '*');
  132. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  133. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  134. next();
  135. };
  136. const setRequestId = (req, res, next) => {
  137. req.requestId = uuid.v4();
  138. res.header('X-Request-Id', req.requestId);
  139. next();
  140. };
  141. const accountFromToken = (token, req, next) => {
  142. pgPool.connect((err, client, done) => {
  143. if (err) {
  144. next(err);
  145. return;
  146. }
  147. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.filtered_languages 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) => {
  148. done();
  149. if (err) {
  150. next(err);
  151. return;
  152. }
  153. if (result.rows.length === 0) {
  154. err = new Error('Invalid access token');
  155. err.statusCode = 401;
  156. next(err);
  157. return;
  158. }
  159. req.accountId = result.rows[0].account_id;
  160. req.filteredLanguages = result.rows[0].filtered_languages;
  161. next();
  162. });
  163. });
  164. };
  165. const accountFromRequest = (req, next) => {
  166. const authorization = req.headers.authorization;
  167. const location = url.parse(req.url, true);
  168. const accessToken = location.query.access_token;
  169. if (!authorization && !accessToken) {
  170. const err = new Error('Missing access token');
  171. err.statusCode = 401;
  172. next(err);
  173. return;
  174. }
  175. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  176. accountFromToken(token, req, next);
  177. };
  178. const wsVerifyClient = (info, cb) => {
  179. accountFromRequest(info.req, err => {
  180. if (!err) {
  181. cb(true, undefined, undefined);
  182. } else {
  183. log.error(info.req.requestId, err.toString());
  184. cb(false, 401, 'Unauthorized');
  185. }
  186. });
  187. };
  188. const authenticationMiddleware = (req, res, next) => {
  189. if (req.method === 'OPTIONS') {
  190. next();
  191. return;
  192. }
  193. accountFromRequest(req, next);
  194. };
  195. const errorMiddleware = (err, req, res, {}) => {
  196. log.error(req.requestId, err.toString());
  197. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  198. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  199. };
  200. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  201. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  202. const streamType = notificationOnly ? ' (notification)' : '';
  203. log.verbose(req.requestId, `Starting stream from ${id} for ${req.accountId}${streamType}`);
  204. const listener = message => {
  205. const { event, payload, queued_at } = JSON.parse(message);
  206. const transmit = () => {
  207. const now = new Date().getTime();
  208. const delta = now - queued_at;
  209. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  210. log.silly(req.requestId, `Transmitting for ${req.accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  211. output(event, encodedPayload);
  212. };
  213. if (notificationOnly && event !== 'notification') {
  214. return;
  215. }
  216. // Only messages that may require filtering are statuses, since notifications
  217. // are already personalized and deletes do not matter
  218. if (needsFiltering && event === 'update') {
  219. pgPool.connect((err, client, done) => {
  220. if (err) {
  221. log.error(err);
  222. return;
  223. }
  224. const unpackedPayload = payload;
  225. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  226. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  227. if (Array.isArray(req.filteredLanguages) && req.filteredLanguages.indexOf(unpackedPayload.language) !== -1) {
  228. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  229. done();
  230. return;
  231. }
  232. const queries = [
  233. 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)),
  234. ];
  235. if (accountDomain) {
  236. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  237. }
  238. Promise.all(queries).then(values => {
  239. done();
  240. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  241. return;
  242. }
  243. transmit();
  244. }).catch(err => {
  245. done();
  246. log.error(err);
  247. });
  248. });
  249. } else {
  250. transmit();
  251. }
  252. };
  253. subscribe(`${redisPrefix}${id}`, listener);
  254. attachCloseHandler(`${redisPrefix}${id}`, listener);
  255. };
  256. // Setup stream output to HTTP
  257. const streamToHttp = (req, res) => {
  258. res.setHeader('Content-Type', 'text/event-stream');
  259. res.setHeader('Transfer-Encoding', 'chunked');
  260. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  261. req.on('close', () => {
  262. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  263. clearInterval(heartbeat);
  264. });
  265. return (event, payload) => {
  266. res.write(`event: ${event}\n`);
  267. res.write(`data: ${payload}\n\n`);
  268. };
  269. };
  270. // Setup stream end for HTTP
  271. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  272. req.on('close', () => {
  273. unsubscribe(id, listener);
  274. if (closeHandler) {
  275. closeHandler();
  276. }
  277. });
  278. };
  279. // Setup stream output to WebSockets
  280. const streamToWs = (req, ws) => (event, payload) => {
  281. if (ws.readyState !== ws.OPEN) {
  282. log.error(req.requestId, 'Tried writing to closed socket');
  283. return;
  284. }
  285. ws.send(JSON.stringify({ event, payload }));
  286. };
  287. // Setup stream end for WebSockets
  288. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  289. ws.on('close', () => {
  290. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  291. unsubscribe(id, listener);
  292. if (closeHandler) {
  293. closeHandler();
  294. }
  295. });
  296. ws.on('error', () => {
  297. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  298. unsubscribe(id, listener);
  299. if (closeHandler) {
  300. closeHandler();
  301. }
  302. });
  303. };
  304. app.use(setRequestId);
  305. app.use(allowCrossDomain);
  306. app.use(authenticationMiddleware);
  307. app.use(errorMiddleware);
  308. app.get('/api/v1/streaming/user', (req, res) => {
  309. const channel = `timeline:${req.accountId}`;
  310. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  311. });
  312. app.get('/api/v1/streaming/user/notification', (req, res) => {
  313. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  314. });
  315. app.get('/api/v1/streaming/public', (req, res) => {
  316. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true);
  317. });
  318. app.get('/api/v1/streaming/public/local', (req, res) => {
  319. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true);
  320. });
  321. app.get('/api/v1/streaming/hashtag', (req, res) => {
  322. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  323. });
  324. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  325. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  326. });
  327. const wss = new WebSocket.Server({ server, verifyClient: wsVerifyClient });
  328. wss.on('connection', ws => {
  329. const req = ws.upgradeReq;
  330. const location = url.parse(req.url, true);
  331. req.requestId = uuid.v4();
  332. ws.isAlive = true;
  333. ws.on('pong', () => {
  334. ws.isAlive = true;
  335. });
  336. switch(location.query.stream) {
  337. case 'user':
  338. const channel = `timeline:${req.accountId}`;
  339. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  340. break;
  341. case 'user:notification':
  342. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  343. break;
  344. case 'public':
  345. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  346. break;
  347. case 'public:local':
  348. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  349. break;
  350. case 'hashtag':
  351. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  352. break;
  353. case 'hashtag:local':
  354. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  355. break;
  356. default:
  357. ws.close();
  358. }
  359. });
  360. setInterval(() => {
  361. wss.clients.forEach(ws => {
  362. if (ws.isAlive === false) {
  363. ws.terminate();
  364. return;
  365. }
  366. ws.isAlive = false;
  367. ws.ping('', false, true);
  368. });
  369. }, 30000);
  370. server.listen(process.env.PORT || 4000, () => {
  371. log.info(`Worker ${workerId} now listening on ${server.address().address}:${server.address().port}`);
  372. });
  373. const onExit = () => {
  374. log.info(`Worker ${workerId} exiting, bye bye`);
  375. server.close();
  376. process.exit(0);
  377. };
  378. const onError = (err) => {
  379. log.error(err);
  380. };
  381. process.on('SIGINT', onExit);
  382. process.on('SIGTERM', onExit);
  383. process.on('exit', onExit);
  384. process.on('error', onError);
  385. };
  386. throng({
  387. workers: numWorkers,
  388. lifetime: Infinity,
  389. start: startWorker,
  390. master: startMaster,
  391. });