The code powering m.abunchtell.com https://m.abunchtell.com
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

417 linhas
12 KiB

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