diff --git a/src/libs/actions/Network.ts b/src/libs/actions/Network.ts index 638eef84aff6..6c85edf8e048 100644 --- a/src/libs/actions/Network.ts +++ b/src/libs/actions/Network.ts @@ -1,10 +1,13 @@ +import {differenceInHours} from 'date-fns/differenceInHours'; import Onyx from 'react-native-onyx'; import Log from '@libs/Log'; import type {NetworkStatus} from '@libs/NetworkConnection'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {ConnectionChanges} from '@src/types/onyx/Network'; let isPoorConnectionSimulated: boolean | undefined; +let connectionChanges: ConnectionChanges | undefined; Onyx.connect({ key: ONYXKEYS.NETWORK, callback: (value) => { @@ -20,9 +23,33 @@ Onyx.connect({ } isPoorConnectionSimulated = !!value.shouldSimulatePoorConnection; + connectionChanges = value.connectionChanges; }, }); +function trackConnectionChanges() { + if (!connectionChanges?.startTime) { + Onyx.merge(ONYXKEYS.NETWORK, {connectionChanges: {startTime: new Date().getTime(), amount: 1}}); + return; + } + + const diffInHours = differenceInHours(new Date(), connectionChanges.startTime); + const newAmount = (connectionChanges.amount ?? 0) + 1; + + if (diffInHours < 1) { + Onyx.merge(ONYXKEYS.NETWORK, {connectionChanges: {amount: newAmount}}); + return; + } + + Log.info( + `[NetworkConnection] Connection has changed ${newAmount} time(s) for the last ${diffInHours} hour(s). Poor connection simulation is turned ${ + isPoorConnectionSimulated ? 'on' : 'off' + }`, + ); + + Onyx.merge(ONYXKEYS.NETWORK, {connectionChanges: {startTime: new Date().getTime(), amount: 0}}); +} + function setIsOffline(isOffline: boolean, reason = '') { if (reason) { let textToLog = '[Network] Client is'; @@ -30,6 +57,9 @@ function setIsOffline(isOffline: boolean, reason = '') { textToLog += ` because: ${reason}`; Log.info(textToLog); } + + trackConnectionChanges(); + Onyx.merge(ONYXKEYS.NETWORK, {isOffline}); } diff --git a/src/types/onyx/Network.ts b/src/types/onyx/Network.ts index d834da50cab7..74fb1202a8a2 100644 --- a/src/types/onyx/Network.ts +++ b/src/types/onyx/Network.ts @@ -1,5 +1,14 @@ import type {NetworkStatus} from '@libs/NetworkConnection'; +/** The value where connection changes are tracked */ +type ConnectionChanges = { + /** Amount of connection changes */ + amount?: number; + + /** Start time in milliseconds */ + startTime?: number; +}; + /** Model of network state */ type Network = { /** Is the network currently offline or not */ @@ -14,6 +23,9 @@ type Network = { /** Poor connection timeout id */ poorConnectionTimeoutID?: NodeJS.Timeout; + /** The value where connection changes are tracked */ + connectionChanges?: ConnectionChanges; + /** Whether we should fail all network requests */ shouldFailAllRequests?: boolean; @@ -25,3 +37,4 @@ type Network = { }; export default Network; +export type {ConnectionChanges};