Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defer local updates if there are missing updates and only call GetMissingOnyxMessages once #38997

Merged
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
d32cd8b
defer updates if missing updates are fetched
chrispader Mar 26, 2024
e41558e
simplify
chrispader Mar 26, 2024
931527c
move deferred updates out of callback
chrispader Mar 26, 2024
5088441
simplify comments
chrispader Mar 26, 2024
9954e40
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Mar 26, 2024
a314f1f
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Mar 26, 2024
9d818d3
fix: apply deferred updates in order
chrispader Mar 26, 2024
f21ea78
simplify and improve applying deferred updates
chrispader Mar 27, 2024
3cc017e
check if deferred updates are older than the currently applied one
chrispader Mar 27, 2024
ce9027c
improve code
chrispader Mar 27, 2024
9889206
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Mar 27, 2024
c3034e0
fix: refetching logic
chrispader Mar 29, 2024
b9afdf3
fix: comments and logic
chrispader Mar 29, 2024
6a5c922
restructure file
chrispader Apr 1, 2024
4f35d1e
fix: re-write to detect possible multiple gaps in the deferred updates
chrispader Apr 1, 2024
095f09e
simplified conditions
chrispader Apr 1, 2024
6c748ac
further improve comments
chrispader Apr 1, 2024
b5deb28
fix: minor problems
chrispader Apr 2, 2024
2d08786
remove unnecessary code
chrispader Apr 2, 2024
25c8623
improve comment
chrispader Apr 2, 2024
7769810
fix: check for queryPromise
chrispader Apr 2, 2024
47613cf
update comment
chrispader Apr 2, 2024
fb9ac39
update comment
chrispader Apr 2, 2024
b9692d1
move lines
chrispader Apr 2, 2024
af920cd
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Apr 2, 2024
2514772
fix: comments
chrispader Apr 2, 2024
dab2b9f
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Apr 2, 2024
c0fe364
fix: wrong early return
chrispader Apr 2, 2024
252f0ab
fix: missing return
chrispader Apr 2, 2024
c1ca79b
Revert "fix: missing return"
chrispader Apr 2, 2024
67f322e
Update OnyxUpdateManager.ts
chrispader Apr 2, 2024
cd48514
Merge branch 'main' into @chrispader/prevent-simultaneous-calls-to-Ge…
chrispader Apr 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 152 additions & 10 deletions src/libs/actions/OnyxUpdateManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Log from '@libs/Log';
import * as SequentialQueue from '@libs/Network/SequentialQueue';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {OnyxUpdatesFromServer, Response} from '@src/types/onyx';
import * as App from './App';
import * as OnyxUpdates from './OnyxUpdates';

Expand All @@ -27,6 +28,134 @@ Onyx.connect({
callback: (value) => (lastUpdateIDAppliedToClient = value),
});

let queryPromise: Promise<Response | Response[] | void> | undefined;

type DeferredUpdatesDictionary = Record<number, OnyxUpdatesFromServer>;
let deferredUpdates: DeferredUpdatesDictionary = {};

// This function will reset the query variables, unpause the SequentialQueue and log an info to the user.
function finalizeUpdatesAndResumeQueue() {
console.debug('[OnyxUpdateManager] Done applying all updates');
queryPromise = undefined;
deferredUpdates = {};
Onyx.set(ONYXKEYS.ONYX_UPDATES_FROM_SERVER, null);
SequentialQueue.unpause();
}

// This function applies a list of updates to Onyx in order and resolves when all updates have been applied
const applyUpdates = (updates: DeferredUpdatesDictionary) => Promise.all(Object.values(updates).map((update) => OnyxUpdates.apply(update)));

