index.js 9.0 KB

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