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 // - WebSocket to receive notifications when page is visible
const [visible, setVisible] = useState(true); const [visible, setVisible] = useState(true);
usePageVisibility(setVisible); usePageVisibility(setVisible);
useEffect(() => { const checkLatestNotification = async (masto, instance, skipCheckMarkers) => {
let sub;
if (isLoggedIn && visible) {
const { masto, streaming, instance } = api();
(async () => {
// 1. Get the latest notification
if (states.notificationsLast) { if (states.notificationsLast) {
const notificationsIterator = masto.v1.notifications.list({ const notificationsIterator = masto.v1.notifications.list({
limit: 1, limit: 1,
since_id: states.notificationsLast.id, sinceId: states.notificationsLast.id,
}); });
const { value: notifications } = await notificationsIterator.next(); const { value: notifications } = await notificationsIterator.next();
if (notifications?.length) { if (notifications?.length) {
if (skipCheckMarkers) {
states.notificationsShowNew = true;
} else {
let lastReadId; let lastReadId;
try { try {
const markers = await masto.v1.markers.fetch({ 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 // 2. Start streaming
if (streaming) { if (streaming) {
try {
hasStreaming = true;
sub = streaming.user.notification.subscribe(); sub = streaming.user.notification.subscribe();
console.log('🎏 Streaming notification', sub); console.log('🎏 Streaming notification', sub);
for await (const entry of sub) { for await (const entry of sub) {
@ -56,12 +68,25 @@ export default memo(function BackgroundService({ isLoggedIn }) {
} }
states.notificationsShowNew = true; 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 () => { return () => {
sub?.unsubscribe?.(); sub?.unsubscribe?.();
sub = null; sub = null;
clearInterval(pollNotifications);
}; };
}, [visible, isLoggedIn]); }, [visible, isLoggedIn]);