// In order for the deferred updates to be applied correctly in order,
// we need to check if there are any gaps between deferred updates.
type DetectGapAndSplitResult = {applicableUpdates: DeferredUpdatesDictionary; updatesAfterGaps: DeferredUpdatesDictionary; latestMissingUpdateID: number | undefined};
function detectGapsAndSplit(updates: DeferredUpdatesDictionary): DetectGapAndSplitResult {
Copy link
Contributor

@eh2077 eh2077 Apr 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a few examples or test cases here will be very helpful to understand the code.

const updateValues = Object.values(updates);
chrispader marked this conversation as resolved.
Show resolved Hide resolved
const applicableUpdates: DeferredUpdatesDictionary = {};

let gapExists = false;
let firstUpdateAfterGaps: number | undefined;
let latestMissingUpdateID: number | undefined;

for (const [index, update] of updateValues.entries()) {
const isFirst = index === 0;

// If any update's previousUpdateID doesn't match the lastUpdateID from the previous update, the deferred updates aren't chained and there's a gap.
// For the first update, we need to check that the previousUpdateID of the fetched update is the same as the lastUpdateIDAppliedToClient.
// For any other updates, we need to check if the previousUpdateID of the current update is found in the deferred updates.
// If an update is chained, we can add it to the applicable updates.
const isChained = isFirst ? update.previousUpdateID === lastUpdateIDAppliedToClient : !!updates[Number(update.previousUpdateID)];
if (isChained) {
// If a gap exists already, we will not add any more updates to the applicable updates.
// Instead, once there are two chained updates again, we can set "firstUpdateAfterGaps" to the first update after the current gap.
if (gapExists) {
// If "firstUpdateAfterGaps" hasn't been set yet and there was a gap, we need to set it to the first update after all gaps.
if (!firstUpdateAfterGaps) {
firstUpdateAfterGaps = Number(update.previousUpdateID);
}
} else {
// If no gap exists yet, we can add the update to the applicable updates
applicableUpdates[Number(update.lastUpdateID)] = update;
}
} else {
// When we find a (new) gap, we need to set "gapExists" to true and reset the "firstUpdateAfterGaps" variable,
// so that we can continue searching for the next update after all gaps
gapExists = true;
firstUpdateAfterGaps = undefined;
chrispader marked this conversation as resolved.
Show resolved Hide resolved

// If there is a gap, it means the previous update is the latest missing update.
latestMissingUpdateID = Number(update.previousUpdateID);
}
}

// When "firstUpdateAfterGaps" is not set yet, we need to set it to the last update in the list,
// because we will fetch all missing updates up to the previous one and can then always apply the last update in the deferred updates.
if (!firstUpdateAfterGaps) {
firstUpdateAfterGaps = Number(updateValues[updateValues.length - 1].lastUpdateID);
}

let updatesAfterGaps: DeferredUpdatesDictionary = {};
if (gapExists && firstUpdateAfterGaps) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
updatesAfterGaps = Object.fromEntries(Object.entries(updates).filter(([lastUpdateID]) => Number(lastUpdateID) >= firstUpdateAfterGaps!));
}

return {applicableUpdates, updatesAfterGaps, latestMissingUpdateID};
}

// This function will check for gaps in the deferred updates and
// apply the updates in order after the missing updates are fetched and applied
function validateAndApplyDeferredUpdates(): Promise<Response[] | void> {
// We only want to apply deferred updates that are newer than the last update that was applied to the client.
// At this point, the missing updates from "GetMissingOnyxUpdates" have been applied already, so we can safely filter out.
const pendingDeferredUpdates = Object.fromEntries(
Object.entries(deferredUpdates).filter(([lastUpdateID]) => {
// It should not be possible for lastUpdateIDAppliedToClient to be null,
// after the missing updates have been applied.
// If still so we want to keep the deferred update in the list.
if (!lastUpdateIDAppliedToClient) {
return true;
}
return (Number(lastUpdateID) ?? 0) > lastUpdateIDAppliedToClient;
}),
);

// If there are no remaining deferred updates after filtering out outdated ones,
// we can just unpause the queue and return
if (Object.values(pendingDeferredUpdates).length === 0) {
return Promise.resolve();
}

const {applicableUpdates, updatesAfterGaps, latestMissingUpdateID} = detectGapsAndSplit(pendingDeferredUpdates);

// If we detected a gap in the deferred updates, only apply the deferred updates before the gap,
// re-fetch the missing updates and then apply the remaining deferred updates after the gap
if (latestMissingUpdateID) {
return new Promise((resolve, reject) => {
deferredUpdates = {};
applyUpdates(applicableUpdates).then(() => {
// After we have applied the applicable updates, there might have been new deferred updates added.
// In the next (recursive) call of "validateAndApplyDeferredUpdates",
// the initial "updatesAfterGaps" and all new deferred updates will be applied in order,
// as long as there was no new gap detected. Otherwise repeat the process.
deferredUpdates = {...deferredUpdates, ...updatesAfterGaps};

// It should not be possible for lastUpdateIDAppliedToClient to be null, therefore we can ignore this case.
// If lastUpdateIDAppliedToClient got updated in the meantime, we will just retrigger the validation and application of the current deferred updates.
if (!lastUpdateIDAppliedToClient || latestMissingUpdateID <= lastUpdateIDAppliedToClient) {
validateAndApplyDeferredUpdates().then(resolve).catch(reject);
return;
}

// Then we can fetch the missing updates and apply them
App.getMissingOnyxUpdates(lastUpdateIDAppliedToClient, latestMissingUpdateID).then(validateAndApplyDeferredUpdates).then(resolve).catch(reject);
});
});
}

// If there are no gaps in the deferred updates, we can apply all deferred updates in order
return applyUpdates(applicableUpdates);
}

