index.js 8.0 KB

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