index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 = [], firstComment, workspaceId = 'default' } = 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(
  53. `${serviceUrl}/post`,
  54. { content, accountId, imageUrl, videoUrl, link, media, firstComment: firstComment?.trim() || undefined },
  55. { timeout: 30000, headers: { 'X-Workspace-Id': workspaceId } }
  56. );
  57. results[resultKey] = { success: true, ...response.data.result };
  58. } catch (err) {
  59. results[resultKey] = { success: false, error: err.message };
  60. }
  61. }
  62. const allOk = Object.values(results).every((r) => r.success);
  63. const anyOk = Object.values(results).some((r) => r.success);
  64. const postStatus = allOk ? 'published' : anyOk ? 'partial' : 'failed';
  65. await db.collection('posts').updateOne(
  66. { _id: effectivePostId },
  67. {
  68. $set: {
  69. content,
  70. destinations: destList,
  71. type: 'scheduled',
  72. status: postStatus,
  73. publishedAt: new Date(),
  74. platformResults: results,
  75. workspaceId,
  76. },
  77. $setOnInsert: { createdAt: new Date() },
  78. },
  79. { upsert: true }
  80. );
  81. await db.collection('scheduled_jobs').updateOne(
  82. { bullJobId: String(job.id) },
  83. {
  84. $set: {
  85. status: 'completed',
  86. completedAt: new Date(),
  87. },
  88. }
  89. );
  90. return results;
  91. }
  92. // ─── System Job Worker ────────────────────────────────────────────────────────
  93. async function processSystemJob(job) {
  94. if (job.name === 'meta-token-refresh') {
  95. log.info({ action: 'token_refresh', trigger: 'scheduled', outcome: 'start' });
  96. const res = await axios.post(`${GATEWAY_URL}/meta/token-refresh`, {}, { timeout: 60000 });
  97. log.info({ action: 'token_refresh', trigger: 'scheduled', outcome: 'success', refreshed: res.data.refreshed, skipped: res.data.skipped, errors: res.data.errors });
  98. return res.data;
  99. }
  100. if (job.name === 'metrics-crawl') {
  101. log.info({ action: 'metrics_crawl', trigger: 'scheduled', outcome: 'start' });
  102. const res = await axios.post(`${GATEWAY_URL}/analytics/crawl`, {}, { timeout: 120000 });
  103. log.info({ action: 'metrics_crawl', trigger: 'scheduled', outcome: 'success', total: res.data.total });
  104. return res.data;
  105. }
  106. if (job.name === 'competitor-scrape') {
  107. log.info({ action: 'competitor_scrape', trigger: 'scheduled', outcome: 'start' });
  108. const res = await axios.post(`${GATEWAY_URL}/competitors/scrape-all`, {}, { timeout: 120000 });
  109. log.info({ action: 'competitor_scrape', trigger: 'scheduled', outcome: 'success', results: res.data.results?.length });
  110. return res.data;
  111. }
  112. }
  113. // ─── HTTP Endpoints ──────────────────────────────────────────────────────────
  114. app.get('/health', async () => ({ status: 'ok', service: 'scheduler' }));
  115. // Create a scheduled post.
  116. // Body: { content, scheduledAt, destinations: [{ platform, accountId?, imageUrl?, videoUrl?, link? }] }
  117. // Legacy { platforms: string[] } still accepted for backwards compatibility.
  118. app.post('/schedule', async (request, reply) => {
  119. const { postId, content, destinations, platforms, scheduledAt, media = [], firstComment } = request.body;
  120. const workspaceId = request.headers['x-workspace-id'] || 'default';
  121. const destList = destinations || (platforms || []).map((p) => ({ platform: p }));
  122. if (!content || !destList.length || !scheduledAt) {
  123. return reply.code(400).send({ error: 'content, destinations, and scheduledAt are required' });
  124. }
  125. const delay = new Date(scheduledAt).getTime() - Date.now();
  126. if (delay < 0) {
  127. return reply.code(400).send({ error: 'scheduledAt must be in the future' });
  128. }
  129. const job = await postQueue.add(
  130. 'scheduled-post',
  131. { postId, content, destinations: destList, media, firstComment: firstComment?.trim() || undefined, workspaceId },
  132. { delay, attempts: 3, backoff: { type: 'exponential', delay: 60000 } }
  133. );
  134. const db = await getDb();
  135. await db.collection('scheduled_jobs').insertOne({
  136. postId,
  137. type: 'one-time',
  138. content,
  139. scheduledAt: new Date(scheduledAt),
  140. destinations: destList,
  141. status: 'pending',
  142. attempts: 0,
  143. maxAttempts: 3,
  144. bullJobId: String(job.id),
  145. workspaceId,
  146. createdAt: new Date(),
  147. });
  148. return { success: true, jobId: job.id, scheduledAt };
  149. });
  150. // Zamanlanmış görevleri listele
  151. app.get('/jobs', async (request) => {
  152. const { status = 'pending' } = request.query;
  153. const workspaceId = request.headers['x-workspace-id'] || 'default';
  154. const db = await getDb();
  155. // Include legacy jobs without workspaceId (backwards compat)
  156. const filter = { status, $or: [{ workspaceId }, { workspaceId: { $exists: false } }] };
  157. const jobs = await db
  158. .collection('scheduled_jobs')
  159. .find(filter)
  160. .sort({ scheduledAt: 1 })
  161. .toArray();
  162. return { success: true, count: jobs.length, jobs };
  163. });
  164. // Görevi iptal et
  165. app.delete('/jobs/:jobId', async (request, reply) => {
  166. const { jobId } = request.params;
  167. const workspaceId = request.headers['x-workspace-id'] || 'default';
  168. const db = await getDb();
  169. const jobDoc = await db.collection('scheduled_jobs').findOne({
  170. bullJobId: jobId,
  171. $or: [{ workspaceId }, { workspaceId: { $exists: false } }],
  172. });
  173. if (!jobDoc) return reply.code(404).send({ error: 'Job bulunamadı' });
  174. const job = await postQueue.getJob(jobId);
  175. if (job) await job.remove();
  176. await db.collection('scheduled_jobs').updateOne(
  177. { bullJobId: jobId },
  178. { $set: { status: 'cancelled' } }
  179. );
  180. return { success: true, jobId };
  181. });
  182. // ─── Başlatma ────────────────────────────────────────────────────────────────
  183. async function start() {
  184. await connect();
  185. redis = new IORedis(REDIS_URL, { maxRetriesPerRequest: null });
  186. postQueue = new Queue('post-queue', { connection: redis });
  187. const worker = new Worker('post-queue', processPostJob, { connection: redis });
  188. worker.on('failed', (job, err) => {
  189. log.error({ action: 'job_process', jobId: job?.id, outcome: 'failure', err: err.message });
  190. });
  191. // Daily system jobs (housekeeping, token refresh, etc.)
  192. const systemQueue = new Queue('system-queue', { connection: redis });
  193. const systemWorker = new Worker('system-queue', processSystemJob, { connection: redis });
  194. systemWorker.on('failed', (job, err) => {
  195. log.error({ action: 'system_job', jobId: job?.id, jobName: job?.name, outcome: 'failure', err: err.message });
  196. });
  197. // Register daily system jobs — BullMQ deduplicates by repeat key on restart
  198. await systemQueue.add(
  199. 'meta-token-refresh',
  200. {},
  201. { repeat: { every: 24 * 60 * 60 * 1000 }, removeOnComplete: 5, removeOnFail: 5 }
  202. );
  203. log.info({ action: 'system_job_register', job: 'meta-token-refresh', interval: '24h', outcome: 'success' });
  204. await systemQueue.add(
  205. 'metrics-crawl',
  206. {},
  207. { repeat: { every: 24 * 60 * 60 * 1000 }, removeOnComplete: 5, removeOnFail: 5 }
  208. );
  209. log.info({ action: 'system_job_register', job: 'metrics-crawl', interval: '24h', outcome: 'success' });
  210. await systemQueue.add(
  211. 'competitor-scrape',
  212. {},
  213. { repeat: { every: 7 * 24 * 60 * 60 * 1000 }, removeOnComplete: 5, removeOnFail: 5 }
  214. );
  215. log.info({ action: 'system_job_register', job: 'competitor-scrape', interval: '7d', outcome: 'success' });
  216. await app.listen({ port: process.env.PORT || 3011, host: '0.0.0.0' });
  217. log.info({ action: 'service_start', port: 3011, outcome: 'success' }, 'Scheduler started');
  218. }
  219. start().catch((err) => { log.error({ action: 'service_start', outcome: 'failure', err: err.message }); process.exit(1); });