Fallback to polling if streaming fails

This commit is contained in:
Lim Chee Aun 2023-11-01 21:31:43 +08:00
parent 33f807de73
commit 7119a78711

View file

@ -13,19 +13,17 @@ export default memo(function BackgroundService({ isLoggedIn }) {
// - WebSocket to receive notifications when page is visible
const [visible, setVisible] = useState(true);
usePageVisibility(setVisible);
useEffect(() => {
let sub;
if (isLoggedIn && visible) {
const { masto, streaming, instance } = api();
(async () => {
// 1. Get the latest notification
const checkLatestNotification = async (masto, instance, skipCheckMarkers) => {
if (states.notificationsLast) {
const notificationsIterator = masto.v1.notifications.list({
limit: 1,
since_id: states.notificationsLast.id,
sinceId: states.notificationsLast.id,
});
const { value: notifications } = await notificationsIterator.next();
if (notifications?.length) {
if (skipCheckMarkers) {
states.notificationsShowNew = true;
} else {
let lastReadId;
try {
const markers = await masto.v1.markers.fetch({
@ -40,9 +38,23 @@ export default memo(function BackgroundService({ isLoggedIn }) {
}
}
}
}
};
useEffect(() => {
let sub;
let pollNotifications;
if (isLoggedIn && visible) {
const { masto, streaming, instance } = api();
(async () => {
// 1. Get the latest notification
await checkLatestNotification(masto, instance);
let hasStreaming = false;
// 2. Start streaming
if (streaming) {
try {
hasStreaming = true;
sub = streaming.user.notification.subscribe();
console.log('🎏 Streaming notification', sub);
for await (const entry of sub) {
@ -56,12 +68,25 @@ export default memo(function BackgroundService({ isLoggedIn }) {
}
states.notificationsShowNew = true;
}
} catch (e) {
hasStreaming = false;
console.error(e);
}
}
if (!hasStreaming) {
console.log('🎏 Streaming failed, fallback to polling');
// Fallback to polling every minute
pollNotifications = setInterval(() => {
checkLatestNotification(masto, instance, true);
}, 1000 * 60);
}
})();
}
return () => {
sub?.unsubscribe?.();
sub = null;
clearInterval(pollNotifications);
};
}, [visible, isLoggedIn]);