index.js 8.4 KB

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