From f8c32d22dc0b5b2e945c66d54761d9e4dfa8a286 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:13:13 +0000 Subject: [PATCH 1/2] fix: skip setup only while the error state is still in its back-off window [ENG-7265] shouldReturnEarlyForErrorState skipped setup once the error state had expired and retried while it was still active. Invert the check, and make isNowExpired read the ISO strings that dates become after AsyncStorage, so the fixed check cannot skip forever on a reloaded config. The error-state tests now run the real isNowExpired instead of a mock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011A96cuRpyd6PjGE9yABjux --- packages/react-native/src/lib/common/setup.ts | 2 +- .../src/lib/common/tests/setup.test.ts | 111 +++++++++++------- .../src/lib/common/tests/utils.test.ts | 20 ++++ packages/react-native/src/lib/common/utils.ts | 6 +- 4 files changed, 96 insertions(+), 43 deletions(-) diff --git a/packages/react-native/src/lib/common/setup.ts b/packages/react-native/src/lib/common/setup.ts index 7c76e20..f4addc7 100644 --- a/packages/react-native/src/lib/common/setup.ts +++ b/packages/react-native/src/lib/common/setup.ts @@ -226,7 +226,7 @@ const shouldReturnEarlyForErrorState = ( if (existingConfig?.status.value === "error") { logger.debug("Formbricks was set to an error state."); const expiresAt = existingConfig.status.expiresAt; - if (expiresAt && isNowExpired(expiresAt)) { + if (expiresAt && !isNowExpired(expiresAt)) { logger.debug("Error state is not expired, skipping setup"); return true; } 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 0ed44f2..09e2bdd 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -251,62 +251,93 @@ describe("setup.ts", () => { ); }); - test("skips setup if existing config is in error state and not expired", async () => { - const mockConfig = { + describe("error state back-off", () => { + const errorConfig = (expiresAt: Date | string) => ({ get: vi.fn().mockReturnValue({ workspaceId: "env_123", appUrl: "https://my.url", workspace: {}, user: { data: {}, expiresAt: null }, - status: { value: "error", expiresAt: new Date(Date.now() + 10000) }, + status: { value: "error", expiresAt }, }), - }; + }); - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); + beforeEach(async () => { + // Exercise the real expiry check instead of pinning a mocked answer. + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + }); - (isNowExpired as unknown as Mock).mockReturnValue(true); + test.each([ + ["a Date", new Date(Date.now() + 5 * 60000)], + // Configs read back from AsyncStorage carry dates as ISO strings. + ["an ISO string", new Date(Date.now() + 5 * 60000).toISOString()], + ])("skips setup while the error state has not expired (%s)", async (_, expiresAt) => { + getInstanceConfigMock.mockReturnValue( + errorConfig(expiresAt) as unknown as Promise, + ); - 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(true); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Formbricks was set to an error state.", + ); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Error state is not expired, skipping setup", + ); + expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup"); }); - expect(result.ok).toBe(true); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Formbricks was set to an error state.", - ); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Error state is not expired, skipping setup", - ); - }); - test("proceeds if error state is expired", async () => { - const mockConfig = { - get: vi.fn().mockReturnValue({ + test.each([ + ["a Date", new Date(Date.now() - 1000)], + ["an ISO string", new Date(Date.now() - 1000).toISOString()], + ])("continues setup once the error state has expired (%s)", async (_, expiresAt) => { + getInstanceConfigMock.mockReturnValue( + errorConfig(expiresAt) as unknown as Promise, + ); + + await setup({ workspaceId: "env_123", appUrl: "https://my.url", - workspace: {}, - user: { data: {}, expiresAt: null }, - status: { value: "error", expiresAt: new Date(Date.now() - 10000) }, // expired - }), - }; + }); - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); + expect(mockLogger.debug).toHaveBeenCalledWith( + "Error state is expired. Continue with setup.", + ); + expect(mockLogger.debug).not.toHaveBeenCalledWith( + "Error state is not expired, skipping setup", + ); + expect(mockLogger.debug).toHaveBeenCalledWith("Start setup"); + }); - const result = await setup({ - environmentId: "env_123", - appUrl: "https://my.url", + test("skips setup inside the window and continues after it", async () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + getInstanceConfigMock.mockReturnValue( + errorConfig( + new Date("2026-01-01T00:10:00Z"), + ) as unknown as Promise, + ); + + vi.setSystemTime(new Date("2026-01-01T00:09:59Z")); + await setup({ workspaceId: "env_123", appUrl: "https://my.url" }); + expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup"); + + vi.setSystemTime(new Date("2026-01-01T00:10:00Z")); + await setup({ workspaceId: "env_123", appUrl: "https://my.url" }); + expect(mockLogger.debug).toHaveBeenCalledWith("Start setup"); + } finally { + vi.useRealTimers(); + } }); - expect(result.ok).toBe(true); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Formbricks was set to an error state.", - ); - expect(mockLogger.debug).toHaveBeenCalledWith( - "Error state is expired. Continue with setup.", - ); }); test("uses existing config if workspaceId/appUrl match, checks for expiration sync", async () => { diff --git a/packages/react-native/src/lib/common/tests/utils.test.ts b/packages/react-native/src/lib/common/tests/utils.test.ts index c350d77..5a0eee9 100644 --- a/packages/react-native/src/lib/common/tests/utils.test.ts +++ b/packages/react-native/src/lib/common/tests/utils.test.ts @@ -9,6 +9,7 @@ import { getDefaultLanguageCode, getLanguageCode, getStyling, + isNowExpired, shouldDisplayBasedOnPercentage, wrapThrowsAsync, } from "@/lib/common/utils"; @@ -489,6 +490,25 @@ describe("utils.ts", () => { // --------------------------------------------------------------------------------- // delayedResult // --------------------------------------------------------------------------------- + describe("isNowExpired()", () => { + test("is false before the expiry and true from it on", () => { + expect(isNowExpired(new Date(Date.now() + 60000))).toBe(false); + expect(isNowExpired(new Date(Date.now() - 1))).toBe(true); + }); + + test("reads an ISO string, the shape a date has after AsyncStorage", () => { + const future = JSON.parse( + JSON.stringify(new Date(Date.now() + 60000)), + ) as unknown as Date; + const past = JSON.parse( + JSON.stringify(new Date(Date.now() - 60000)), + ) as unknown as Date; + + expect(isNowExpired(future)).toBe(false); + expect(isNowExpired(past)).toBe(true); + }); + }); + describe("delayedResult()", () => { test("returns the value after the delay", async () => { const result = await delayedResult(10, 10); diff --git a/packages/react-native/src/lib/common/utils.ts b/packages/react-native/src/lib/common/utils.ts index b5f5140..01e1eff 100644 --- a/packages/react-native/src/lib/common/utils.ts +++ b/packages/react-native/src/lib/common/utils.ts @@ -228,8 +228,10 @@ export const shouldDisplayBasedOnPercentage = ( return Math.random() * 100 < displayPercentage; // NOSONAR: Math.random() is sufficient for non-security survey display logic }; -export const isNowExpired = (expirationDate: Date): boolean => { - return new Date() >= expirationDate; +// A date read back from AsyncStorage is an ISO string, so normalise before comparing: +// `new Date() >= "2026-…"` compares a number with NaN and is always false. +export const isNowExpired = (expirationDate: Date | string): boolean => { + return Date.now() >= new Date(expirationDate).getTime(); }; export const delayedResult = async (value: T, ms: number): Promise => { From 6db15a620f4f257dd3a9bd5cee1c4da38970ac9d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:15:50 +0000 Subject: [PATCH 2/2] fix: load the error state a failed first setup stores, so the back-off applies [ENG-7265] handleErrorOnFirstSetup stores only `{ status }`. loadFromStorage read `workspace.expiresAt` unguarded, threw, and dropped the config, so setup never saw the error state and retried on every call. Guard the workspace read and add a round-trip test. Review follow-ups: reset the isNowExpired mock after the back-off tests, give isNowExpired its own section in utils.test.ts, and assert the result of the continue-setup case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011A96cuRpyd6PjGE9yABjux --- .../react-native/src/lib/common/config.ts | 5 ++- .../src/lib/common/tests/config.test.ts | 17 +++++++++ .../src/lib/common/tests/setup.test.ts | 7 +++- .../src/lib/common/tests/utils.test.ts | 38 +++++++++---------- 4 files changed, 45 insertions(+), 22 deletions(-) diff --git a/packages/react-native/src/lib/common/config.ts b/packages/react-native/src/lib/common/config.ts index 8f55b4a..7cd519f 100644 --- a/packages/react-native/src/lib/common/config.ts +++ b/packages/react-native/src/lib/common/config.ts @@ -105,8 +105,9 @@ export class RNConfig { // check if the config has expired if ( - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- need to check if expiresAt is set - parsedConfig.workspace.expiresAt && + // A failed first setup stores only the error status, with no workspace, so both can be missing. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- see above + parsedConfig.workspace?.expiresAt && new Date(parsedConfig.workspace.expiresAt) <= new Date() ) { return err(new Error("Config in local storage has expired")); diff --git a/packages/react-native/src/lib/common/tests/config.test.ts b/packages/react-native/src/lib/common/tests/config.test.ts index 2110f16..d6159d2 100644 --- a/packages/react-native/src/lib/common/tests/config.test.ts +++ b/packages/react-native/src/lib/common/tests/config.test.ts @@ -75,6 +75,23 @@ describe("RNConfig", () => { } }); + test("loadFromStorage() reads back the error state a failed first setup writes", async () => { + const expiresAt = new Date(Date.now() + 10 * 60000); + // handleErrorOnFirstSetup stores only the status, with no workspace. + vi.spyOn(AsyncStorage, "getItem").mockResolvedValueOnce( + JSON.stringify({ status: { value: "error", expiresAt } }), + ); + + const result = await configInstance.loadFromStorage(); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.data.status).toEqual({ + value: "error", + expiresAt: expiresAt.toISOString(), + }); + } + }); + test("loadFromStorage() migrates legacy { environmentId, environment } shape", async () => { const { workspaceId, workspace, ...rest } = mockConfig; const legacyStored = { 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 09e2bdd..f70b44c 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -271,6 +271,10 @@ describe("setup.ts", () => { ); }); + afterEach(() => { + (isNowExpired as unknown as Mock).mockReset(); + }); + test.each([ ["a Date", new Date(Date.now() + 5 * 60000)], // Configs read back from AsyncStorage carry dates as ISO strings. @@ -303,11 +307,12 @@ describe("setup.ts", () => { errorConfig(expiresAt) as unknown as Promise, ); - await setup({ + const result = await setup({ workspaceId: "env_123", appUrl: "https://my.url", }); + expect(result.ok).toBe(true); expect(mockLogger.debug).toHaveBeenCalledWith( "Error state is expired. Continue with setup.", ); diff --git a/packages/react-native/src/lib/common/tests/utils.test.ts b/packages/react-native/src/lib/common/tests/utils.test.ts index 5a0eee9..ea36be0 100644 --- a/packages/react-native/src/lib/common/tests/utils.test.ts +++ b/packages/react-native/src/lib/common/tests/utils.test.ts @@ -49,6 +49,25 @@ describe("utils.ts", () => { }); }); + // --------------------------------------------------------------------------------- + // isNowExpired + // --------------------------------------------------------------------------------- + describe("isNowExpired()", () => { + test("is false before the expiry and true from it on", () => { + expect(isNowExpired(new Date(Date.now() + 60000))).toBe(false); + expect(isNowExpired(new Date(Date.now() - 1))).toBe(true); + }); + + test("reads an ISO string, the shape a date has after AsyncStorage", () => { + expect(isNowExpired(new Date(Date.now() + 60000).toISOString())).toBe( + false, + ); + expect(isNowExpired(new Date(Date.now() - 60000).toISOString())).toBe( + true, + ); + }); + }); + // --------------------------------------------------------------------------------- // wrapThrowsAsync // --------------------------------------------------------------------------------- @@ -490,25 +509,6 @@ describe("utils.ts", () => { // --------------------------------------------------------------------------------- // delayedResult // --------------------------------------------------------------------------------- - describe("isNowExpired()", () => { - test("is false before the expiry and true from it on", () => { - expect(isNowExpired(new Date(Date.now() + 60000))).toBe(false); - expect(isNowExpired(new Date(Date.now() - 1))).toBe(true); - }); - - test("reads an ISO string, the shape a date has after AsyncStorage", () => { - const future = JSON.parse( - JSON.stringify(new Date(Date.now() + 60000)), - ) as unknown as Date; - const past = JSON.parse( - JSON.stringify(new Date(Date.now() - 60000)), - ) as unknown as Date; - - expect(isNowExpired(future)).toBe(false); - expect(isNowExpired(past)).toBe(true); - }); - }); - describe("delayedResult()", () => { test("returns the value after the delay", async () => { const result = await delayedResult(10, 10);