fix: make UserSyncJob a periodic task

pull/3281/head
Audric Ackermann 5 months ago
parent c3cfd37950
commit 7f1dab1836
No known key found for this signature in database

@ -14,7 +14,6 @@ import { SessionButton, SessionButtonColor, SessionButtonType } from '../../basi
import { StyledModalDescriptionContainer } from '../shared/ModalDescriptionContainer';
import { BlockOrUnblockModalState } from './BlockOrUnblockModalState';
import type { LocalizerComponentPropsObject } from '../../../types/localizer';
import { UserSync } from '../../../session/utils/job_runners/jobs/UserSyncJob';
type ModalState = NonNullable<BlockOrUnblockModalState>;
@ -78,7 +77,6 @@ export const BlockOrUnblockDialog = ({ pubkeys, action, onConfirmed }: NonNullab
}
closeModal();
onConfirmed?.();
await UserSync.queueNewJobIfNeeded();
}, [action, onConfirmed, pubkeys]);
if (isEmpty(pubkeys)) {

@ -214,6 +214,7 @@ const doAppStartUp = async () => {
global.setTimeout(() => {
// Schedule a confSyncJob in some time to let anything incoming from the network be applied and see if there is a push needed
// Note: this also starts periodic jobs, so we don't need to keep doing it
void UserSync.queueNewJobIfNeeded();
}, 20000);
};

@ -34,7 +34,6 @@ async function joinOpenGroup(
const groupCreated = await joinOpenGroupV2WithUIEvents(
serverUrl,
false,
false,
uiCallback,
errorHandler
);

@ -2,7 +2,6 @@ import { useDispatch, useSelector } from 'react-redux';
import useKey from 'react-use/lib/useKey';
import styled from 'styled-components';
import { declineConversationWithoutConfirm } from '../../../interactions/conversationInteractions';
import { forceSyncConfigurationNowIfNeeded } from '../../../session/utils/sync/syncUtils';
import { updateConfirmModal } from '../../../state/ducks/modalDialog';
import { resetLeftOverlayMode } from '../../../state/ducks/section';
import { getConversationRequestsIds } from '../../../state/selectors/conversations';
@ -83,7 +82,6 @@ export const OverlayMessageRequest = () => {
alsoBlock: false,
conversationId: convoId,
currentlySelectedConvo,
syncToDevices: false,
conversationIdOrigin: null, // block is false, no need for conversationIdOrigin
});
} catch (e) {
@ -92,8 +90,6 @@ export const OverlayMessageRequest = () => {
);
}
}
await forceSyncConfigurationNowIfNeeded();
},
onClickClose: () => {
window.inboxStore?.dispatch(updateConfirmModal(null));

@ -8,7 +8,6 @@ import { SpacerLG } from '../../basic/Text';
import { TypingBubble } from '../../conversation/TypingBubble';
import { UserUtils } from '../../../session/utils';
import { UserSync } from '../../../session/utils/job_runners/jobs/UserSyncJob';
import { SessionUtilUserProfile } from '../../../session/utils/libsession/libsession_utils_user_profile';
import {
useHasBlindedMsgRequestsEnabled,
@ -99,7 +98,6 @@ export const SettingsCategoryPrivacy = (props: {
await SessionUtilUserProfile.insertUserProfileIntoWrapper(
UserUtils.getOurPubKeyStrFromCache()
);
await UserSync.queueNewJobIfNeeded();
forceUpdate();
}}
title={window.i18n('messageRequestsCommunities')}

@ -23,9 +23,7 @@ import { PubKey } from '../session/types';
import { perfEnd, perfStart } from '../session/utils/Performance';
import { sleepFor, timeoutWithAbort } from '../session/utils/Promise';
import { ed25519Str, fromHexToArray, toHex } from '../session/utils/String';
import { UserSync } from '../session/utils/job_runners/jobs/UserSyncJob';
import { SessionUtilContact } from '../session/utils/libsession/libsession_utils_contacts';
import { forceSyncConfigurationNowIfNeeded } from '../session/utils/sync/syncUtils';
import {
conversationReset,
quoteMessage,
@ -124,7 +122,6 @@ export const handleAcceptConversationRequest = async ({
// Note: we don't mark as approvedMe = true, as we do not know if they did send us a message yet.
await convo.setIsApproved(true, false);
await convo.commit();
void forceSyncConfigurationNowIfNeeded();
if (convo.isPrivate()) {
// we only need the approval message (and sending a reply) when we are accepting a message request. i.e. someone sent us a message already and we didn't accept it yet.
@ -182,12 +179,10 @@ export async function declineConversationWithoutConfirm({
alsoBlock,
conversationId,
currentlySelectedConvo,
syncToDevices,
conversationIdOrigin,
}: {
conversationId: string;
currentlySelectedConvo: string | undefined;
syncToDevices: boolean;
alsoBlock: boolean;
conversationIdOrigin: string | null;
}) {
@ -249,9 +244,6 @@ export async function declineConversationWithoutConfirm({
});
}
if (syncToDevices) {
await forceSyncConfigurationNowIfNeeded();
}
if (currentlySelectedConvo && currentlySelectedConvo === conversationId) {
window?.inboxStore?.dispatch(resetConversationExternal());
}
@ -259,7 +251,6 @@ export async function declineConversationWithoutConfirm({
export const declineConversationWithConfirm = ({
conversationId,
syncToDevices,
alsoBlock,
currentlySelectedConvo,
conversationIdOrigin,
@ -300,7 +291,6 @@ export const declineConversationWithConfirm = ({
conversationId,
currentlySelectedConvo,
alsoBlock,
syncToDevices,
conversationIdOrigin,
});
},
@ -414,9 +404,7 @@ async function leaveGroupOrCommunityByConvoId({
}
if (isPublic) {
await ConvoHub.use().deleteCommunity(conversationId, {
fromSyncMessage: false,
});
await ConvoHub.use().deleteCommunity(conversationId);
return;
}
// for groups, we have a "leaving..." state that we don't need for communities.
@ -760,7 +748,6 @@ export async function uploadOurAvatar(newAvatarDecrypted?: ArrayBuffer) {
if (newAvatarDecrypted) {
await setLastProfileUpdateTimestamp(Date.now());
await UserSync.queueNewJobIfNeeded();
const userConfigLibsession = await ReleasedFeatures.checkIsUserConfigFeatureReleased();
if (!userConfigLibsession) {

@ -126,7 +126,7 @@ const acceptOpenGroupInvitationV2 = (completeUrl: string, roomName?: string) =>
},
},
onClickOk: async () => {
await joinOpenGroupV2WithUIEvents(completeUrl, true, false);
await joinOpenGroupV2WithUIEvents(completeUrl, true);
},
onClickClose,

@ -74,7 +74,6 @@ import {
MessageRequestResponse,
MessageRequestResponseParams,
} from '../session/messages/outgoing/controlMessage/MessageRequestResponse';
import { UserSync } from '../session/utils/job_runners/jobs/UserSyncJob';
import { SessionUtilContact } from '../session/utils/libsession/libsession_utils_contacts';
import { SessionUtilConvoInfoVolatile } from '../session/utils/libsession/libsession_utils_convo_info_volatile';
import { SessionUtilUserGroups } from '../session/utils/libsession/libsession_utils_user_groups';
@ -94,7 +93,6 @@ import {
} from '../types/sqlSharedTypes';
import { Notifications } from '../util/notifications';
import { Reactions } from '../util/reactions';
import { Registration } from '../util/registration';
import { Storage } from '../util/storage';
import {
ConversationAttributes,
@ -2754,11 +2752,6 @@ async function commitConversationAndRefreshWrapper(id: string) {
}
}
if (Registration.isDone()) {
// save the new dump if needed to the DB asap
// this call throttled so we do not run this too often (and not for every .commit())
await UserSync.queueNewJobIfNeeded();
}
convo.triggerUIRefresh();
}

@ -15,7 +15,6 @@ import { PubKey } from '../session/types';
import { StringUtils, UserUtils } from '../session/utils';
import { toHex } from '../session/utils/String';
import { FetchMsgExpirySwarm } from '../session/utils/job_runners/jobs/FetchMsgExpirySwarmJob';
import { UserSync } from '../session/utils/job_runners/jobs/UserSyncJob';
import { LibSessionUtil } from '../session/utils/libsession/libsession_utils';
import { SessionUtilContact } from '../session/utils/libsession/libsession_utils_contacts';
import { SessionUtilConvoInfoVolatile } from '../session/utils/libsession/libsession_utils_convo_info_volatile';
@ -506,9 +505,7 @@ async function handleCommunitiesUpdate() {
for (let index = 0; index < communitiesToLeaveInDB.length; index++) {
const toLeave = communitiesToLeaveInDB[index];
window.log.info('leaving community with convoId ', toLeave.id);
await ConvoHub.use().deleteCommunity(toLeave.id, {
fromSyncMessage: true,
});
await ConvoHub.use().deleteCommunity(toLeave.id);
}
// this call can take quite a long time but must be awaited (as it is async and create the entry in the DB, used as a diff)
@ -978,7 +975,6 @@ async function processUserMergingResults(results: Map<ConfigWrapperUser, Incomin
}
const keys = [...results.keys()];
let anyNeedsPush = false;
for (let index = 0; index < keys.length; index++) {
const wrapperType = keys[index];
const incomingResult = results.get(wrapperType);
@ -1031,20 +1027,11 @@ async function processUserMergingResults(results: Map<ConfigWrapperUser, Incomin
variant,
});
}
if (incomingResult.needsPush) {
anyNeedsPush = true;
}
} catch (e) {
window.log.error(`processMergingResults failed with ${e.message}`);
return;
}
}
// Now that the local state has been updated, trigger a config sync (this will push any
// pending updates and properly update the state)
if (anyNeedsPush) {
await UserSync.queueNewJobIfNeeded();
}
}
async function handleUserConfigMessagesViaLibSession(

@ -17,7 +17,6 @@ import { UserUtils } from '../../session/utils';
import { sleepFor } from '../../session/utils/Promise';
import { ed25519Str, stringToUint8Array } from '../../session/utils/String';
import { PreConditionFailed } from '../../session/utils/errors';
import { UserSync } from '../../session/utils/job_runners/jobs/UserSyncJob';
import { LibSessionUtil } from '../../session/utils/libsession/libsession_utils';
import { SessionUtilConvoInfoVolatile } from '../../session/utils/libsession/libsession_utils_convo_info_volatile';
import { groupInfoActions } from '../../state/ducks/metaGroups';
@ -197,7 +196,6 @@ async function handleGroupUpdateInviteMessage({
}
await LibSessionUtil.saveDumpsToDb(UserUtils.getOurPubKeyStrFromCache());
await UserSync.queueNewJobIfNeeded();
if (!found.invitePending) {
// if this group should already be polling based on if that author is pre-approved or we've already approved that group from another device.
getSwarmPollingInstance().addGroupId(groupPk, async () => {
@ -620,7 +618,6 @@ async function handleGroupUpdatePromoteMessage({
}
await LibSessionUtil.saveDumpsToDb(UserUtils.getOurPubKeyStrFromCache());
await UserSync.queueNewJobIfNeeded();
if (!found.invitePending) {
// This group should already be polling based on if that author is pre-approved or we've already approved that group from another device.
// Start polling from it, we will mark ourselves as admin once we get the first merge result, if needed.

@ -3,7 +3,6 @@ import { ConversationModel } from '../../../../models/conversation';
import { ConvoHub } from '../../../conversations';
import { PromiseUtils, ToastUtils } from '../../../utils';
import { forceSyncConfigurationNowIfNeeded } from '../../../utils/sync/syncUtils';
import {
getOpenGroupV2ConversationId,
openGroupV2CompleteURLRegex,
@ -56,10 +55,7 @@ export function parseOpenGroupV2(urlWithPubkey: string): OpenGroupV2Room | undef
* @param room The room id to join
* @param publicKey The server publicKey. It comes from the joining link. (or is already here for the default open group server)
*/
async function joinOpenGroupV2(
room: OpenGroupV2Room,
fromConfigMessage: boolean
): Promise<ConversationModel | undefined> {
async function joinOpenGroupV2(room: OpenGroupV2Room): Promise<ConversationModel | undefined> {
if (!room.serverUrl || !room.roomId || room.roomId.length < 1 || !room.serverPublicKey) {
return undefined;
}
@ -81,9 +77,7 @@ async function joinOpenGroupV2(
// we already have a convo associated with it. Remove everything related to it so we start fresh
window?.log?.warn('leaving before rejoining open group v2 room', conversationId);
await ConvoHub.use().deleteCommunity(conversationId, {
fromSyncMessage: true,
});
await ConvoHub.use().deleteCommunity(conversationId);
}
// Try to connect to server
@ -98,11 +92,6 @@ async function joinOpenGroupV2(
throw new Error(window.i18n('communityJoinError'));
}
// here we managed to connect to the group.
// if this is not a Sync Message, we should trigger one
if (!fromConfigMessage) {
await forceSyncConfigurationNowIfNeeded();
}
return conversation;
} catch (e) {
window?.log?.error('Could not join open group v2', e.message);
@ -132,7 +121,6 @@ export type JoinSogsRoomUICallbackArgs = {
export async function joinOpenGroupV2WithUIEvents(
completeUrl: string,
showToasts: boolean,
fromConfigMessage: boolean,
uiCallback?: (args: JoinSogsRoomUICallbackArgs) => void,
errorHandler?: (error: string) => void
): Promise<boolean> {
@ -174,7 +162,7 @@ export async function joinOpenGroupV2WithUIEvents(
uiCallback?.({ loadingState: 'started', conversationKey: conversationID });
const convoCreated = await joinOpenGroupV2(parsedRoom, fromConfigMessage);
const convoCreated = await joinOpenGroupV2(parsedRoom);
if (convoCreated) {
if (showToasts) {

@ -148,9 +148,7 @@ export async function getAllValidOpenGroupV2ConversationRoomInfos() {
/* eslint-disable no-await-in-loop */
await OpenGroupData.removeV2OpenGroupRoom(roomConvoId);
getOpenGroupManager().removeRoomFromPolledRooms(infos);
await ConvoHub.use().deleteCommunity(roomConvoId, {
fromSyncMessage: false,
});
await ConvoHub.use().deleteCommunity(roomConvoId);
/* eslint-enable no-await-in-loop */
}
} catch (e) {

@ -38,7 +38,6 @@ import { ed25519Str } from '../utils/String';
import { PreConditionFailed } from '../utils/errors';
import { RunJobResult } from '../utils/job_runners/PersistedJob';
import { GroupSync } from '../utils/job_runners/jobs/GroupSyncJob';
import { UserSync } from '../utils/job_runners/jobs/UserSyncJob';
import { LibSessionUtil } from '../utils/libsession/libsession_utils';
import { SessionUtilContact } from '../utils/libsession/libsession_utils_contacts';
import { SessionUtilConvoInfoVolatile } from '../utils/libsession/libsession_utils_convo_info_volatile';
@ -248,7 +247,6 @@ class ConvoController {
// we never keep a left legacy group. Only fully remove it.
await this.removeGroupOrCommunityFromDBAndRedux(groupPk);
await UserSync.queueNewJobIfNeeded();
}
public async deleteGroup(
@ -392,10 +390,9 @@ class ConvoController {
getSwarmPollingInstance().removePubkey(groupPk, 'deleteGroup');
window.inboxStore?.dispatch(groupInfoActions.removeGroupDetailsFromSlice({ groupPk }));
await UserSync.queueNewJobIfNeeded();
}
public async deleteCommunity(convoId: string, options: DeleteOptions) {
public async deleteCommunity(convoId: string) {
const conversation = await this.deleteConvoInitialChecks(convoId, 'Community', false);
if (!conversation || !conversation.isPublic()) {
return;
@ -408,10 +405,6 @@ class ConvoController {
}
await removeCommunityFromWrappers(conversation.id); // this call needs to fetch the pubkey
await this.removeGroupOrCommunityFromDBAndRedux(conversation.id);
if (!options.fromSyncMessage) {
await UserSync.queueNewJobIfNeeded();
}
}
public async delete1o1(
@ -454,10 +447,6 @@ class ConvoController {
window.inboxStore?.dispatch(resetConversationExternal());
}
}
if (!options.fromSyncMessage) {
await UserSync.queueNewJobIfNeeded();
}
}
/**

@ -13,7 +13,6 @@ import {
} from '../messages/outgoing/controlMessage/group/ClosedGroupNewMessage';
import { PubKey } from '../types';
import { UserUtils } from '../utils';
import { forceSyncConfigurationNowIfNeeded } from '../utils/sync/syncUtils';
import { ConvoHub } from './ConversationController';
import { ConversationTypeEnum } from '../../models/types';
import { NetworkTime } from '../../util/NetworkTime';
@ -90,8 +89,6 @@ export async function createClosedGroup(groupName: string, members: Array<string
// commit again as now the keypair is saved and can be added to the libsession wrapper UserGroup
await convo.commit();
await forceSyncConfigurationNowIfNeeded();
await openConversationWithMessages({ conversationKey: groupPublicKey, messageId: null });
}

@ -229,6 +229,8 @@ class UserSyncJob extends PersistedJob<UserSyncPersistedData> {
}
}
let interval: NodeJS.Timeout | undefined;
/**
* Queue a new Sync Configuration if needed job.
* A UserSyncJob can only be added if there is none of the same type queued already.
@ -239,6 +241,10 @@ async function queueNewJobIfNeeded() {
return;
}
// let's schedule periodic UserConfig jobs so we don't need to always remember to call UserSync.queueNewJobIfNeeded
if (!interval) {
interval = global.setInterval(() => void queueNewJobIfNeeded(), defaultMsBetweenRetries);
}
if (
!lastRunConfigSyncJobTimestamp ||
lastRunConfigSyncJobTimestamp < Date.now() - defaultMsBetweenRetries

@ -23,7 +23,6 @@ import {
NotEmptyArrayOfBatchResults,
} from '../../apis/snode_api/SnodeRequestTypes';
import { PubKey } from '../../types';
import { UserSync } from '../job_runners/jobs/UserSyncJob';
import { ed25519Str } from '../String';
const requiredUserVariants: Array<ConfigWrapperUser> = [
@ -42,8 +41,6 @@ async function initializeLibSessionUtilWrappers() {
throw new Error('edkeypair not found for current user');
}
const privateKeyEd25519 = keypair.privKeyBytes;
// let's plan a sync on start with some room for the app to be ready
setTimeout(() => UserSync.queueNewJobIfNeeded, 20000);
// fetch the dumps we already have from the database
const dumps = await ConfigDumpData.getAllDumpsWithData();

@ -28,7 +28,6 @@ import { PreConditionFailed } from '../../session/utils/errors';
import { GroupInvite } from '../../session/utils/job_runners/jobs/GroupInviteJob';
import { GroupPendingRemovals } from '../../session/utils/job_runners/jobs/GroupPendingRemovalsJob';
import { GroupSync } from '../../session/utils/job_runners/jobs/GroupSyncJob';
import { UserSync } from '../../session/utils/job_runners/jobs/UserSyncJob';
import { RunJobResult } from '../../session/utils/job_runners/PersistedJob';
import { LibSessionUtil } from '../../session/utils/libsession/libsession_utils';
import { ed25519Str } from '../../session/utils/String';
@ -871,8 +870,6 @@ async function handleNameChangeFromUI({
);
}
await UserSync.queueNewJobIfNeeded();
convo.set({
active_at: createAtNetworkTimestamp,
});

Loading…
Cancel
Save