From b6e477bccdef6f1e383c7f19965377b8262cf1c5 Mon Sep 17 00:00:00 2001 From: pandeymangg Date: Fri, 4 Dec 2026 11:20:49 +0530 Subject: [PATCH 1/2] fix: finish setup when the /user sync fails, keeping the saved user [ENG-7681] A failed /user sync at setup returned early, so setup never finished and every track was dropped until the app restarted. Keep the saved user state, push its expiry 30 minutes ahead and finish setup (ENG-7620 #9). --- packages/react-native/src/lib/common/setup.ts | 33 ++--- .../src/lib/common/tests/setup.test.ts | 121 ++++++++++++------ 2 files changed, 90 insertions(+), 64 deletions(-) diff --git a/packages/react-native/src/lib/common/setup.ts b/packages/react-native/src/lib/common/setup.ts index f4addc7..77058af 100644 --- a/packages/react-native/src/lib/common/setup.ts +++ b/packages/react-native/src/lib/common/setup.ts @@ -89,14 +89,14 @@ async function syncUserStateIfExpired( configInput: { appUrl: string; workspaceId: string }, logger: ReturnType, existingConfig?: TConfig, -): Promise> { +): Promise { const userState = existingConfig?.user; if (userState && !userState.expiresAt) { - return ok(userState); + return userState; } if (userState?.expiresAt && !isNowExpired(userState.expiresAt)) { - return ok(userState); + return userState; } logger.debug("Person state expired. Syncing."); @@ -110,24 +110,20 @@ async function syncUserStateIfExpired( }, }); if (updatesResponse.ok) { - return ok(updatesResponse.data.state); + return updatesResponse.data.state; } logger.error( `Error updating user state: ${updatesResponse.error.code} - ${updatesResponse.error.responseMessage ?? ""}`, ); - return err({ - code: "network_error", - message: "Error updating user state", - status: 500, - url: new URL( - `${configInput.appUrl}/api/v2/client/${configInput.workspaceId}/user`, - ), - responseMessage: "Unknown error", - } as const); + // A failed sync must not stop setup: keep the saved user and try again in 30 minutes. + return { + ...userState, + expiresAt: new Date(Date.now() + 30 * 60000), + }; } - return ok(DEFAULT_USER_STATE_NO_USER_ID); + return DEFAULT_USER_STATE_NO_USER_ID; } // Helper: Update app config with synced states @@ -313,7 +309,6 @@ export const setup = async ( if (shouldSyncConfig(existingConfig, resolvedInput)) { logger.debug("Configuration fits setup parameters."); let workspace: TWorkspaceState | undefined; - let userState: TUserState | undefined; try { const workspaceResult = await syncWorkspaceStateIfExpired( @@ -328,18 +323,12 @@ export const setup = async ( return err(workspaceResult.error); } - const userStateResult = await syncUserStateIfExpired( + const userState = await syncUserStateIfExpired( resolvedInput, logger, existingConfig, ); - if (userStateResult.ok) { - userState = userStateResult.data; - } else { - return err(userStateResult.error); - } - updateAppConfigWithSyncedStates( appConfig, workspace, diff --git a/packages/react-native/src/lib/common/tests/setup.test.ts b/packages/react-native/src/lib/common/tests/setup.test.ts index f70b44c..31881de 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -9,6 +9,7 @@ import { test, vi, } from "vitest"; +import { CommandQueue } from "@/lib/common/command-queue"; import { RN_ASYNC_STORAGE_KEY, RNConfig } from "@/lib/common/config"; import { addCleanupEventListeners, @@ -25,9 +26,13 @@ import { } from "@/lib/common/setup"; import type * as CommonUtilsModule from "@/lib/common/utils"; import { filterSurveys, isNowExpired } from "@/lib/common/utils"; +import { trackAction } from "@/lib/survey/action"; +import { SurveyStore } from "@/lib/survey/store"; import { DEFAULT_USER_STATE_NO_USER_ID } from "@/lib/user/state"; import { sendUpdatesToBackend } from "@/lib/user/update"; import { fetchWorkspaceState } from "@/lib/workspace/state"; +import type { TUserState, TWorkspaceState } from "@/types/config"; +import type { TSurvey } from "@/types/survey"; // 1) Mock AsyncStorage vi.mock("@react-native-async-storage/async-storage", () => ({ @@ -88,6 +93,11 @@ vi.mock("@/lib/user/update", () => ({ sendUpdatesToBackend: vi.fn(), })); +// 8) Mock netinfo, which the survey action module imports +vi.mock("@react-native-community/netinfo", () => ({ + fetch: vi.fn(), +})); + describe("setup.ts", () => { let getInstanceConfigMock: MockInstance<() => Promise>; let getInstanceLoggerMock: MockInstance<() => Logger>; @@ -468,57 +478,84 @@ describe("setup.ts", () => { expect(sendUpdatesToBackend).not.toHaveBeenCalled(); }); - test("returns an error when user sync fails", async () => { - const mockConfig = { - get: vi.fn().mockReturnValue({ + test("finishes setup with the saved user when the user sync fails, so track can show a survey", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + try { + const now = new Date("2026-01-01T12:00:00Z"); + vi.setSystemTime(now); + + const survey = { + id: "survey_1", + displayPercentage: null, + triggers: [{ actionClass: { name: "checkout" } }], + } as unknown as TSurvey; + const savedUser: TUserState = { + data: { + userId: "user_abc", + contactId: "contact_abc", + segments: ["segment_1"], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() - 5000), + }; + let storedConfig = { workspaceId: "env_123", appUrl: "https://my.url", workspace: { - data: { surveys: [] }, - expiresAt: new Date(Date.now() + 60_000), - }, - user: { - data: { - userId: "user_abc", - contactId: null, - segments: [], - displays: [], - responses: [], - lastDisplayAt: null, - }, - expiresAt: new Date(Date.now() - 5000), + data: { surveys: [survey], actionClasses: [] }, + expiresAt: new Date(now.getTime() + 60_000), }, + user: savedUser, filteredSurveys: [], status: { value: "success", expiresAt: null }, - }), - update: vi.fn(), - }; + }; + const mockConfig = { + get: vi.fn(() => storedConfig), + update: vi.fn((next: typeof storedConfig) => { + storedConfig = next; + }), + }; - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); - (isNowExpired as unknown as Mock) - .mockReturnValueOnce(false) - .mockReturnValueOnce(true); - (sendUpdatesToBackend as unknown as Mock).mockResolvedValueOnce({ - ok: false, - error: { - code: "network_error", - message: "User sync failed", - }, - }); + getInstanceConfigMock.mockReturnValue( + mockConfig as unknown as Promise, + ); + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + (filterSurveys as unknown as Mock).mockImplementation( + (workspace: TWorkspaceState) => workspace.data.surveys, + ); + (sendUpdatesToBackend as unknown as Mock).mockResolvedValueOnce({ + ok: false, + error: { code: "network_error", message: "User sync failed" }, + }); - const result = await setup({ - environmentId: "env_123", - appUrl: "https://my.url", - }); + const result = await setup({ + workspaceId: "env_123", + appUrl: "https://my.url", + }); - expect(result.ok).toBe(false); - if (!result.ok) { - expect(result.error.code).toBe("network_error"); - expect("message" in result.error && result.error.message).toBe( - "Error updating user state", - ); + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).toHaveBeenCalledTimes(1); + // The saved user is kept and its expiry is pushed 30 min ahead. + expect(storedConfig.user).toEqual({ + data: savedUser.data, + expiresAt: new Date(now.getTime() + 30 * 60_000), + }); + + const queue = new CommandQueue(); + queue.add(trackAction, true, "checkout"); + await queue.wait(); + + expect(SurveyStore.getInstance().getSurvey()).toBe(survey); + } finally { + SurveyStore.getInstance().resetSurvey(); + (isNowExpired as unknown as Mock).mockReset(); + vi.useRealTimers(); } }); From 3118afbe7c0476783b306b150dcdd6698ac22f7f Mon Sep 17 00:00:00 2001 From: pandeymangg Date: Fri, 4 Dec 2026 13:25:58 +0530 Subject: [PATCH 2/2] test: cover setup keeping a fresh saved user and resetting one without a userId [ENG-7681] --- .../src/lib/common/tests/setup.test.ts | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/packages/react-native/src/lib/common/tests/setup.test.ts b/packages/react-native/src/lib/common/tests/setup.test.ts index 31881de..f5c60be 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -559,6 +559,92 @@ describe("setup.ts", () => { } }); + describe("saved user state at setup", () => { + const now = new Date("2026-01-01T12:00:00Z"); + + const setupWithSavedUser = async (user: TUserState) => { + let storedConfig = { + workspaceId: "env_123", + appUrl: "https://my.url", + workspace: { + data: { surveys: [], actionClasses: [] }, + expiresAt: new Date(now.getTime() + 60_000), + }, + user, + filteredSurveys: [], + status: { value: "success", expiresAt: null }, + }; + getInstanceConfigMock.mockReturnValue({ + get: vi.fn(() => storedConfig), + update: vi.fn((next: typeof storedConfig) => { + storedConfig = next; + }), + } as unknown as Promise); + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + (filterSurveys as unknown as Mock).mockReturnValue([]); + + const result = await setup({ + workspaceId: "env_123", + appUrl: "https://my.url", + }); + return { result, storedUser: storedConfig.user }; + }; + + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(now); + }); + + afterEach(() => { + (isNowExpired as unknown as Mock).mockReset(); + vi.useRealTimers(); + }); + + test("keeps a saved user that hasn't expired, without syncing it", async () => { + const savedUser: TUserState = { + data: { + userId: "user_abc", + contactId: "contact_abc", + segments: ["segment_1"], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() + 5000), + }; + + const { result, storedUser } = await setupWithSavedUser(savedUser); + + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).not.toHaveBeenCalled(); + expect(storedUser).toEqual(savedUser); + }); + + test("resets an expired saved user without a userId to the default, without syncing", async () => { + const savedUser: TUserState = { + data: { + userId: null, + contactId: null, + segments: [], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() - 5000), + }; + + const { result, storedUser } = await setupWithSavedUser(savedUser); + + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).not.toHaveBeenCalled(); + expect(storedUser).toEqual(DEFAULT_USER_STATE_NO_USER_ID); + }); + }); + test("resets config if no valid config found, fetches workspace state, sets default user", async () => { const mockConfig = { get: () => {