index.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. require('dotenv').config();
  2. const Fastify = require('fastify');
  3. const { Queue, Worker, QueueEvents } = require('bullmq');
  4. const IORedis = require('ioredis');
  5. const axios = require('axios');
  6. const { randomUUID } = require('crypto');
  7. const { getDb, connect } = require('./utils/MongoDBConnector');
  8. const { createLogger } = require('./utils/logger');
  9. const REDIS_URL = process.env.REDIS_URL || 'redis://redis:6379';
  10. const GATEWAY_URL = process.env.GATEWAY_URL || 'http://gateway:8084';
  11. const PLATFORM_SERVICES = {
  12. twitter: process.env.TWITTER_SERVICE_URL || 'http://twitter:3001',
  13. linkedin: process.env.LINKEDIN_SERVICE_URL || 'http://linkedin:3002',
  14. mastodon: process.env.MASTODON_SERVICE_URL || 'http://mastodon:3003',
  15. bluesky: process.env.BLUESKY_SERVICE_URL || 'http://bluesky:3004',
  16. instagram: process.env.INSTAGRAM_SERVICE_URL || 'http://instagram:3005',
  17. facebook: process.env.FACEBOOK_SERVICE_URL || 'http://facebook:3006',
  18. pinterest: process.env.PINTEREST_SERVICE_URL || 'http://pinterest:3008',
  19. tiktok: process.env.TIKTOK_SERVICE_URL || 'http://tiktok:3007',
  20. };
  21. const log = createLogger('scheduler');
  22. const app = Fastify({ logger: log });
  23. let postQueue;
  24. let redis;
  25. // ─── Job Worker ──────────────────────────────────────────────────────────────
  26. async function processPostJob(job) {
  27. // destinations: [{ platform, accountId?, imageUrl?, videoUrl?, link? }]
  28. // Falls back to legacy { platforms: string[] } format
  29. const { postId, content, destinations, platforms, media = [] } = job.data;
  30. // Ensure every post has a stable ID for analytics tracking
  31. const effectivePostId = postId || randomUUID();
  32. const destList = destinations || (platforms || []).map((p) => ({ platform: p }));
  33. log.info({ action: 'job_process', jobId: job.id, attempt: job.attemptsMade + 1, destinations: destList.map((d) => d.accountId ? `${d.platform}:${d.accountId}` : d.platform) });
  34. const db = await getDb();
  35. // Load any results already recorded from previous attempts so we can skip
  36. // destinations that already succeeded — preventing duplicate posts on retry.
  37. const existingPost = await db.collection('posts').findOne({ _id: effectivePostId }, { projection: { platformResults: 1 } });
  38. const results = { ...(existingPost?.platformResults || {}) };
  39. for (const dest of destList) {
  40. const { platform, accountId, imageUrl, videoUrl, link } = dest;
  41. const resultKey = accountId ? `${platform}:${accountId}` : platform;
  42. if (results[resultKey]?.success) {
  43. log.info({ action: 'job_skip_dest', jobId: job.id, destination: resultKey, reason: 'already_published' });
  44. continue;
  45. }
  46. const serviceUrl = PLATFORM_SERVICES[platform];
  47. if (!serviceUrl) {
  48. results[resultKey] = { success: false, error: 'Unknown platform' };
  49. continue;
  50. }
  51. try {
  52. const response = await axios.post(`${serviceUrl}/post`, { content, accountId, imageUrl, videoUrl, link, media }, { timeout: 30000 });
  53. results[resultKey] = { success: true, ...response.data.result };
  54. } catch (err) {
  55. results[resultKey] = { success: false, error: err.message };
  56. }
  57. }
  58. const allOk = Object.values(results).every((r) => r.success);
  59. const anyOk = Object.values(results).some((r) => r.success);
  60. const postStatus = allOk ? 'published' : anyOk ? 'partial' : 'failed';
  61. await db.collection('posts').updateOne(
  62. { _id: effectivePostId },
  63. {
  64. $set: {
  65. content,
  66. destinations: destList,
  67. type: 'scheduled',
  68. status: postStatus,
  69. publishedAt: new Date(),
  70. platformResults: results,
  71. },
  72. $setOnInsert: { createdAt: new Date() },
  73. },
  74. { upsert: true }
  75. );
  76. await db.collection('scheduled_jobs').updateOne(
  77. { bullJobId: String(job.id) },
  78. {
  79. $set: {
  80. status: 'completed',
  81. completedAt: new Date(),
  82. },
  83. }
  84. );
  85. return results;
  86. }
  87. // ─── System Job Worker ────────────────────────────────────────────────────────
  88. async function processSystemJob(job) {
  89. if (job.name === 'meta-token-refresh') {
  90. log.info({ action: 'token_refresh', trigger: 'scheduled', outcome: 'start' });
  91. const res = await axios.post(`${GATEWAY_URL}/meta/token-refresh`, {}, { timeout: 60000 });
  92. log.info({ action: 'token_refresh', trigger: 'scheduled', outcome: 'success', refreshed: res.data.refreshed, skipped: res.data.skipped, errors: res.data.errors });
  93. return res.data;
  94. }
  95. if (job.name === 'metrics-crawl') {
  96. log.info({ action: 'metrics_crawl', trigger: 'scheduled', outcome: 'start' });
  97. const res = await axios.post(`${GATEWAY_URL}/analytics/crawl`, {}, { timeout: 120000 });
  98. log.info({ action: 'metrics_crawl', trigger: 'scheduled', outcome: 'success', total: res.data.total });
  99. return res.data;
  100. }
  101. }
  102. // ─── HTTP Endpoints ──────────────────────────────────────────────────────────
  103. app.get('/health', async () => ({ status: 'ok', service: 'scheduler' }));
  104. // Create a scheduled post.
  105. // Body: { content, scheduledAt, destinations: [{ platform, accountId?, imageUrl?, videoUrl?, link? }] }
  106. // Legacy { platforms: string[] } still accepted for backwards compatibility.
  107. app.post('/schedule', async (request, reply) => {
  108. const { postId, content, destinations, platforms, scheduledAt, media = [] } = request.body;
  109. const destList = destinations || (platforms || []).map((p) => ({ platform: p }));
  110. if (!content || !destList.length || !scheduledAt) {
  111. return reply.code(400).send({ error: 'content, destinations, and scheduledAt are required' });
  112. }
  113. const delay = new Date(scheduledAt).getTime() - Date.now();
  114. if (delay < 0) {
  115. return reply.code(400).send({ error: 'scheduledAt must be in the future' });
  116. }
  117. const job = await postQueue.add(
  118. 'scheduled-post',
  119. { postId, content, destinations: destList, media },
  120. { delay, attempts: 3, backoff: { type: 'exponential', delay: 60000 } }
  121. );
  122. const db = await getDb();
  123. await db.collection('scheduled_jobs').insertOne({
  124. postId,
  125. type: 'one-time',
  126. content,
  127. scheduledAt: new Date(scheduledAt),
  128. destinations: destList,
  129. status: 'pending',
  130. attempts: 0,
  131. maxAttempts: 3,
  132. bullJobId: String(job.id),
  133. createdAt: new Date(),
  134. });
  135. return { success: true, jobId: job.id, scheduledAt };
  136. });
  137. // Zamanlanmış görevleri listele
  138. app.get('/jobs', async (request) => {
  139. const { status = 'pending' } = request.query;
  140. const db = await getDb();
  141. const jobs = await db
  142. .collection('scheduled_jobs')
  143. .find({ status })
  144. .sort({ scheduledAt: 1 })
  145. .toArray();
  146. return { success: true, count: jobs.length, jobs };
  147. });
  148. // Görevi iptal et
  149. app.delete('/jobs/:jobId', async (request, reply) => {
  150. const { jobId } = request.params;
  151. const job = await postQueue.getJob(jobId);
  152. if (!job) return reply.code(404).send({ error: 'Job bulunamadı' });
  153. await job.remove();
  154. const db = await getDb();
  155. await db.collection('scheduled_jobs').updateOne(
  156. { bullJobId: jobId },
  157. { $set: { status: 'cancelled' } }
  158. );
  159. return { success: true, jobId };
  160. });
  161. // ─── Başlatma ────────────────────────────────────────────────────────────────
  162. async function start() {
  163. await connect();
  164. redis = new IORedis(REDIS_URL, { maxRetriesPerRequest: null });
  165. postQueue = new Queue('post-queue', { connection: redis });
  166. const worker = new Worker('post-queue', processPostJob, { connection: redis });
  167. worker.on('failed', (job, err) => {
  168. log.error({ action: 'job_process', jobId: job?.id, outcome: 'failure', err: err.message });
  169. });
  170. // Daily system jobs (housekeeping, token refresh, etc.)
  171. const systemQueue = new Queue('system-queue', { connection: redis });
  172. const systemWorker = new Worker('system-queue', processSystemJob, { connection: redis });
  173. systemWorker.on('failed', (job, err) => {
  174. log.error({ action: 'system_job', jobId: job?.id, jobName: job?.name, outcome: 'failure', err: err.message });
  175. });
  176. // Register daily system jobs — BullMQ deduplicates by repeat key on restart
  177. await systemQueue.add(
  178. 'meta-token-refresh',
  179. {},
  180. { repeat: { every: 24 * 60 * 60 * 1000 }, removeOnComplete: 5, removeOnFail: 5 }
  181. );
  182. log.info({ action: 'system_job_register', job: 'meta-token-refresh', interval: '24h', outcome: 'success' });
  183. await systemQueue.add(
  184. 'metrics-crawl',
  185. {},
  186. { repeat: { every: 24 * 60 * 60 * 1000 }, removeOnComplete: 5, removeOnFail: 5 }
  187. );
  188. log.info({ action: 'system_job_register', job: 'metrics-crawl', interval: '24h', outcome: 'success' });
  189. await app.listen({ port: process.env.PORT || 3011, host: '0.0.0.0' });
  190. log.info({ action: 'service_start', port: 3011, outcome: 'success' }, 'Scheduler started');
  191. }
  192. start().catch((err) => { log.error({ action: 'service_start', outcome: 'failure', err: err.message }); process.exit(1); });