The code powering m.abunchtell.com https://m.abunchtell.com
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

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