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.
 
 
 
 

483 lines
14 KiB

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