-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjobQueue.cjs
341 lines (300 loc) · 8.45 KB
/
jobQueue.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const Queue = require("bull");
const redis = require("redis");
const admin = require("firebase-admin");
const db = require("./firebaseConfig.cjs");
const PlatformPublisher = require("./src/services/platformPublisher.cjs");
const redisClient = redis.createClient({
url: "redis://127.0.0.1:6379",
});
redisClient.on("error", (error) => {
console.error("Redis error:", error);
});
// Configure queues with retry strategies
const postQueue = new Queue("postQueue", {
redis: "redis://127.0.0.1:6379",
settings: {
lockDuration: 30000, // 30 seconds
stalledInterval: 30000, // 30 seconds
maxStalledCount: 3,
backoff: {
type: "exponential",
delay: 5000, // 5 seconds initial delay
},
attempts: 5, // Maximum retry attempts
},
});
const notificationQueue = new Queue("notificationQueue", {
redis: "redis://127.0.0.1:6379",
settings: {
backoff: {
type: "exponential",
delay: 5000,
},
attempts: 3,
},
});
// Post Queue Processing
postQueue.process(async (job) => {
const { postId, platforms } = job.data;
const errors = [];
try {
// Get post data
const postRef = await db.collection("posts").doc(postId).get();
if (!postRef.exists) {
throw new Error("Post not found");
}
const post = postRef.data();
// Get user's tokens
const userRef = await db.collection("users").doc(post.author).get();
if (!userRef.exists) {
throw new Error("User not found");
}
const user = userRef.data();
// Update post status to processing
await PlatformPublisher.updatePostStatus(postId, "status", "processing");
// Publish to each platform
for (const platform of platforms) {
try {
await PlatformPublisher.updatePostStatus(
postId,
platform,
"publishing"
);
let result;
switch (platform) {
case "facebook":
result = await PlatformPublisher.publishToFacebook(
post.content,
user.connectedAccounts.facebook.accessToken
);
break;
case "twitter":
result = await PlatformPublisher.publishToTwitter(
post.content,
user.connectedAccounts.twitter.accessToken,
user.connectedAccounts.twitter.tokenSecret
);
break;
case "linkedin":
result = await PlatformPublisher.publishToLinkedIn(
post.content,
user.connectedAccounts.linkedin.accessToken
);
break;
}
await PlatformPublisher.updatePostStatus(
postId,
platform,
"published",
result.postId
);
} catch (error) {
errors.push({ platform, error: error.message });
await PlatformPublisher.updatePostStatus(postId, platform, "failed");
}
}
// Create notification for post status
await createNotificationJob(post.author, postId, Date.now(), {
title: errors.length
? "Post Published with Errors"
: "Post Published Successfully",
message: errors.length
? `Your post was published with errors on some platforms: ${errors
.map((e) => e.platform)
.join(", ")}`
: "Your post was successfully published to all platforms!",
});
if (errors.length > 0) {
throw new Error(JSON.stringify(errors));
}
return { success: true };
} catch (error) {
console.error("Post processing error:", error);
throw error;
}
});
// Notification Queue Processing
notificationQueue.process(async (job) => {
const { userId, postId, message } = job.data;
try {
// Get user data
const userRef = await db.collection("users").doc(userId).get();
if (!userRef.exists) {
throw new Error("User not found");
}
const user = userRef.data();
// Get post data
const postRef = await db.collection("posts").doc(postId).get();
if (!postRef.exists) {
throw new Error("Post not found");
}
const post = postRef.data();
// Send notification (e.g., email, push notification)
console.log(
`Sending notification to user ${userId} for post ${postId}: ${message}`
);
// Update notification status
await db.collection("notifications").doc(job.id).update({
status: "sent",
sentAt: admin.firestore.FieldValue.serverTimestamp(),
});
return { success: true };
} catch (error) {
console.error("Notification processing error:", error);
throw error;
}
});
// Enhanced job management functions
const createPostJob = async (postId, platforms, scheduledTime) => {
try {
const job = await postQueue.add(
{ postId, platforms },
{
delay: scheduledTime - Date.now(),
attempts: 5,
removeOnComplete: false, // Keep job data for history
}
);
await db
.collection("posts")
.doc(postId)
.update({
"metadata.scheduledTime":
admin.firestore.Timestamp.fromMillis(scheduledTime),
"metadata.jobId": job.id,
status: "scheduled",
});
return job;
} catch (error) {
console.error("Error creating post job:", error);
throw error;
}
};
const cancelPostJob = async (jobId, postId) => {
try {
const job = await postQueue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.remove();
await db.collection("posts").doc(postId).update({
status: "cancelled",
"metadata.updatedAt": admin.firestore.FieldValue.serverTimestamp(),
});
return true;
} catch (error) {
console.error("Error canceling post:", error);
throw error;
}
};
const reschedulePostJob = async (jobId, postId, newScheduledTime) => {
try {
const job = await postQueue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.remove();
const newJob = await createPostJob(
postId,
job.data.platforms,
newScheduledTime
);
await db
.collection("posts")
.doc(postId)
.update({
"metadata.scheduledTime":
admin.firestore.Timestamp.fromMillis(newScheduledTime),
"metadata.jobId": newJob.id,
"metadata.updatedAt": admin.firestore.FieldValue.serverTimestamp(),
});
return newJob;
} catch (error) {
console.error("Error rescheduling post:", error);
throw error;
}
};
const createNotificationJob = async (
userId,
postId,
scheduledTime,
message
) => {
try {
const job = await notificationQueue.add(
{ userId, postId, message },
{
delay: scheduledTime - Date.now(),
attempts: 3,
removeOnComplete: false, // Keep job data for history
}
);
await db
.collection("notifications")
.doc(job.id)
.set({
userId,
postId,
message,
scheduledTime: admin.firestore.Timestamp.fromMillis(scheduledTime),
status: "scheduled",
createdAt: admin.firestore.FieldValue.serverTimestamp(),
});
return job;
} catch (error) {
console.error("Error creating notification job:", error);
throw error;
}
};
const cancelNotificationJob = async (jobId) => {
try {
const job = await notificationQueue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.remove();
await db.collection("notifications").doc(jobId).update({
status: "cancelled",
cancelledAt: admin.firestore.FieldValue.serverTimestamp(),
});
return true;
} catch (error) {
console.error("Error canceling notification:", error);
throw error;
}
};
const rescheduleNotificationJob = async (jobId, newScheduledTime) => {
try {
const job = await notificationQueue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.remove();
const newJob = await createNotificationJob(
job.data.userId,
job.data.postId,
newScheduledTime,
job.data.message
);
await db
.collection("notifications")
.doc(jobId)
.update({
scheduledTime: admin.firestore.Timestamp.fromMillis(newScheduledTime),
status: "scheduled",
rescheduledAt: admin.firestore.FieldValue.serverTimestamp(),
});
return newJob;
} catch (error) {
console.error("Error rescheduling notification:", error);
throw error;
}
};
module.exports = {
createPostJob,
cancelPostJob,
reschedulePostJob,
createNotificationJob,
cancelNotificationJob,
rescheduleNotificationJob,
};