Debian Codegraph @

web/src/app/Poller.js

raw
1 import api from "./Api";
2 import prefs from "./Prefs";
3 import subscriptionManager from "./SubscriptionManager";
4 import { EVENT_MESSAGE, EVENT_MESSAGE_DELETE } from "./events";
5
6 const delayMillis = 2000; // 2 seconds
7 const intervalMillis = 300000; // 5 minutes
8
9 class Poller {
10 constructor() {
11 this.timer = null;
12 }
13
14 startWorker() {
15 if (this.timer !== null) {
16 return;
17 }
18 console.log(`[Poller] Starting worker`);
19 this.timer = setInterval(() => this.pollAll(), intervalMillis);
20 setTimeout(() => this.pollAll(), delayMillis);
21 }
22
23 stopWorker() {
24 clearTimeout(this.timer);
25 }
26
27 async pollAll() {
28 console.log(`[Poller] Polling all subscriptions`);
29 const subscriptions = await subscriptionManager.all();
30
31 await Promise.all(
32 subscriptions.map(async (s) => {
33 try {
34 await this.poll(s);
35 } catch (e) {
36 console.log(`[Poller] Error polling ${s.id}`, e);
37 }
38 }),
39 );
40 }
41
42 async poll(subscription) {
43 console.log(`[Poller] Polling ${subscription.id}`);
44
45 const since = subscription.last;
46 const notifications = await api.poll(subscription.baseUrl, subscription.topic, since);
47
48 // Filter out notifications older than the prune threshold
49 const deleteAfterSeconds = await prefs.deleteAfter();
50 const pruneThresholdTimestamp = deleteAfterSeconds > 0 ? Math.round(Date.now() / 1000) - deleteAfterSeconds : 0;
51 const recentNotifications =
52 pruneThresholdTimestamp > 0 ? notifications.filter((n) => n.time >= pruneThresholdTimestamp) : notifications;
53
54 // Find the latest notification for each sequence ID
55 const latestBySequenceId = this.latestNotificationsBySequenceId(recentNotifications);
56
57 // Delete all existing notifications for which the latest notification is marked as deleted
58 const deletedSequenceIds = Object.entries(latestBySequenceId)
59 .filter(([, notification]) => notification.event === EVENT_MESSAGE_DELETE)
60 .map(([sequenceId]) => sequenceId);
61 if (deletedSequenceIds.length > 0) {
62 console.log(`[Poller] Deleting notifications with deleted sequence IDs for ${subscription.id}`, deletedSequenceIds);
63 await Promise.all(
64 deletedSequenceIds.map((sequenceId) => subscriptionManager.deleteNotificationBySequenceId(subscription.id, sequenceId)),
65 );
66 }
67
68 // Add only the latest notification for each non-deleted sequence
69 const notificationsToAdd = Object.values(latestBySequenceId).filter((n) => n.event === EVENT_MESSAGE);
70 if (notificationsToAdd.length > 0) {
71 console.log(`[Poller] Adding ${notificationsToAdd.length} notification(s) for ${subscription.id}`);
72 await subscriptionManager.addNotifications(subscription.id, notificationsToAdd);
73 } else {
74 console.log(`[Poller] No new notifications found for ${subscription.id}`);
75 }
76 }
77
78 pollInBackground(subscription) {
79 (async () => {
80 try {
81 await this.poll(subscription);
82 } catch (e) {
83 console.error(`[App] Error polling subscription ${subscription.id}`, e);
84 }
85 })();
86 }
87
88 /**
89 * Groups notifications by sequenceId and returns only the latest (highest time) for each sequence.
90 * Returns an object mapping sequenceId -> latest notification.
91 */
92 latestNotificationsBySequenceId(notifications) {
93 const latestBySequenceId = {};
94 notifications.forEach((notification) => {
95 const sequenceId = notification.sequence_id || notification.id;
96 if (!(sequenceId in latestBySequenceId) || notification.time >= latestBySequenceId[sequenceId].time) {
97 latestBySequenceId[sequenceId] = notification;
98 }
99 });
100 return latestBySequenceId;
101 }
102 }
103
104 const poller = new Poller();
105 export default poller;