export default () => {
console.debug('[OnyxUpdateManager] Listening for updates from the server');
Onyx.connect({
Expand Down Expand Up @@ -66,32 +195,45 @@ export default () => {
// applied in their correct and specific order. If this queue was not paused, then there would be a lot of
// onyx data being applied while we are fetching the missing updates and that would put them all out of order.
SequentialQueue.pause();
let canUnpauseQueuePromise;

// The flow below is setting the promise to a reconnect app to address flow (1) explained above.
if (!lastUpdateIDAppliedToClient) {
// If there is a ReconnectApp query in progress, we should not start another one.
if (queryPromise) {
return;
}

Log.info('Client has not gotten reliable updates before so reconnecting the app to start the process');

// Since this is a full reconnectApp, we'll not apply the updates we received - those will come in the reconnect app request.
canUnpauseQueuePromise = App.finalReconnectAppAfterActivatingReliableUpdates();
queryPromise = App.finalReconnectAppAfterActivatingReliableUpdates();
} else {
// The flow below is setting the promise to a getMissingOnyxUpdates to address flow (2) explained above.

// Get the number of deferred updates before adding the new one
const existingDeferredUpdatesCount = Object.keys(deferredUpdates).length;

// Add the new update to the deferred updates
chrispader marked this conversation as resolved.
Show resolved Hide resolved
deferredUpdates[Number(updateParams.lastUpdateID)] = updateParams;

// If there are deferred updates already, we don't need to fetch the missing updates again.
if (existingDeferredUpdatesCount > 0) {
return;
}

console.debug(`[OnyxUpdateManager] Client is behind the server by ${Number(previousUpdateIDFromServer) - lastUpdateIDAppliedToClient} so fetching incremental updates`);
Log.info('Gap detected in update IDs from server so fetching incremental updates', true, {
lastUpdateIDFromServer,
previousUpdateIDFromServer,
lastUpdateIDAppliedToClient,
});
canUnpauseQueuePromise = App.getMissingOnyxUpdates(lastUpdateIDAppliedToClient, previousUpdateIDFromServer);

// Get the missing Onyx updates from the server and afterwards validate and apply the deferred updates.
// This will trigger recursive calls to "validateAndApplyDeferredUpdates" if there are gaps in the deferred updates.
queryPromise = App.getMissingOnyxUpdates(lastUpdateIDAppliedToClient, previousUpdateIDFromServer).then(validateAndApplyDeferredUpdates);
}

canUnpauseQueuePromise.finally(() => {
OnyxUpdates.apply(updateParams).finally(() => {
console.debug('[OnyxUpdateManager] Done applying all updates');
Onyx.set(ONYXKEYS.ONYX_UPDATES_FROM_SERVER, null);
SequentialQueue.unpause();
});
});
queryPromise.finally(finalizeUpdatesAndResumeQueue);
},
});
};
Loading